Class Util
- Author:
- Olivier Dedieu, Jean-Philippe Encausse, Olivier Jaquemet, Nicolas Dos Santos
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final HashMapstatic final HashMapstatic final TreeSetThe empty TreeSet (immutable).
UseemptyTreeSet()for generics compliance.static final charstatic intprotected static org.apache.oro.text.regex.Perl5Compilerprotected static org.apache.oro.text.regex.Patternprotected static org.apache.oro.text.regex.Perl5Substitutionstatic final Stringstatic final StringRegular expressions used to manually validate URL authorities if IANA domain name validation isn't desired. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Collection<T> addAll(Collection<T> collection, Enumeration<T> enu) Add all element of the enumerate to the collection return the collection modified.static <T> Collection<T> addAll(Collection<T> collection, Iterator<T> it) Add all element of the iterator to the collection return the collection modified.static <T> Collection<T> addAll(T[] array, Collection<T> coll) Copy all non-null objects from the given array to given collection.static <T> T[]addAll(T[] array1, T... otherArrays) Adds all the elements of the given arrays into a new array.static <K,V> void addInMapHashSet(Map<K, Set<V>> map, K key, V value) A convenient method that add the given value to a set bound to the given key in the given map.static <K,V> void addInMapLinkedHashSet(Map<K, LinkedHashSet<V>> map, K key, V value) A convenient method that add the given value to a set bound to the given key in the given map.static booleanarrayContains(Object[] array, Object key) Test if an array contains a given object.static StringbuildCamelID(String str) Build a Camel Case ID from the given String: remove the blanks, unaccentuates, removes non-alphanum chars.static StringBuild an ID from the given String: replaces the blanks with '_', unaccentuates, removes non-alphanum chars and lowercases.static StringBuild an ID from the given String: replaces the blanks with '_', unaccentuates, removes chars out of the given range and lowercases.static StringBuild an ID from the given String: replaces the blanks with '_', unaccentuates, removes non-alphanum chars and lowercases.static <T> Collection<T> cleanCollection(Collection<T> coll) Remove the null entries of the given collection.static <K,V> Map <K, V> Removes all the entry of the given map with an empty valuestatic Object[]cleanObjectArray(Object[] array) Creates a new array that contains all elements of the given array without null.static String[]cleanStringArray(String[] array) Creates a new array that contains all elements of the given array except empty Strings (ie null or empty).static <T> Set<T> collectionToCleanSet(Collection<T> coll) Returns a set which contains all the non empty element of the given collection.static <K,V> Map.Entry <K, V> compareMap(Map<K, V> map1, Map<K, V> map2) Returns the first common Map.Entry of the given maps.static StringConceal the given string with an internally choosen encryption algorithm.
WARNING: This method is not mathematically safe and is only used to hide sensitive data on first look.static longconvertFileSizeWidgetElt(String value, String unit) Convert a size value and the unit in which it is expressed into a file size expressed in bytes.static StringDeprecated.static StringDeprecated.using this algorythm for "encryption" is completely unsecure.static StringdecodeBASE64(String str) Decode the given string using BASE64 algorithmstatic StringdecodeCookie(String src) static StringDoes the opposite job of encodeHtmlBasicEntities.static int[]decodeIntArray(String param) static int[]decodeIntArray(String param, char separator) static ObjectdecodeObject(String encoded) Returns the object decoded from the given String.static String[]decodeStringArray(String param) static String[]decodeStringArray(String param, char separator) static Stringstatic StringdecryptDES3(String encryptedStr) Decrypt the specified string using DESedeStringEncrypterusing same internal key used byencryptDES3(String).static final <T> TreeSet<T> Returns the empty TreeSet (immutable).static StringencodeBASE64(String str) Encode the given string using BASE64 algorithm.static StringencodeBASE64(String str, boolean isChunck) Encode the given string using BASE64 algorithm.static StringencodeCookie(String src) static StringEncode given string according to the following table.static StringencodeIntArray(int[] array) static StringencodeIntArray(int[] array, char separator) static StringencodeObject(Object obj) Returns the encoded objected as a String.static StringencodeStringArray(String[] array) static StringencodeStringArray(String[] array, char separator) static StringSame implementation asURLEncoder.encode(String, String), but space is encoded with %20 and '/' is not encoded.static StringSame implementation asURLEncoder.encode(String, String), but space is encoded with %20 and '/' is not encoded.static StringSame implementation asURLEncoder.encode(String, Charset), but space is encoded with %20 and '/' is not encoded.static StringencryptDES3(String clearStr) Encrypt the specified string using DESedeStringEncrypterwith an internal key.
WARNING: This method is not mathematically safe and is only used to hide sensitive data on first look.static StringDoes the opposite of isoLatin1ToEntities.static StringescapeBackslash(String str) Escape all the '\' in the given String ('\\')static StringescapeChars(String str, String charsToEscape) Escape specified characters in a String.static StringescapeHtml(String str) Escapes some special HTML characters such as <, >, & and ".static StringDeprecated.use com.jalios.jcms.HttpUtil.encodeForJavaScriptstatic StringEscape all the invalid char in Java String: '\' -> "\\" CR -> "\n" '"' -> \"static StringescapeLuceneQuery(String str) Escape Lucene special chars used in classic QueryParser.static StringescapePercent(String url) This method replace % in wrong hexa character by '_' characterstatic StringescapeRegexp(String string) Escape a (OROMatcher) regular expression with support of basic regexp (* and ?).static StringescapeRegexp(String string, boolean basicRegexp) Escape a (OROMatcher) regular expression with support of basic regexp (* and ?).static intExecutes the specified command and arguments in a separate process.static intexec(String[] cmdarray, OutputStream stdout, OutputStream stderr) Executes the specified command and arguments in a separate process.static intexec(String[] cmdarray, StringBuilder stdout, StringBuilder stderr) Executes the specified command and arguments in a separate process.static intExecutes the specified command and arguments in a separate process.static booleanforceFullGarbageCollection(long timeout) Force the garbage collectionstatic StringformatFileSize(long size) This method format the given size on the greatest unit.static StringformatFileSize(long size, Locale locale) This method format the given size on the greatest unit.static StringformatFileSize(long size, Locale locale, boolean htmlDisplay) This method format the given size on the greatest unit.static StringformatSize(long size, Locale locale) This method format the given number using International System prefix (aka metric system).static StringGenerates a basic password (consonnants / voyels) of 8 characters.static StringgeneratePassword(int length) Generates a basic password (consonnants / voyels) of the specified length.static StringgeneratePronounceablePassword(int pwdLength) Generates pronounceable passwords of specified length.static SetgetAllChildren(TreeNode node, Set nodeSet) Fill the given set with every children of the given treenode, including the node itself, returns the filled set.static TreeSetgetAllChildrenSet(TreeNode node) Returns a TreeSet with all children of the given treenode, (including the node itself)static <T> ArrayList<T> getArrayList(boolean skipNull, boolean trim, T... array) static <T> ArrayList<T> getArrayList(T... array) Returns a new ArrayList filled with the given objects (skip null object).getBatchSet(Collection<T> coll, int batchSize) Convenient method to convert a Collection of object into many smaller collections allowing batch processing.static booleangetBoolean(boolean[] array, int index, boolean defaultValue) static byte[]getBytesUtf8(String string) Encodes the specifiedStringinto a sequence of bytes using the given UTF-8 charset, storing the result into a new byte array.static ObjectgetChildListMap(Map map, String key) Returns the first Value matching the given keystatic ListgetChildrenListMap(Map map, String key) Returns values matching the given key.static ListgetChildrenListMap(Map map, String[] keys) Returns a new List of values matching the ordered given keys.getClassFiles(String realPath, String fullname, boolean java) Returns a Set of relative path to all class files including inner class and java.static StringgetClassNameFromFilename(String filename) Returns the class name from the filename of a class (e.g.static StringgetClassShortName(Class clazz) Returns the short name of the given class (e.g.static StringgetClassShortName(Object object) Returns the short name of the given object's class (e.g.static StringgetClassShortName(String fullname) Returns the short name of the given class name (e.g.static <K,V> Map <K, V> getCleanMap(Map<K, V> map) Returns a copy of the given map without the entry with an empty value.
The copy preserves the type for TreeMap, LinkedHashMap and HashMap.static Class<?> getCommonSuperClass(Class<?>... classes) Retrieve the common super class of the specified classes.static StringReturns the current StackTrace in a String.static String[]getFileSizeUnitHTMLLabels(Locale locale) Retrieve an array containing I18Ned labels to express file size, from bytes to petabytes.static String[]getFileSizeUnitLabels(Locale locale) Retrieve an array containing I18Ned labels to express file size, from bytes to petabytes.static String[]getFileSizeWidgetElt(long size) Convert a file size to a rounded value with a size as a string and the unit in which it is expressed (units are in english).static String[]getFileSizeWidgetUnit(Locale locale) Retrieve an array containing I18Ned labels to express file size, from bytes to petaabytes.static <T> TgetFirst(Collection<T> coll) Returns the first item of the given collection (or null if the collection is empty).static <T> TgetFirst(T[] array) Returns the first item of the given array (or null if the array is empty).static ClassgetFirstCommonClass(Class parent, Class child) Follow class tree of parent to find a class or an interface that is also parent of the child.static StringgetFirstSentences(String text, int limit) Get the first sentences in a given string.static <K,V> HashMap <K, V> getHashMap(Map<K, V> map) Returns a new HashMap filled with the given map (if it is not null)static <K,V> HashMap <K, V> getHashMap(K key, V value) Returns a new HashMap filled with the given key/value pair (if the key is not null).static <T> HashSet<T> getHashSet(T... array) Returns a new HashSet filled with the given objects (skip null object).static intgetInt(int[] array, int index, int defaultValue) static intstatic <K,V> Object Iterate over a Map, looking for a Key associated to a given value.static <K,V> Set <K> Iterate over a Map, looking for a Keys associated to a given value.static <T> TReturns the last item of the given List (or null if the List is empty).static <T> TReturns the last item of the given SortedSet (or null if the SortedSet is empty).static <T> TgetLast(T[] array) Returns the last item of the given array (or null if the array is empty).static <K,V> LinkedHashMap <K, V> getLinkedHashMap(Map<K, V> map) Returns a new LinkedHashMap filled with the given map (if it is not null)static <K,V> LinkedHashMap <K, V> getLinkedHashMap(K key, V value) Returns a new LinkedHashMap filled with the given key/value pair (if the key is not null).static StringReturn the group matching the given regexp for the given String or null if do not match or exception happensstatic StringReturn the group matching the given regexp for the given String or null if do not match or exception happensstatic <T> TgetNext(Collection<T> coll, T item) Returns the next item of the given collection (or null if the collection is empty).static <T> TgetNext(T[] array, T item) Returns the next item of the given array (or null if the array is empty).static ObjectgetPackageClassFiles(String realPath, String fullPackage, boolean sources, String excludesPattern) Returns a Set of relative path to all class files including inner class and java.static intgetSize(boolean[] array) Returns the size of the given array.static intgetSize(byte[] array) Returns the size of the given array.static intgetSize(char[] array) Returns the size of the given array.static intgetSize(double[] array) Returns the size of the given array.static intgetSize(float[] array) Returns the size of the given array.static intgetSize(int[] array) Returns the size of the given array.static intgetSize(long[] array) Returns the size of the given array.static intgetSize(short[] array) Returns the size of the given array.static intReturns the size of the given array.static intReturns the size of the given String.static intgetSize(Collection coll) Returns the size of the given collection.static intReturns the size of the given map.static StringgetStackTrace(Throwable throwable) This method print the stack trace into a String and return it.static StringCall the method getString() with the Object in the array specified at the given index.static StringReturn the String representation of the given object if it is not null nor empty, otherwise it returns the default value.static StringgetStringUtf8(byte[] bytes) static ListgetSuperclassList(Class clazz, Class ancestor, boolean addClass, boolean addAncestor) Returns a list of classes the given class is an ancestor of.static TreeSetgetTreeDescendantSet(TreeNode node) Returns a TreeSet with all descendant of the given treenode, (excluding the node itself)static SetgetTreeDescendantSet(TreeNode node, Set nodeSet) static <K,V> TreeMap <K, V> getTreeMap(Map<K, V> map) Returns a new TreeMap filled with the given map (if it is not null)static <K,V> TreeMap <K, V> getTreeMap(K key, V value) Returns a new TreeMap filled with the given key/value pair (if the key is not null).static <T> TreeSet<T> getTreeSet(T... array) Returns a new TreeSet filled with the given objects (skip null object).static booleanhasAppenderDefined(org.apache.log4j.Logger logger) Checks if the givenLoggerhas any appender defined.static Stringhtml2Ascii(String str) Deprecated.since jcms-9.0.0static intSearches for the first occurrence of the given argument in a given array, testing for equality using theequalsmethod.static boolean[]insertArray(boolean[] array, int index, boolean elt) Insert an element into a boolean array and return a duplicate copy of it.static int[]insertArray(int[] array, int index, int elt) Insert an element into an int array and return a duplicate copy of it.static Object[]insertArray(Object[] array, int index, Object elt) Insert an element into an Object array and return a duplicate copy of it.static <K,V> Map <? extends K, ? extends V> This method will return a new Map containing only values of specified map with given keys.static SetReturns the intersection of an array ofSet.static SetReturns the intersection of twoSet.static SetReturns the intersection of threeSet.static booleanisChildNode(TreeNode node, TreeNode child) Test if a node is a child of an other node
Return false if child == nodestatic booleanisConcealed(String str) static booleanisEmpty(boolean[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(byte[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(char[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(double[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(float[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(int[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(long[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(short[] array) Returnstrueif this array isnullor empty.static booleanisEmpty(SQLQueryResult sqr) Returnstrueif this SQLQueryResult isnullor empty.static booleanReturnstrueif this file isnullor empty.static booleanisEmpty(File file, FileFilter fileFilter) Returnstrueif this file isnullor empty.static booleanReturnstrueif this object isnullor empty.static booleanReturnstrueif this array isnullor empty.static booleanReturnstrueif this array isnullor empty.static booleanReturnstrueif this string isnullor empty (once trimmed).static booleanisEmpty(Collection<?> c) Returnstrueif this collection isnullor empty.static booleanisEmpty(Collection<?> c, boolean deep) Returnstrueif this collection isnullor empty.static booleanReturnstrueif this map isnullor empty.static <K,V> boolean isMapFilled(Map<K, V> map) Returns true if the given map contains at least one value not empty.static booleanisNodeChild(TreeNode parentNode, TreeNode child) Test if a node is a child of an other node
Return false if child == node.static booleanReturns true if the given string only contains 0-9 charactersstatic StringConvert all the isoLatin1 accent into XML entities (e.g.static booleanisSameContent(boolean[] array1, boolean[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(byte[] array1, byte[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(char[] array1, char[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(double[] array1, double[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(float[] array1, float[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(int[] array1, int[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(long[] array1, long[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(short[] array1, short[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(Object[] array1, Object[] array2) Returns true if array1 has same content than array2.static booleanisSameContent(String str1, String str2) Returns true if str1 has same content than str2.static booleanisSameContent(Collection col1, Collection col2) Returns true if col1 has same content than col2.static booleanisSameContent(Date date1, Date date2) Returns true if date1 has same content than date2.static booleanisSameContent(List list1, List list2) Returns true if list1 has same content than list2.static booleanisSameContent(Map map1, Map map2) Returns true if map1 has same content than map2.static booleanisSameContent(Set set1, Set set2) Returns true if set1 has same content than set2.static booleanisSameContent(org.jdom.Element elt1, org.jdom.Element elt2) Returns true if elt1 has same content than elt2.static booleanisValidEmail(String email) Checks that the given email is empty or has a valid email syntax.static booleanisValidEmail(String[] emails) Returns true if all the given emails are either null, empty or valid.static booleanisValidEmail(Collection<String> emails) Returns true if all the given emails are either null, empty or valid.static booleanisValidEmail(Map emailMap) Returns true if all the given emails contained as value of the map are either null, empty or valid.static booleanisValidString(String[] strings, Predicate<String> p) Returns true if all the given strings are either null, empty or valid.static booleanisValidString(String string, Predicate<String> p) Return true if the given string is null, empty or valid.static booleanisValidString(Collection<String> strings, Predicate<String> p) Returns true if all the given strings are either null, empty or valid.static booleanisValidString(Map stringMap, Predicate<String> p) Returns true if all the given strings contained as value of the map are either null, empty or valid.static booleanisValidUri(String uri) Return true if the given uri is null, empty or valid.static booleanisValidUri(String[] uris) Returns true if all the given uris are either null, empty or valid.static booleanisValidUri(Collection<String> uris) Returns true if all the given uris are either null, empty or valid.static booleanisValidUri(Map uriMap) Returns true if all the given uris contained as value of the map are either null, empty or valid.static booleanisValidUrl(String url) Return true if the given url is null, empty or valid.static booleanisValidUrl(String[] urls) Returns true if all the given urls are either null, empty or valid.static booleanisValidUrl(Collection<String> urls) Returns true if all the given urls are either null, empty or valid.static booleanisValidUrl(Map urlMap) Returns true if all the given urls contained as value of the map are either null, empty or valid.static StringJoins an array of boolean with the given separator.static StringJoins an array of boolean with the given separator.static StringJoins an array of double with the given separator.static StringJoins an array of double with the given separator.static StringJoins an array of int with the given separator.static StringJoins an array of int with the given separator.static StringJoins an array of long with the given separator.static StringJoins an array of long with the given separator.static StringJoins an array of String with the given separator.static StringJoins an array of String with the given separator.static StringJoin all specified strings with a space separator.static Stringjoin(Collection<?> coll, int maxFirst, int maxLast) Joins a collection of object but returns only the first ones and the last ones.static Stringjoin(Collection<?> col, String sep) Joins a collection of Object with the given separator into a String.static Stringjoin(Collection<?> col, String sep, int max, String suffix) Joins a collection of Object with the given separator into a String.static StringJoins a collection of Object with the given separator into a String.static StringJoins a collection of Object with the given separator into a String.static StringJoins the entries of a map into a String.static MapReturns the Map from the given JSON.static voidlistDictionary(Dictionary<?, ?> dict) Lists a Dictionnary onSystem.out.static voidlistDictionary(Dictionary<?, ?> dict, PrintStream out) Lists a Dictionnary on the givenPrintStream.static voidlistDictionary(Dictionary<?, ?> dict, PrintStream out, String sep) Lists a dictionnary on the givenPrintStreamwith the given separator.static voidLists a map onSystem.out.static voidlistMap(Map<?, ?> map, PrintStream out) Lists a map on the givenPrintStream.static voidlistMap(Map<?, ?> map, PrintStream out, String sep) Lists a map on the givenPrintStreamwith the given separator.static voidmainRemoveArray(String[] args) static voidmainSwapArray(String[] args) static voidmainTestBuildID(String[] args) static voidmainTestEmpty(String[] args) static voidmainTestGeneratePassword(String[] args) static voidmainTestJoin(String[] args) static StringReturns the JSON for the given Map.static StringCalculates the MD5 digest and returns the value as a base64 string.static doublemean(Collection<? extends Number> values) Returns the mean of the collection of values.static <T> Set<T> Merge the variations of sets that have diverged from the same original set.static booleannotEmpty(int[] array) Returnstrueif this array is notnullnor empty.static booleannotEmpty(SQLQueryResult map) Returnstrueif this SQLQueryResult is notnullnor empty.static booleanReturnstrueif this File is notnullnor empty.static booleannotEmpty(File file, FileFilter fileFilter) Returnstrueif this File is notnullnor empty.static booleanReturnstrueif this object is notnullnor empty.static booleanReturnstrueif this array is notnullnor empty.static booleanReturnstrueif this array is notnullnor empty.static booleanReturnstrueif this string is notnullnor empty (once trimmed).static booleannotEmpty(Collection<?> c) Returnstrueif this collection is notnullnor empty.static booleanReturnstrueif this map is notnullnor empty.static DoubleparseDouble(String str) Parse string into Double.static StringperformDecoding(String src, HashMap transMap) Replace all occurences of values found in transMap with their assiocated keys.static StringperformEncodeDecode(String src, HashMap transMap, boolean decode) Encode or decode the given String using the given translation Map.static StringperformEncoding(String src, HashMap transMap) Replace all occurences of keys found in transMap with their assiocated values.Prefix all elements of a Set of String with a given prefixstatic <K,V> Map <K, V> Copy all non-null objects from the given array to given map with a given value.static StringrandomString(int length) static Stringrecapitalize(String str) Force the first char of a String to be a uppercase char.static StringreduceBlankLines(String text) Right trim all the lines in the message and reduced many CRLF to only one line.static boolean[]removeArray(boolean[] array, int index) Remove an element of an Array of booleanstatic boolean[]removeArray(boolean[] array, int from, int to) Remove n elements of an Array of booleanstatic int[]removeArray(int[] array, int index) Remove an element of an Array of intstatic int[]removeArray(int[] array, int from, int to) Remove n elements of an Array of intstatic Object[]removeArray(Object[] array, int index) Remove an element of an Array of objectstatic Object[]removeArray(Object[] array, int from, int to) Remove n elements of an Array of objectstatic Object[]removeArray(Object[] array, Object obj) Remove an element of an Array of objectstatic StringremoveBlankLines(String str) Cleans the given string : remove pure blank lines and remove leadings white spaces.static <K,V> void removeFromMapHashSet(Map<K, Set<V>> map, K key, V value) A convenient method that remove the given value to a set bound to the given key in the given map.static <K,V> void removeFromMapLinkedHashSet(Map<K, LinkedHashSet<V>> map, K key, V value) A convenient method that remove the given value to a set bound to the given key in the given map.static StringRepeat a String patterncounttimesstatic StringSearch and replace a string by another onestatic Stringreplace(String text, String regexp, RegexpSubstitution substitution) Replaces the given regexp in the given text with the given substitution function.static StringSearch and replace a string by another one (Note the input string must not contains '#' char)static Stringreplace(String input, Pattern regex, MatcherCallback callback) Searches a string for a specified regular expression, and returns a new string where the specified values are replaced.static Stringreplace(String text, org.apache.oro.text.regex.Pattern pattern, RegexpSubstitution substitution) Replaces the given pattern in the given text with the given substitution function.static StringreplaceAll(String input, String searchString, String replaceString) Replace all occurrences of searchString with replaceString in input string.static StringReveal the specified hidden string with an internally choosen encryption algorithm.static <K,V> Map <V, K> reverseMap(Map<K, V> originalMap, Map<V, K> reverseMap) Fill the reverse map with the original map replacing keys by values and values by keys.Slices the given list in a list of sub list containing less than max value per list.static String[]Splits a String into an array of String.static String[]Splits a String into an array of String.static <T extends Collection>
List<T> splitCollection(T coll, int max) Split the given collection in sub collections having max elements.static int[]splitToIntArray(String str, String delim) Splits a String into an array of int.splitToList(String str, String delim) Splits a String into a list of String.static String[]splitWithPattern(String text, String pattern) Splits a String according a given pattern and returns an array of String.static StringstartsWith(String str, Collection<String> coll) Returns the String in the given collection that is a starting string og given strstringArrayToCleanSet(String[] array) Returns a set which contains all the non empty cells of the given array.static <K,V> Map <K, V> This method will return a new Map containing all values of specified map without given keys.static SetReturns the subset of an array ofSet.static SetReturns the subset of an array ofSet.static SetReturns the subset of an array ofSet.static doublesum(Collection<? extends Number> values) Returns the sum of the collection of numbers.static StringSurround a given text (the first argument) with the two other arguments, only if the given text is not empty.static StringsurroundWithTag(String inside, String tag) Surround a given text (the first argument) with a html tag.static boolean[]swapArray(boolean[] array, int from, int to, boolean roll, boolean copy) Swap two cells of a boolean array.static int[]swapArray(int[] array, int from, int to, boolean roll, boolean copy) Swap two cells of an int array.static Object[]Swap two cells of an Object array.static Object[]Converts an object value to an arrays ofObject.static booleanConvert an Object (assert to be either a String or a Boolean) to a booleanstatic byteConvert an Object (assert to be either aStringor aByte) to abytestatic charConvert an Object (assert to be either aStringor aCharacter) to acharstatic DateParse a String and Convert it into a Datestatic doubleConvert an Object (assert to be either aStringor aDouble) to adoublestatic floatConvert an Object (assert to be either aStringor aFloat) to afloatstatic intConvert an Object (assert to be either aStringor aInteger) to aintstatic int[]toIntArray(Object[] objs, int def) Convert an Object[] (assert to be either aStringor aInteger) to aintstatic IntegerConverts an object value to anInteger.static longConvert an Object (assert to be either aStringor aLong) to alongstatic NumberConverts an object value to aNumber.static Number[]toNumberArray(Object obj, Number[] defaultValues) Converts an object value to aNumberarray.static shortConvert an Object (assert to be either aStringor aShort) to ashortstatic StringConverts an object value to aString.static String[]toStringArray(Object obj, String[] defaultValues) Converts an object value to aStringarray.static StringtoWordLine(String str) Split a text in a String with one word by line (used for diffing 2 strings at word level).static String[]Remove the trailing empty cells of the given String array.static StringTrim the end of a Stringstatic <T> List<T> Returns a copy of the given list without any null values at the end.static String[]trimStringArray(String[] array) Remove the trailing empty cells of the given String array.static StringTruncates the given String.static StringTruncates the given Stringstatic StringReturns a unique truncated string.static StringtruncateHtml(String text, int length, boolean trim) Truncate an HTML string.static StringTruncates the given value to be compliant with standard VARCHAR limit (ie 255 chars)truncateVarchar(List<String> list) Truncates the content of the given list to be compliant with standard VARCHAR limit (ie 255 chars)truncateVarchar(Set<String> set) Truncates the content of the given set to be compliant with standard VARCHAR limit (ie 255 chars)static Stringunaccentuate(String str) Removes all the accentuate chars of the given string.static StringunaccentuateRegexp(String str) Build an unaccentuated version of the given regexp.static Stringuncapitalize(String str) Force the first char of a String to be a lowercase char.static StringunescapeChar(String str) Unescape escaped character in a String.static Set<?> Returns the union of an array ofSet.static SetReturns the union of twoSet.static SetReturns the union of threeSet.static voidupdateListMap(Map map, Object key, Object value, boolean lazy) Updated Map with the given key/value pair.static booleanvalidateRegexp(String regexp) Tell if a String is a valid Perl 5 regexp.static StringWraps a single line of text, identifying words by' '.static StringWraps a single line of text, identifying words by' '.
-
Field Details
-
UNSTABLE_TEST_ENABLED
- See Also:
-
EMPTY_TREESET
The empty TreeSet (immutable).
UseemptyTreeSet()for generics compliance. -
regexpEscaped1
-
regexpEscaped2
-
regexpEscaped3
-
hexaPercentPattern
protected static org.apache.oro.text.regex.Pattern hexaPercentPattern -
hexaPercentSubst
protected static org.apache.oro.text.regex.Perl5Substitution hexaPercentSubst -
hexaPercentCompiler
protected static org.apache.oro.text.regex.Perl5Compiler hexaPercentCompiler -
ESCAPE_CHAR
public static final char ESCAPE_CHAR- See Also:
-
cookieTransTable
-
isoLatin1_xml
-
basicEntitiesEncodingMap
-
basicEntitiesDecodingMap
-
FILE_SIZE_UNIT_DIV
public static int FILE_SIZE_UNIT_DIV -
URL_VALIDATOR_AUTHORITY_REGEX
Regular expressions used to manually validate URL authorities if IANA domain name validation isn't desired.- Since:
- JCMS-6942
- See Also:
-
-
Method Details
-
emptyTreeSet
Returns the empty TreeSet (immutable). Unlike the like-named field, this method is parameterized.This example illustrates the type-safe way to obtain an empty set:
TreeSet<String> s = Util.emptyTreeSet();
- Returns:
- always return the same instance #EMPTY_TREESET
- See Also:
-
getKey
Iterate over a Map, looking for a Key associated to a given value.- Parameters:
map- the Map to searhc onvalue- the value to search- Returns:
- the key associated to a given value
-
getKeys
Iterate over a Map, looking for a Keys associated to a given value.- Parameters:
map- the Map to searhc onvalue- the value to search- Returns:
- a Set of keys associated to a the given value
-
updateListMap
Updated Map with the given key/value pair. Create a List of values if key already exists. If boolean "lazy" is false always create a List.- Parameters:
map- Map to work withkey- Object key of the Mapvalue- Object value of the maplazy- boolean true to create List only after 2 elements
-
getChildListMap
Returns the first Value matching the given key- Parameters:
map- the Mapkey- Object key of the Map- Returns:
- Object or null if key does not match
-
getChildrenListMap
Returns values matching the given key.- Parameters:
map- the Mapkey- Object key of the Map- Returns:
- List or null if key does not match
-
getChildrenListMap
Returns a new List of values matching the ordered given keys.- Parameters:
map- the Mapkeys- Object key of the Map- Returns:
- List or null if key does not match
-
reverseMap
Fill the reverse map with the original map replacing keys by values and values by keys.- Type Parameters:
K- keyV- value- Parameters:
originalMap- original mapreverseMap- reverse map- Returns:
- the reverse map
- Since:
- jcms-4.0
-
compareMap
Returns the first common Map.Entry of the given maps.- Parameters:
map1- the first mapmap2- the second map.- Returns:
- the common entry (from map1) or null.
- Since:
- jcms-5.7.0
-
isMapFilled
Returns true if the given map contains at least one value not empty.- Parameters:
map- the map.- Returns:
- true if the given map contains at least one value not empty.
- Since:
- jcms-5.7.0
-
addAll
Add all element of the enumerate to the collection return the collection modified.- Parameters:
collection-Collectionenu-Enumeration- Returns:
- Collection
- Since:
- jcms-4.0
-
addAll
Add all element of the iterator to the collection return the collection modified.- Parameters:
collection- the collectionit- the iterator- Returns:
- the collection
- Since:
- jcms-6.0.0
-
startsWith
Returns the String in the given collection that is a starting string og given str- Parameters:
str- the String to matchcoll- a Collection of String that may be start of str- Returns:
- The matching starting string or null
- Since:
- jcms-5.7.0
-
getString
Return the String representation of the given object if it is not null nor empty, otherwise it returns the default value.- Parameters:
obj- the objectdefaultValue- the default value- Returns:
- the default value if the given object is null or if obj.toString() is null or empty
-
getString
Call the method getString() with the Object in the array specified at the given index. Check that the index, array are valid.- Parameters:
array- the object arrayindex- the indexdefaultValue- the default value- Returns:
- String
- Since:
- jcms-4.0
-
getObject
-
getInt
public static int getInt(int[] array, int index, int defaultValue) -
getBoolean
public static boolean getBoolean(boolean[] array, int index, boolean defaultValue) -
getSize
Returns the size of the given String. Returns 0 if the String is null.- Parameters:
str- the String.- Returns:
- the size of the given String. Returns 0 if the String is null.
- Since:
- jcms-6.0.0
-
getSize
Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- the array.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-6.0.0
-
getSize
public static int getSize(byte[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of byte.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(short[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of short.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(int[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of int.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(long[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of long.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(float[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of float.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(double[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of double.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(boolean[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of boolean.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
public static int getSize(char[] array) Returns the size of the given array. Returns 0 if the array is null.- Parameters:
array- an array of char.- Returns:
- the size of the given array. Returns 0 if the array is null.
- Since:
- jcms-7.0.0
-
getSize
Returns the size of the given collection. Returns 0 if the collection is null.- Parameters:
coll- the collection.- Returns:
- the size of the given collection. Returns 0 if the collection is null.
- Since:
- jcms-6.0.0
-
getSize
Returns the size of the given map. Returns 0 if the map is null.- Parameters:
map- the map.- Returns:
- the size of the given map. Returns 0 if the map is null.
- Since:
- jcms-6.0.0
-
notEmpty
Returnstrueif this File is notnullnor empty.- Parameters:
file- the file to test- Returns:
- true if the file is not empty.
-
isEmpty
Returnstrueif this file isnullor empty.- Parameters:
file- the file to test- Returns:
- true if the file is empty.
-
notEmpty
Returnstrueif this File is notnullnor empty.- Parameters:
file- the file to testfileFilter- the filter- Returns:
- true if the file is not empty.
-
isEmpty
Returnstrueif this file isnullor empty.- Parameters:
file- the file to testfileFilter- the filter- Returns:
- true if the file is empty.
-
notEmpty
Returnstrueif this object is notnullnor empty.- Parameters:
object- the object to test- Returns:
- true if the object is not empty.
-
isEmpty
Returnstrueif this object isnullor empty.- Parameters:
object- the object to test- Returns:
- true if the object is empty.
-
notEmpty
public static boolean notEmpty(int[] array) Returnstrueif this array is notnullnor empty.- Parameters:
array- the array to test- Returns:
- true
-
isEmpty
public static boolean isEmpty(int[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(long[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(byte[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(short[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(float[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(double[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(boolean[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
isEmpty
public static boolean isEmpty(char[] array) Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
notEmpty
Returnstrueif this array is notnullnor empty.- Parameters:
array- the array to test- Returns:
- true if the array is not empty.
-
isEmpty
Returnstrueif this array isnullor empty.- Parameters:
array- the array to test- Returns:
- true if the array is empty.
-
notEmpty
Returnstrueif this array is notnullnor empty.- Parameters:
array- the array to testrecursive- check if arrays elements are empty- Returns:
- true if the array is not empty.
-
isEmpty
Returnstrueif this array isnullor empty.- Parameters:
array- the array to testrecursive- check if arrays elements are empty- Returns:
- true if the array is empty.
-
notEmpty
Returnstrueif this collection is notnullnor empty.- Parameters:
c- the collection to test- Returns:
- true if the collection is not empty.
-
isEmpty
Returnstrueif this collection isnullor empty.- Parameters:
c- the collection to test- Returns:
- true if the collection is empty.
-
isEmpty
Returnstrueif this collection isnullor empty.- Parameters:
c- the collection to testdeep- to call Util.isEmpty on content otherwise check only == null- Returns:
- true if the collection is empty.
- Since:
- jcms-4.2
-
notEmpty
Returnstrueif this map is notnullnor empty.- Parameters:
map- the map to test- Returns:
- true if the map is not empty.
- Since:
- jcms-4.1
-
isEmpty
Returnstrueif this SQLQueryResult isnullor empty.- Parameters:
sqr- the SQLQueryResult to test- Returns:
- true if the SQLQueryResult is empty.
- Since:
- jcms-4.1
-
notEmpty
Returnstrueif this SQLQueryResult is notnullnor empty.- Parameters:
map- the SQLQueryResult to test- Returns:
- true if the SQLQueryResult is empty.
- Since:
- jcms-4.1
-
isEmpty
Returnstrueif this map isnullor empty.- Parameters:
map- the map to test- Returns:
- true if the map is empty.
- Since:
- jcms-4.1
-
mainTestEmpty
-
join
Joins a collection of Object with the given separator into a String. Uses thetoString()method for each iterated Object.- Parameters:
col- the collectionsep- the separator- Returns:
- a String which contains all the iterated objects.
-
join
Joins a collection of Object with the given separator into a String. Uses thetoString()method for each iterated Object.- Parameters:
col- the collectionsep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- a String which contains all the iterated objects.
- Since:
- jcms-4.0
-
join
Joins a collection of object but returns only the first ones and the last ones.Examples:
Util.join(List.of(1, 2, 3, 4, 5), 1, 1)) => "1, ..., 5"Util.join(List.of(1, 2, 3, 4, 5), 2, 1)) => "1, 2, ..., 5"Util.join(List.of(1, 2, 3, 4, 5), 2, 2)) => "1, 2, 3, 4, 5"Util.join(List.of(1, 2, ...), 2, 0)) => "1, 2, ..."Util.join(List.of(1, 2, 3, 4, 5), 0, 2)) => "..., 4, 5"
- Parameters:
coll- the collectionmaxFirst- the count of first object to printmaxLast- the count of last object to print- Returns:
- a String which contains the maxFirst objects, "...", and the maxList objects.
- Since:
- jcms-10.0.8
-
join
Joins a collection of Object with the given separator into a String. Uses thetoString()method for each iterated Object.- Parameters:
it- the iterator of the collectionsep- the separator- Returns:
- a String which contains all the iterated objects.
-
join
Joins a collection of Object with the given separator into a String. Uses thetoString()method for each iterated Object.- Parameters:
it- the iterator of the collectionsep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- a String which contains all the iterated objects.
- Since:
- jcms-4.0
-
joinMap
public static String joinMap(Map<? extends Object, ? extends Object> map, String keyValueSep, String entrySep) Joins the entries of a map into a String.Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("simpleobject", "bar"); map.put("stringarray", new String[] { "hi", "hello" } ); List<Object> list = new ArrayList<Object>(); list.add("John"); list.add("Doe"); map.put("collection", list ); String output = "{" + Util.joinMap(map, "=>", ", ") + "}"; output == "{ simpleobject=>bar, stringarray=>[hi, hello], collection=>[John, Doe] }"- Parameters:
map- the map to join akeyValueSep- the separator to use between key and the valueentrySep- the separator to use between each entry- Returns:
- a new string (returns an empty string if map was null or empty)
-
listMap
Lists a map onSystem.out.- Parameters:
map- the map to list
-
listMap
Lists a map on the givenPrintStream.- Parameters:
map- the map to listout- the PrintStream to use to list the map
-
listMap
Lists a map on the givenPrintStreamwith the given separator.- Parameters:
map- the map to listout- the PrintStream to use to list the mapsep- the separator
-
listDictionary
Lists a Dictionnary onSystem.out.- Parameters:
dict- the Dictionnary to list
-
listDictionary
Lists a Dictionnary on the givenPrintStream.- Parameters:
dict- the Dictionnary to listout- the PrintStream to use to list the dictionnary
-
listDictionary
Lists a dictionnary on the givenPrintStreamwith the given separator.- Parameters:
dict- the dictionnary to listout- the PrintStream to use to list the dictionnarsep- the separator
-
subMap
This method will return a new Map containing all values of specified map without given keys.- Parameters:
map- Map to work onkeys- Set of key to remove- Returns:
- Map a new HashMap or TreeMap contain map values without specified keys
-
interMap
public static <K,V> Map<? extends K,? extends V> interMap(Map<? extends K, ? extends V> map, Set<? extends K> keys) This method will return a new Map containing only values of specified map with given keys.- Parameters:
map- Map to work onkeys- Set of key- Returns:
- Map a new HashMap or TreeMap contain map values with specified keys
-
prefixSet
Prefix all elements of a Set of String with a given prefix- Parameters:
set- Set of Stringprefix- a String to prefix- Returns:
- Set a new set
-
unionSet
Returns the union of an array ofSet. The result set does not contains null item.- Parameters:
sets- an array ofSet- Returns:
- the union
Set(same class as the first set)
-
unionSet
Returns the union of twoSet.- Parameters:
set1- the firstSetset2- the secondSet- Returns:
- the union
Set
-
unionSet
Returns the union of threeSet.- Parameters:
set1- the firstSetset2- the secondSetset3- the thridSet- Returns:
- the union
Set
-
interSet
Returns the intersection of an array ofSet.- Parameters:
sets- an array ofSet- Returns:
- a new
Set(same class as the first set, with same comparator for TreeSet) containing only element presents in all the given set. does not return a new set if only one set was given, instead return the given set.
-
interSet
Returns the intersection of twoSet.- Parameters:
set1- the firstSetset2- the secondSet- Returns:
- the intersection
Set
-
interSet
Returns the intersection of threeSet.- Parameters:
set1- the firstSetset2- the secondSetset3- the thridSet- Returns:
- the intersection
Set
-
subSet
Returns the subset of an array ofSet. The subset contains all the elements of the firstSetwithout those of the otherSet.- Parameters:
sets- an array ofSet- Returns:
- the subset
Set(same class as the first set)
-
subSet
Returns the subset of an array ofSet. The subset contains all the elements of the firstSetwithout those of the secondSet.- Parameters:
set1- the firstSetset2- the secondSet- Returns:
- the subset
Set
-
subSet
Returns the subset of an array ofSet. The subset contains all the elements of the firstSetwithout those of the second and thirdSet.- Parameters:
set1- the firstSetset2- the secondSetset3- the thirdSet- Returns:
- the subset
Set
-
mergeSet
Merge the variations of sets that have diverged from the same original set.- Type Parameters:
T- any type- Parameters:
originalSet- the original setsets- the new sets that have diverged from the original set- Returns:
- the merge of the new sets based on originalSet.
- Since:
- jcms-10.0.6
-
getArrayList
Returns a new ArrayList filled with the given objects (skip null object).- Type Parameters:
T- any type- Parameters:
array- a varargs of objects- Returns:
- a new ArrayList filled with the given objects.
- Since:
- jcms-6.1.0
-
getArrayList
@SafeVarargs public static <T> ArrayList<T> getArrayList(boolean skipNull, boolean trim, T... array) - Type Parameters:
T- any type- Parameters:
skipNull- remove null objecttrim- if true remove the null at the end of the arrayarray- a varargs of objects- Returns:
- a new ArrayList filled with the given objects.
- Since:
- jcms-7.1.0
-
getHashSet
Returns a new HashSet filled with the given objects (skip null object).- Type Parameters:
T- any type- Parameters:
array- a varargs of objects- Returns:
- a new HashSet filled with the given objects.
- Since:
- jcms-6.0.1
-
getTreeSet
Returns a new TreeSet filled with the given objects (skip null object).- Type Parameters:
T- any type- Parameters:
array- a varargs of objects- Returns:
- a new TreeSet filled with the given objects.
- Since:
- jcms-6.0.1
-
getHashMap
Returns a new HashMap filled with the given key/value pair (if the key is not null).- Type Parameters:
K- any typeV- any type- Parameters:
key- the first key to be addedvalue- the first value to be added- Returns:
- a HashMap filled with the given key/value pair.
- Since:
- jcms-5.7.3
-
getHashMap
Returns a new HashMap filled with the given map (if it is not null)- Type Parameters:
K- any typeV- any type- Parameters:
map- the map to be added- Returns:
- a new HashMap filled with the given map.
- Since:
- jcms-6.0.0
-
getTreeMap
Returns a new TreeMap filled with the given key/value pair (if the key is not null).- Type Parameters:
K- any typeV- any type- Parameters:
key- the first key to be addedvalue- the first value to be added- Returns:
- a TreeMap filled with the given key/value pair.
- Since:
- jcms-5.7.3
-
getTreeMap
Returns a new TreeMap filled with the given map (if it is not null)- Type Parameters:
K- any typeV- any type- Parameters:
map- the map to be added- Returns:
- a new TreeMap filled with the given map.
- Since:
- jcms-6.0.0
-
getLinkedHashMap
Returns a new LinkedHashMap filled with the given key/value pair (if the key is not null).- Type Parameters:
K- any typeV- any type- Parameters:
key- the first key to be addedvalue- the first value to be added- Returns:
- a LinkedHashMap filled with the given key/value pair.
- Since:
- jcms-5.7.3
-
getLinkedHashMap
Returns a new LinkedHashMap filled with the given map (if it is not null)- Type Parameters:
K- any typeV- any type- Parameters:
map- the map to be added- Returns:
- a new LinkedHashMap filled with the given map.
- Since:
- jcms-6.0.0
-
getFirst
Returns the first item of the given collection (or null if the collection is empty).- Parameters:
coll- the collection- Returns:
- the first item of the given collection (or null if the collection is empty).
- Since:
- jcms-6.0.0
-
getFirst
public static <T> T getFirst(T[] array) Returns the first item of the given array (or null if the array is empty).- Parameters:
array- the array- Returns:
- the first item of the given array (or null if the array is empty).
- Since:
- jcms-6.0.0
-
getNext
Returns the next item of the given collection (or null if the collection is empty).- Parameters:
coll- the collectionitem- the item- Returns:
- the next item of the given collection (or null if the collection is empty).
- Since:
- jcms-9.0.0
-
getNext
public static <T> T getNext(T[] array, T item) Returns the next item of the given array (or null if the array is empty).- Parameters:
array- the arrayitem- the item- Returns:
- the next item of the given array (or null if the array is empty).
- Since:
- jcms-9.0.0
-
getLast
Returns the last item of the given SortedSet (or null if the SortedSet is empty).- Parameters:
set- the SortedSet- Returns:
- the last item of the given SortedSet (or null if the SortedSet is empty).
- Since:
- jcms-8.0.0
-
getLast
Returns the last item of the given List (or null if the List is empty).- Parameters:
list- the List- Returns:
- the last item of the given List (or null if the List is empty).
- Since:
- jcms-8.0.0
-
getLast
public static <T> T getLast(T[] array) Returns the last item of the given array (or null if the array is empty).- Parameters:
array- the array- Returns:
- the last item of the given array (or null if the array is empty).
- Since:
- jcms-8.0.0
-
addInMapHashSet
A convenient method that add the given value to a set bound to the given key in the given map.- Parameters:
map- the mapkey- the keyvalue- the value- Since:
- jcms-7.0.0
-
removeFromMapHashSet
A convenient method that remove the given value to a set bound to the given key in the given map.- Parameters:
map- the mapkey- the keyvalue- the value- Since:
- jcms-7.0.0
-
addInMapLinkedHashSet
A convenient method that add the given value to a set bound to the given key in the given map. This method have an underlying LinkedHashSEt to guarantee iteration order.- Parameters:
map- the mapkey- the keyvalue- the value- Since:
- jcms-7.0.0
-
removeFromMapLinkedHashSet
A convenient method that remove the given value to a set bound to the given key in the given map. This method have an underlying LinkedHashSet to guarantee iteration order.- Parameters:
map- the mapkey- the keyvalue- the value- Since:
- jcms-7.0.0
-
cleanMap
Removes all the entry of the given map with an empty value- Parameters:
map- the map to clean- Returns:
- the given map (for method chaining)
- Since:
- jcms-10.0.0
-
getCleanMap
Returns a copy of the given map without the entry with an empty value.
The copy preserves the type for TreeMap, LinkedHashMap and HashMap. For other Map types, the copy is an HashMap.
If themapparameter is null, it returns a new HashMap.- Parameters:
map- the map to copy- Returns:
- a copy of the given map without the entry with an empty value.
- Since:
- jcms-10.0.0
-
cleanCollection
Remove the null entries of the given collection. Caution, this method changes the content of the given collection.- Parameters:
coll- the collection to be cleaned- Returns:
- the given collection without null entries.
- Since:
- jcms-4.1
-
collectionToCleanSet
Returns a set which contains all the non empty element of the given collection.- Parameters:
coll- the collection- Returns:
- a set which contains all the non empty element of the given collection.
- Since:
- jcms-5.5.0
-
stringArrayToCleanSet
Returns a set which contains all the non empty cells of the given array.- Parameters:
array- the array- Returns:
- a set which contains all the non empty cells of the given array.
- Since:
- jcms-5.5.0
-
addAll
Copy all non-null objects from the given array to given collection.- Parameters:
array- the array to copy fromcoll- the collection to copy to- Returns:
- the collection
- Since:
- jcms-4.1.1
-
addAll
public static <T> T[] addAll(T[] array1, T... otherArrays) Adds all the elements of the given arrays into a new array.
The new array contains all of the element of
array1followed by all of the elementsarray2. When an array is returned, it is always a new array.Util.addAll(null, null) = null Util.addAll(array1, null) = cloned copy of array1 Util.addAll(null, array2) = cloned copy of array2 Util.addAll([], []) = [] Util.addAll([null], [null]) = [null, null] Util.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
- Type Parameters:
T- the component type of the array- Parameters:
array1- the first array whose elements are added to the new array, may benullotherArrays- the other arrays whose elements are added to the new array, may benull- Returns:
- The new array,
nullif both arrays arenull. The type of the new array is the type of the first array, unless the first array is null, in which case the type is the same as the second array. - Throws:
IllegalArgumentException- if the array types are incompatible
-
putAll
Copy all non-null objects from the given array to given map with a given value.- Parameters:
array- the array to copy frommap- the collection to copy tovalue- the value to set- Returns:
- the collection
- Since:
- jcms-5.7
-
swapArray
public static int[] swapArray(int[] array, int from, int to, boolean roll, boolean copy) Swap two cells of an int array.- Parameters:
array- the arrayfrom- the location of the first element (< 0 not to swap)to- the location of the element to swap with (-2 to roll back, -1 to roll forward)roll- if should roll from end to startcopy- return a copy of of the array- Returns:
- int[]
-
swapArray
public static boolean[] swapArray(boolean[] array, int from, int to, boolean roll, boolean copy) Swap two cells of a boolean array.- Parameters:
array- the array of arrayfrom- the location of the first element (< 0 not to swap)to- the location of the element to swap with (-2 to roll back, -1 to roll forward)roll- if should roll from end to startcopy- return a copy of of the array- Returns:
- boolean[]
-
swapArray
Swap two cells of an Object array.- Parameters:
array- the array of arrayfrom- the location of the first element (< 0 not to swap)to- the location of the element to swap with (-2 to roll back, -1 to roll forward)roll- if should roll from end to startcopy- return a copy of of the array- Returns:
- Object[]
-
insertArray
public static int[] insertArray(int[] array, int index, int elt) Insert an element into an int array and return a duplicate copy of it.- Parameters:
array- the arrayindex- the location where the element must be inserted (use -1 to insert ahead and array.length (or greater) to insert at the end)elt- the element to be inserted- Returns:
- a new int[]
-
insertArray
public static boolean[] insertArray(boolean[] array, int index, boolean elt) Insert an element into a boolean array and return a duplicate copy of it.- Parameters:
array- the arrayindex- the location where the element must be inserted (use -1 to insert ahead, array.length (or greater) to insert at the end)elt- the element to be inserted- Returns:
- a new boolean[]
-
insertArray
Insert an element into an Object array and return a duplicate copy of it.- Parameters:
array- the arrayindex- the location where the element must be inserted (use -1 to insert ahead, array.length (or greater) to insert at the end)elt- the element to be inserted- Returns:
- Object[]
-
removeArray
Remove an element of an Array of object- Parameters:
array- the array of objectindex- the location of the element to be removed from- Returns:
- Object[] remove a copy of the array without the element. If the index is bad then return the original array
-
removeArray
Remove an element of an Array of object- Parameters:
array- the array of objectobj- the object to be removed- Returns:
- Object[] remove a copy of the array without the element. If the index is bad then return the original array
-
removeArray
public static int[] removeArray(int[] array, int index) Remove an element of an Array of int- Parameters:
array- the array of intindex- the location of the element to be removed from- Returns:
- int[] remove a copy of the array without the element. If the index is bad then return the original array
-
removeArray
public static boolean[] removeArray(boolean[] array, int index) Remove an element of an Array of boolean- Parameters:
array- the array of booleanindex- the location of the element to be removed from- Returns:
- boolean[] remove a copy of the array without the element. If the index is bad then return the original array
-
removeArray
Remove n elements of an Array of object- Parameters:
array- the array of intfrom- the location of the first element to be removed fromto- the location of the last element to be removed from- Returns:
- Object[] remove a copy of the array without the element. If the from or to is bad then return the original array
-
removeArray
public static int[] removeArray(int[] array, int from, int to) Remove n elements of an Array of int- Parameters:
array- the array of intfrom- the location of the first element to be removed fromto- the location of the last element to be removed from- Returns:
- int[] remove a copy of the array without the element. If the from or to is bad then return the original array
-
removeArray
public static boolean[] removeArray(boolean[] array, int from, int to) Remove n elements of an Array of boolean- Parameters:
array- the array of booleanfrom- the location of the first element to be removed fromto- the location of the last element to be removed from- Returns:
- boolean[] remove a copy of the array without the element. If the from or to is bad then return the original array
-
isSameContent
public static boolean isSameContent(boolean[] array1, boolean[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a boolean arrayarray2- a boolean array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(byte[] array1, byte[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a byte arrayarray2- a byte array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(char[] array1, char[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a char arrayarray2- a char array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(double[] array1, double[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a double arrayarray2- a double array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(float[] array1, float[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a float arrayarray2- a float array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(int[] array1, int[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- an int arrayarray2- an int array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(long[] array1, long[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a long arrayarray2- a long array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(short[] array1, short[] array2) Returns true if array1 has same content than array2.- Parameters:
array1- a short arrayarray2- a short array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
Returns true if array1 has same content than array2.- Parameters:
array1- an object arrayarray2- an object array- Returns:
- true if array1 has same content than array2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
Returns true if col1 has same content than col2.- Parameters:
col1- a Collection (a Set or a List)col2- a Collection (a Set if col1 is a Set or a List if col1 is a List)- Returns:
- true if col1 has same content than col2
- Since:
- jcms-9.0.3
- See Also:
-
isSameContent
Returns true if set1 has same content than set2.- Parameters:
set1- a Setset2- a Set- Returns:
- true if set1 has same content than set2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
Returns true if list1 has same content than list2.- Parameters:
list1- a Listlist2- a List- Returns:
- true if list1 has same content than list2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
Returns true if map1 has same content than map2.- Parameters:
map1- a Mapmap2- a Map- Returns:
- true if map1 has same content than map2 (note: null == empty)
- Since:
- jcms-2.2
-
isSameContent
Returns true if str1 has same content than str2.- Parameters:
str1- a Stringstr2- a String- Returns:
- true if str1 has same content than str2
- Since:
- jcms-2.2
-
isSameContent
Returns true if date1 has same content than date2.- Parameters:
date1- a Datedate2- a Date- Returns:
- true if date1 has same content than date2
- Since:
- jcms-2.2
-
isSameContent
public static boolean isSameContent(org.jdom.Element elt1, org.jdom.Element elt2) Returns true if elt1 has same content than elt2.- Parameters:
elt1- a JDom Elementelt2- a JDom Element- Returns:
- true if elt1 has same content than elt2
- Since:
- jcms-2.2
-
splitCollection
Split the given collection in sub collections having max elements.- Parameters:
coll- the collection to splitmax- the max element for each sub collections- Returns:
- a list of the splitted collections.
- Since:
- jcms-10.0.0
-
getTreeDescendantSet
Returns a TreeSet with all descendant of the given treenode, (excluding the node itself)- Parameters:
node- the node- Returns:
- a TreeSet with all descendant of the given treenode, (excluding the node itself)
-
getTreeDescendantSet
-
getAllChildrenSet
Returns a TreeSet with all children of the given treenode, (including the node itself)- Parameters:
node- the node- Returns:
- a TreeSet with all children of the given treenode, (including the node itself)
-
getAllChildren
Fill the given set with every children of the given treenode, including the node itself, returns the filled set.- Parameters:
node- the parent nodenodeSet- the set to fill, if null, returns null- Returns:
- the given set, filled with children and node.
-
isChildNode
Test if a node is a child of an other node
Return false if child == node- Parameters:
node- the parent nodechild- the node to seek- Returns:
- boolean if the child is a child or subchild of node
-
isNodeChild
Test if a node is a child of an other node
Return false if child == node.Works like
isChildNode(TreeNode, TreeNode)but use reverse algorithm using parent instead of childrenUse this method with Top/Down cached TreeNode
- Parameters:
parentNode- the parent nodechild- the node to seek- Returns:
- boolean if the child is a child or subchild of node
-
notEmpty
Returnstrueif this string is notnullnor empty (once trimmed).- Parameters:
s- the string to test- Returns:
- true if the string is not empty.
-
isEmpty
Returnstrueif this string isnullor empty (once trimmed).- Parameters:
s- the string to test- Returns:
- true if the string is empty.
-
splitToIntArray
Splits a String into an array of int.- Parameters:
str- the String to splitdelim- the delimiter (same as StringTokenizer)- Returns:
- an array of String.
- See Also:
-
split
Splits a String into an array of String.- Parameters:
str- the String to splitdelim- the delimiter (same as StringTokenizer)- Returns:
- an array of String.
- See Also:
-
splitToList
Splits a String into a list of String.- Parameters:
str- the String to splitdelim- the delimiter (same as StringTokenizer)- Returns:
- an ArrayList of String.
- See Also:
-
split
Splits a String into an array of String. This method does NOT work as split(str, delim) based on StringTokenizer. This one, checks for empty token. For instance, splitting "A||BC|" with '|' as delim and "EMPTY" as empty token will return: String[] {"A", "EMPTY", "BC", "EMPTY"}- Parameters:
str- the String to splitdelim- the delimiteremptyToken- the value to used when encounter an empty token- Returns:
- an array of String.
- Since:
- jcms-3.0
-
splitWithPattern
Splits a String according a given pattern and returns an array of String. For each match, add group(1) if not empty otherwise adds group(0).
Example1 (without group(1)):
text: foo [one: 1] [two: 2] bar [three: 3] bar
pattern: "\\[([^\\]]+)\\]"
returnsString[] {"one: 1", "two: 2", "three: 3" }
Example2 (with group(1)):
text: foo [one: 1] [two: 2] bar [three: 3] bar
pattern: "\\[[^\\]]+\\]"
returnsString[] {"[one: 1]", "[two: 2]", "[three: 3]" }
- Parameters:
text- the text to split.pattern- the pattern to split with.- Returns:
- an array of String (never null)
- Since:
- jcms-5.7.2
-
trimEnd
Trim the end of a String- Parameters:
str- the String to trim- Returns:
- String the trimmed String
-
getMatch
Return the group matching the given regexp for the given String or null if do not match or exception happens- Parameters:
regexp- the regular expressionstr- the String to matchgroup- the group to match- Returns:
- String the matching group
-
getMatch
Return the group matching the given regexp for the given String or null if do not match or exception happens- Parameters:
pattern- java.util.regex.Patternstr- the String to matchgroup- the group to match- Returns:
- String the matching group
-
wordWrap
Wraps a single line of text, identifying words by
' '.New lines will be separated by the system property line separator. Very long words, such as URLs will not be wrapped.
Leading spaces on a new line are stripped. Trailing spaces are not stripped.
Util.wordWrap(null, *) = null Util.wordWrap("", *) = ""- Parameters:
str- the String to be word wrapped, may be nullwidth- the column to wrap the words at, less than 1 is treated as 1- Returns:
- a line with newlines inserted,
nullif null input TODO: replace with jakarta WordUtils.wrap()
-
wordWrap
Wraps a single line of text, identifying words by
' '.Leading spaces on a new line are stripped. Trailing spaces are not stripped.
Util.wordWrap(null, *, *, *) = null Util.wordWrap("", *, *, *) = ""- Parameters:
str- the String to be word wrapped, may be nullwrapLength- the column to wrap the words at, less than 1 is treated as 1newLineStr- the string to insert for a new line,nulluses the system property line separatorwrapLongWords- true if long words (such as URLs) should be wrapped- Returns:
- a line with newlines inserted,
nullif null input TODO: replace with jakarta WordUtils.wrap()
-
mainTestGeneratePassword
-
mainTestJoin
-
join
Joins an array of String with the given separator.- Parameters:
array- the array of String to join.sep- the separator- Returns:
- the join String.
-
join
Joins an array of String with the given separator.- Parameters:
array- the array of String to join.sep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- the join String.
- Since:
- jcms-4.0
-
join
Joins an array of int with the given separator.- Parameters:
array- the array of int to join.sep- the separator- Returns:
- the join String.
-
join
Joins an array of int with the given separator.- Parameters:
array- the array of int to join.sep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- the join String.
- Since:
- jcms-4.0
-
join
Join all specified strings with a space separator.- Parameters:
str- the strings to be joined.- Returns:
- String
-
join
Joins an array of long with the given separator.- Parameters:
array- the array of long to join.sep- the separator- Returns:
- the join String.
- Since:
- jcms-5.5
-
join
Joins an array of long with the given separator.- Parameters:
array- the array of long to join.sep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- the join String.
- Since:
- jcms-5.5
-
join
Joins an array of double with the given separator.- Parameters:
array- the array of long to join.sep- the separator- Returns:
- the join String.
- Since:
- jcms-5.5
-
join
Joins an array of double with the given separator.- Parameters:
array- the array of double to join.sep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- the join String.
- Since:
- jcms-5.5
-
join
Joins an array of boolean with the given separator.- Parameters:
array- the array of boolean to join.sep- the separator- Returns:
- the join String.
-
join
Joins an array of boolean with the given separator.- Parameters:
array- the array of boolean to join.sep- the separatormax- the maximum of item to joinsuffix- the suffix to add if the maximum has been reached- Returns:
- the join String.
- Since:
- jcms-4.0
-
toWordLine
Split a text in a String with one word by line (used for diffing 2 strings at word level).- Parameters:
str- the string to split- Returns:
- the result String
- Since:
- jcms-2.2
-
repeat
Repeat a String patterncounttimes- Parameters:
pattern- the patterncount- the number of times the pattern must be repeated- Returns:
- a String containing the result
-
arrayContains
Test if an array contains a given object. Return true if the test with '==' operator or 'equals' method returns true.- Parameters:
array- the array to be searched.key- the value to be searched for.- Returns:
- true if the array contains the given object.
-
trim
Remove the trailing empty cells of the given String array. E.g. trimString(new String[] {"", "x", "", "y", null, ""}) returns {"", "x", "y"}.- Parameters:
array- the array to be trimmed- Returns:
- the trimmed array
-
trimStringArray
Remove the trailing empty cells of the given String array. E.g. trimStringArray(new String[] {"", "x", "", "y", null, ""}) returns {"", "x", "y"}.- Parameters:
array- the array to be trimmed- Returns:
- the trimmed array
-
trimList
Returns a copy of the given list without any null values at the end.- Type Parameters:
T- any type- Parameters:
list- the list to be trimmed- Returns:
- a copy of the given list without any null values at the end.
- Since:
- jcms-5.7.0
-
cleanStringArray
Creates a new array that contains all elements of the given array except empty Strings (ie null or empty). Each string is trimed.- Parameters:
array- the array to be cleaned- Returns:
- the cleaned array
-
cleanObjectArray
Creates a new array that contains all elements of the given array without null.- Parameters:
array- the array to be cleaned- Returns:
- the cleaned array
- Since:
- jcms-5.0.5
-
unaccentuate
Removes all the accentuate chars of the given string. The following accentuate chars are supported: À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö Œ Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö œ ù ú û ü ý þ ÿ- Parameters:
str- the String to unaccentuate.- Returns:
- an unaccentuate String.
-
unaccentuateRegexp
Build an unaccentuated version of the given regexp. E.g. char 'e' is replaced by (e|é|è|ê|ë).- Parameters:
str- the String of the regexp to unaccentuate.- Returns:
- an unaccentuate String.
-
recapitalize
Force the first char of a String to be a uppercase char.- Parameters:
str- the String to proceed- Returns:
- the result String
-
uncapitalize
Force the first char of a String to be a lowercase char.- Parameters:
str- the String to proceed- Returns:
- the result String
- Since:
- jcms-2.2
-
cryptUnix
Deprecated.using this algorythm for "encryption" is completely unsecure. Do NOT use.Encrypt the given string with the Unix crypt algorithm- Parameters:
str- the String to encrypt- Returns:
- the encrypted string
- Since:
- jcms-4.0
-
cryptMD5
Deprecated.using MD5 algorithm for "encryption" is completely unsecure, don't.
If you need to encrypt data, use a dedicated library.
If you need to validate passwords or other kind of authentication digest, use strong algorithm such asBCrypt.
If you need to hash data for signing or other basic use case, use DigestUtils from Apache Commons Codec.
And if you absolutely need the same contract for backward compatibility, usemd5Base64(String)which provides exactly the same behavior with a method name which does not implying it can be used for encryption.Encrypt the given string with the MD5 algorithm and BASE64- Parameters:
str- the String to encrypt- Returns:
- the encrypted string
- Since:
- jcms-4.0
-
md5Base64
Calculates the MD5 digest and returns the value as a base64 string.This method is provided for backward compatibility to replace the deprecated method
cryptMD5(String).
For any new developpement, prefer the use ofDigestUtils.md5Hexfrom Apache Commons Codec.- Parameters:
str- the data to digest- Returns:
- MD5 digest as a base64 string
- Since:
- jcms-10.0.0 DEVJCMS-2504
-
encodeBASE64
Encode the given string using BASE64 algorithm. The output is chuncked every 76 character. Equivalent to 'Util.encodeBase64(str, true)'- Parameters:
str- the String to encode- Returns:
- the encoded string
- Since:
- jcms-5.5.0
-
encodeBASE64
Encode the given string using BASE64 algorithm.- Parameters:
str- the string to encodeisChunck- - if true this encoder will chunk the base64 output into 76 character blocks- Returns:
- the encoded string
- Since:
- jcms-6.0
-
decodeBASE64
Decode the given string using BASE64 algorithm- Parameters:
str- the String to decode- Returns:
- the decoded string
- Since:
- jcms-5.5.0
-
encryptDES3
Encrypt the specified string using DESedeStringEncrypterwith an internal key.
WARNING: This method is not mathematically safe and is only used to hide sensitive data on first look.- Parameters:
clearStr- the string to encrypt.- Returns:
- the encrypted string prefixed, or null/empty string if the specified clearStr was null/empty.
- Throws:
StringEncrypter.EncryptionException- if the encryption could not be performed- Since:
- jcms-5.7.0
-
decryptDES3
Decrypt the specified string using DESedeStringEncrypterusing same internal key used byencryptDES3(String).- Parameters:
encryptedStr- the encrypted string to decrypt. if null or empty, the return- Returns:
- the decrypted string, or null/empty string if the specified encryptedStr was null/empty
- Throws:
StringEncrypter.EncryptionException- if the decryption could not be performed- Since:
- jcms-5.7.0
-
conceal
Conceal the given string with an internally choosen encryption algorithm.
WARNING: This method is not mathematically safe and is only used to hide sensitive data on first look.
WARNING: This method will return the clear text string if the string could not be encrypted.- Parameters:
clearStr- the String to encrypt- Returns:
- the encrypted string
- Since:
- jcms-5.7
-
reveal
Reveal the specified hidden string with an internally choosen encryption algorithm.- Parameters:
concealedStr- the String to encrypt- Returns:
- the encrypted string
- Since:
- jcms-5.7
-
isConcealed
-
buildID
Build an ID from the given String: replaces the blanks with '_', unaccentuates, removes chars out of the given range and lowercases.- Parameters:
str- the String to used as base for the IDcharRange- a perl5 char range. All the chars out of this range will be ignored (e.g. "0-9a-z_A-Z" to keep only alpha-num chars)- Returns:
- the ID
- Since:
- jcms-4.0.1
-
buildID
Build an ID from the given String: replaces the blanks with '_', unaccentuates, removes non-alphanum chars and lowercases.- Parameters:
str- the String to used as base for the ID- Returns:
- the ID
- Since:
- jcms-4.0
-
buildCamelID
Build a Camel Case ID from the given String: remove the blanks, unaccentuates, removes non-alphanum chars.- Parameters:
str- the String to used as base for the ID- Returns:
- the ID
- Since:
- jcms-5.7.0
-
buildUID
Build an ID from the given String: replaces the blanks with '_', unaccentuates, removes non-alphanum chars and lowercases. Add a number to the id if it already exists.- Parameters:
str- the String to used as base for the IDstrSet- the set of String of existing ids- Returns:
- the ID
-
mainTestBuildID
-
escapePercent
This method replace % in wrong hexa character by '_' character- Parameters:
url- the utf-8 string to escape- Returns:
- String the escaped String
-
escapeRegexp
Escape a (OROMatcher) regular expression with support of basic regexp (* and ?). Example: (a*b?) will be escaped into \(a.*b.?\).- Parameters:
string- the regexp string to be escaped- Returns:
- the escaped string
- See Also:
-
escapeRegexp
Escape a (OROMatcher) regular expression with support of basic regexp (* and ?). Example: (a*b?) will be escaped into \(a.*b.?\).- Parameters:
string- the regexp string to be escapedbasicRegexp- if true convert * and ? to Perl5 regular expression- Returns:
- the escaped string
- Since:
- jcms-4.1
-
escapeChars
Escape specified characters in a String.Example:
Util.escapeChar("ab|cde%fg|hi=j", "|="); // -> ab%7ccde%25fg%7chi%3dj- Parameters:
str- the stringcharsToEscape- a string containing all the chararacters to escape- Returns:
- a new String with all
charToEscapeescaped
-
unescapeChar
Unescape escaped character in a String. Character to unescape are prepended with ESCAPE_CHAR.Example:
Util.unescapeChar("ab%7ccde%25fg%7chij"); // -> ab|cde%fg|hij- Parameters:
str- the string- Returns:
- a new String with all
charToUnescapeunescaped
-
escapeLuceneQuery
Escape Lucene special chars used in classic QueryParser. I.e. + - && || ! ( ) { } [ ] ^ " ~ * ? : \ (see https://lucene.apache.org/core/6_0_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html)- Parameters:
str- the string to escape- Returns:
- the escaped string
- Since:
- jcms-4.0
-
replace
Search and replace a string by another one (Note the input string must not contains '#' char)- Parameters:
str- the input Stringmatch- a Perl5 regexprep- a Perl5 replace pattern- Returns:
- the modified String
-
replace
Search and replace a string by another one- Parameters:
str- the input Stringpattern- the Perl5 substitution pattern (e.g. s!regexp!replace!)- Returns:
- the modified String
-
replace
public static String replace(String text, String regexp, RegexpSubstitution substitution) throws org.apache.oro.text.regex.MalformedPatternException Replaces the given regexp in the given text with the given substitution function.- Parameters:
text- the textregexp- the regexpsubstitution- the RegexpSubstitution function called.- Returns:
- the result text or the given text if there is null parameter
- Throws:
org.apache.oro.text.regex.MalformedPatternException- if an error has occurred.- Since:
- jcms-6.0.0
-
replace
public static String replace(String text, org.apache.oro.text.regex.Pattern pattern, RegexpSubstitution substitution) Replaces the given pattern in the given text with the given substitution function.- Parameters:
text- the textpattern- the patternsubstitution- the RegexpSubstitution function called.- Returns:
- the result text or the given text if there is null parameter
- Since:
- jcms-6.0.0
-
replace
Searches a string for a specified regular expression, and returns a new string where the specified values are replaced.Pattern regex = Pattern.compile("\\d+"); String result = StringReplacer.replace("test6test12hoho", regex, (Matcher m) -> { return "" + (Integer.parseInt(m.group()) * 2); });- Parameters:
input- the input Stringregex- Regular expression that will be replaced by the new valuecallback- callback to return the replacement text- Returns:
- A new String, where the specified regular expression has been replaced by the new value
-
replaceAll
Replace all occurrences of searchString with replaceString in input string. DO NOT use any regular expressions.- Parameters:
input- represents input stringsearchString- represents substring for replacereplaceString- represents replaced string value- Returns:
- new string with replaced values
- Since:
- jcms-5.5.0
-
removeBlankLines
Cleans the given string : remove pure blank lines and remove leadings white spaces. This method has been rewritten in jcms-5.0.1 and is about twice faster than the previous implementation.- Parameters:
str- the String to be cleaned- Returns:
- the cleaned String
- Since:
- jcms-4.0
-
escapeBackslash
Escape all the '\' in the given String ('\\')- Parameters:
str- the String to escape- Returns:
- the escaped String
-
escapeJavaStringChar
Escape all the invalid char in Java String:- '\' -> "\\"
- CR -> "\n"
- '"' -> \"
- Parameters:
str- the String to escape- Returns:
- the escaped String
-
escapeJavaScriptQuote
Deprecated.use com.jalios.jcms.HttpUtil.encodeForJavaScriptEscape JavaScript quotes- ' -> \'
- " -> \"
- Parameters:
str- the String to escape- Returns:
- the escaped String
- Since:
- jcms-2.2
-
getFirstSentences
Get the first sentences in a given string.- Parameters:
text- the string to get the first sentence.limit- how many sentences to get (return the original text if limit <0).- Returns:
- a string containing the first sentences.
-
mainSwapArray
-
mainRemoveArray
-
truncateHtml
Truncate an HTML string.
- Prevents html tags to be split in the middle of the attributes.
That is, the string "the image: <img src='some.jpg' border='0'>"
will end "the image: "
- Warning: do not prevent opened tag not to be closed:
with a string "go there: <a href='hello'>a link</a>"
you can end with "go there: <a href='hello'>a lin" which is invalid html
Use
HtmlUtil.truncate(String, int, String)for advanced HTML support.- Parameters:
text- the HTML content to be truncatedlength- the length to keep.trim- if true trims the input text- Returns:
- the truncated text
-
truncate
Truncates the given String.- Parameters:
str- the String to truncatelength- the length to truncate to- Returns:
- the truncated string
- Since:
- jcms-6.1.0
-
truncate
Truncates the given String- Parameters:
str- the String to truncatelength- the length to truncate tosuffix- the suffix to add if the string has been truncated- Returns:
- the truncated string
- Since:
- jcms-4.0.2
-
truncate
Returns a unique truncated string. If str <= length it returns str if str > length it returns a truncated version of str that has not been already used.When call twice with the same too long string it returns the same truncated string.
Example:
Map<String,String> truncatedMap = new HashMap<String,String>()
Util.truncate("co", 4, truncatedMap) => "co"
Util.truncate("comm", 4, truncatedMap) => "comm"
Util.truncate("common1", 4, truncatedMap) => "com0"
Util.truncate("common2", 4, truncatedMap) => "com1"
Util.truncate("common3", 4, truncatedMap) => "com2"
Util.truncate("common1", 4, truncatedMap) => "com0"
Util.truncate("common4", 4, truncatedMap) => "com3"The method must be called with the same
lengthattribute each time it is called with the sametruncatedMap- Parameters:
str- the String to truncatelength- the length to truncate totruncatedMap- a map to memorize the truncation- Returns:
- a unique truncated string.
- Since:
- jcms-10.0.0
-
html2Ascii
Deprecated.since jcms-9.0.0Convert the specified string from HTML to raw text, preserving and converting as much spaces as possibles (space, <br>, carriage return, line feeds, ...).Contrary to the behavior implied by the method name, the returned text may contained unicode characters.
Important limitation note : as of current implementation, the conversion is performed using regular expression. This processing can lead to StackErrorOverflow when a large and invalid HTML content is specified. If you don't need to preserve and convert spaces from the HTML, uses
HtmlUtil.html2text(String).
More information on this problem in JIRA issue JCMS-2628- Parameters:
str- the html to convert- Returns:
- the text converted
- See Also:
-
surround
Surround a given text (the first argument) with the two other arguments, only if the given text is not empty. Otherwise, returns an empty text.- Parameters:
inside- The text to be surrounded.begin- The text at the beginning.end- The text at the end.- Returns:
- The given text surrounded.
-
surroundWithTag
Surround a given text (the first argument) with a html tag. If the text is empty, returns an empty text. If the tag is empty, returns the original text.- Parameters:
inside- The text to be surrounded.tag- The tag- Returns:
- The text surrounded.
-
decodeUrl
-
encodeUrl
Same implementation asURLEncoder.encode(String, String), but space is encoded with %20 and '/' is not encoded.- Parameters:
s-Stringto be translated.- Returns:
- the translated
String.
-
encodeUrl
Same implementation asURLEncoder.encode(String, String), but space is encoded with %20 and '/' is not encoded.- Parameters:
s-Stringto be translated.enc-Stringencoding- Returns:
- the translated
String.
-
encodeUrl
Same implementation asURLEncoder.encode(String, Charset), but space is encoded with %20 and '/' is not encoded.- Parameters:
s-Stringto be translated.charset-Stringcharset- Returns:
- the translated
String.
-
encodeCookie
-
decodeCookie
-
isoLatin1ToEntities
Convert all the isoLatin1 accent into XML entities (e.g. 'é' -> é)- Parameters:
src- the String to convert- Returns:
- the converted String
-
entitiesToIsoLatin1
Does the opposite of isoLatin1ToEntities.- Parameters:
src- the String to convert- Returns:
- the converted String
-
encodeHtmlBasicEntities
Encode given string according to the following table.- " : "
- ' : '
- < : <
- > : >
- & : &
- Parameters:
src- the String to convert- Returns:
- the converted String
-
decodeHtmlBasicEntities
Does the opposite job of encodeHtmlBasicEntities.- Parameters:
src- the String to convert- Returns:
- the converted String
-
performEncoding
Replace all occurences of keys found in transMap with their assiocated values.- Parameters:
src- the String to converttransMap- the translation map- Returns:
- the converted String
-
performDecoding
Replace all occurences of values found in transMap with their assiocated keys.- Parameters:
src- the String to converttransMap- the translation map- Returns:
- the converted String
-
performEncodeDecode
Encode or decode the given String using the given translation Map. If encoding replace occurence of keys with values. If decoding replace occurence of values with keys- Parameters:
src- the String to convert. If src is null, return src.transMap- the translation map. If transMap is null, return src.decode- if true use values else use keys- Returns:
- the converted String
-
encodeIntArray
-
decodeIntArray
-
encodeIntArray
-
decodeIntArray
-
encodeStringArray
-
decodeStringArray
-
encodeStringArray
-
decodeStringArray
-
encodeObject
Returns the encoded objected as a String.- Parameters:
obj- the object to be encoded- Returns:
- the encoded objected as a String.
- Since:
- jcms-6.0.0
- See Also:
-
decodeObject
Returns the object decoded from the given String.Warning: This method uses object deserialization, NEVER use with untrusted data.
- Parameters:
encoded- the String that contains the encoded object- Returns:
- the object decoded from the given String.
- Since:
- jcms-6.0.0
- See Also:
-
toArray
Converts an object value to an arrays ofObject.- Parameters:
obj- object to convert, may be nulldefaultValues- array of default values used when the specified object could not be converted.- Returns:
- array of Object
-
toString
Converts an object value to aString.- Parameters:
obj- object containing a string, may be nulldefaultValue- default value used when the specified object could not be converted.- Returns:
- String created from the object
-
toStringArray
Converts an object value to aStringarray.- Parameters:
obj- object containing strings, may be nulldefaultValues- array of default values used when the specified object could not be converted.- Returns:
- String array created from the object
-
isNumber
Returns true if the given string only contains 0-9 characters- Parameters:
str- the String to be checked- Returns:
- true if the given string only contains 0-9 characters
-
toNumber
Converts an object value to aNumber.- Parameters:
obj- object containing a number, may be nulldefaultValue- default value used when the specified object could not be converted.- Returns:
- Number created from the object
-
toNumberArray
Converts an object value to aNumberarray.- Parameters:
obj- object containing numbers, may be nulldefaultValues- array of default values used when the specified object could not be converted.- Returns:
- Number array created from the object
-
toInteger
Converts an object value to anInteger.- Parameters:
obj- object containing an integer, may be nulldefaultValue- default value used when the specified object could not be converted.- Returns:
- Integer created from the object
-
toIntArray
Convert an Object[] (assert to be either aStringor aInteger) to aint- Parameters:
objs- the object array to convertdef- default int value to use is object is empty, not aStringnor aInteger- Returns:
- a
int[]or null if objs is null - Since:
- jcms-5.6.0
- See Also:
-
toInt
Convert an Object (assert to be either aStringor aInteger) to aint- Parameters:
obj- the object to convertdef- default int value to use is object is empty, not aStringnor aInteger- Returns:
- a
int - Since:
- jcms-4.0
-
toFloat
Convert an Object (assert to be either aStringor aFloat) to afloat- Parameters:
obj- the object to convertdef- default float value to use is object is empty, not aStringnor aFloat- Returns:
- a
float - Since:
- jcms-4.0
-
toByte
Convert an Object (assert to be either aStringor aByte) to abyte- Parameters:
obj- the object to convertdef- default byte value to use is object is empty, not aStringnor aByte- Returns:
- a
byte - Since:
- jcms-4.0
-
toShort
Convert an Object (assert to be either aStringor aShort) to ashort- Parameters:
obj- the object to convertdef- default short value to use is object is empty, not aStringnor aShort- Returns:
- a
short - Since:
- jcms-4.0
-
toLong
Convert an Object (assert to be either aStringor aLong) to along- Parameters:
obj- the object to convertdef- default long value to use is object is empty, not aStringnor aLong- Returns:
- a
long - Since:
- jcms-4.0
-
toDouble
Convert an Object (assert to be either aStringor aDouble) to adouble- Parameters:
obj- the object to convertdef- default double value to use is object is empty, not aStringnor aDouble- Returns:
- a
double - Since:
- jcms-4.0
-
parseDouble
Parse string into Double.Support most common decimal mark and grouping seperator without using any Locale specific behavior.
- Parameters:
str- the string to parse- Returns:
- a Double instance or null if str could not be parsed
-
toChar
Convert an Object (assert to be either aStringor aCharacter) to achar- Parameters:
obj- the object to convertdef- default char value to use is object is empty, not aStringnor aCharacter- Returns:
- a
char - Since:
- jcms-4.0
-
toBoolean
Convert an Object (assert to be either a String or a Boolean) to a boolean- Parameters:
obj- the object to convertdef- default boolean value to use is object is empty, not aStringnor aBoolean- Returns:
- a
boolean - Since:
- jcms-4.0
-
toDate
Parse a String and Convert it into a Date- Parameters:
str- the String to parseformat- the date Format (can be null)loc- the Locale tio use (can be null)def- the default Date to return if errors append.- Returns:
- the converted Date
-
formatSize
This method format the given number using International System prefix (aka metric system).Example: 4096 -> 4k, 532923 -> 520.43k
- Parameters:
size- the size to formatlocale- the locale to use for the unit- Returns:
- the formatted file size
-
formatFileSize
This method format the given size on the greatest unit. Example: 4096 -> 4 KB, 532923 -> 520.43 KB Use default locale.The format used is plain text.
- Parameters:
size- the size to format- Returns:
- the formatted file size
-
formatFileSize
This method format the given size on the greatest unit. Example: 4096 -> 4 KB, 532923 -> 520.43 KBThe format used is HTML (with detailled abbreviations).
- Parameters:
size- the size to formatlocale- the locale to use for the unit- Returns:
- the formatted file size
-
formatFileSize
This method format the given size on the greatest unit. Example: 4096 -> 4 KB, 532923 -> 520.43 KB- Parameters:
size- the size to formatlocale- the locale to use for the unithtmlDisplay- if true, uses an html format, with detailled abbreviation, otherwise, use only plain text- Returns:
- the formatted file size
-
getFileSizeWidgetElt
Convert a file size to a rounded value with a size as a string and the unit in which it is expressed (units are in english).Example :
long KILOBYTES = 1024; long MEGABYTES = 1024*KILOBYTES; long GIGABYTES = 1024*MEGABYTES; long TERABYTES = 1024*GIGABYTES; Util.getFileSizeWidgetElt(768) -> { "768", "" } Util.getFileSizeWidgetElt(2*KILOBYTES+512) -> { "2", "KB" } Util.getFileSizeWidgetElt(3*MEGABYTES + 2*KILOBYTES + 512) -> { "3", "MB" } Util.getFileSizeWidgetElt(4*GIGABYTES + 3*MEGABYTES + 2*KILOBYTES + 512) -> { "4", "GB" } Util.getFileSizeWidgetElt(5*TERABYTES + 4*GIGABYTES + 3*MEGABYTES + 2*KILOBYTES + 512) -> { "5", "TB" }- Parameters:
size- the real size- Returns:
- a array of 2 strings :
[0]is the value, converted in the proper unit,
[1]is the unit (empty string for bytes value, "KB", "MB", "GB" or "TB"). - See Also:
-
convertFileSizeWidgetElt
Convert a size value and the unit in which it is expressed into a file size expressed in bytes.Example :
long KILOBYTES = 1024; long MEGABYTES = 1024*KILOBYTES; long GIGABYTES = 1024*MEGABYTES; long TERABYTES = 1024*GIGABYTES; Util.convertFileSizeWidgetElt("768", ""); -> 768 Util.convertFileSizeWidgetElt("2", "KB"); -> 2048 (== 2*KILOBYTES) Util.convertFileSizeWidgetElt("3", "MB"); -> 3145728 (== 3*MEGABYTES) Util.convertFileSizeWidgetElt("4", "GB"); -> 4294967296 (== 4*GIGABYTES) Util.convertFileSizeWidgetElt("5", "TB"); -> 5497558138880 (== 5*TERABYTES)- Parameters:
value- the size, expressed in the unit specified in the parameter "unit"unit- the unit in english, from following values : empty string for bytes value, "KB", "MB", "GB" or "TB"- Returns:
- the real value in bytes
- See Also:
-
getFileSizeWidgetUnit
Retrieve an array containing I18Ned labels to express file size, from bytes to petaabytes.Example :
Util.getFileSizeUnitLabels(Locale.ENGLISH); -> { "","KB","MB","GB","TB", "PB" } Util.getFileSizeUnitLabels(Locale.FRENCH); -> { "","Ko","Mo","Go","To", "Po" } Util.getFileSizeUnitLabels(Locale.of("tlh")); -> { "","KB","MB","GB","TB", "PB" }- Parameters:
locale- the Locale in which to retrieve the label- Returns:
- an array of 6 labels, in the specified Locale if it exists, otherwise in english, never return null.
-
getFileSizeUnitLabels
Retrieve an array containing I18Ned labels to express file size, from bytes to petabytes.Example :
Util.getFileSizeUnitLabels(Locale.ENGLISH); -> { "b","KB","MB","GB","TB", "PB" } Util.getFileSizeUnitLabels(Locale.FRENCH); -> { "o","Ko","Mo","Go","To", "Po" } Util.getFileSizeUnitLabels(Locale.of("tlh")); -> { "B","KB","MB","GB","TB", "PB" }- Parameters:
locale- the Locale in which to retrieve the label- Returns:
- an array of 6 labels, in the specified Locale if it exists, otherwise in english, never return null.
-
getFileSizeUnitHTMLLabels
Retrieve an array containing I18Ned labels to express file size, from bytes to petabytes.Example :
Util.getFileSizeUnitLabels(Locale.ENGLISH); -> { "<abbr title=\"bytes\">B</abbr>","<abbr title=\"kilo bytes\">KB</abbr>","<abbr title=\"mega bytes\">MB</abbr>","<abbr title=\"giga bytes\">GB</abbr>","<abbr title=\"tera bytes\">TB</abbr>","<abbr title=\"peta octets\">PB</abbr>" } Util.getFileSizeUnitLabels(Locale.FRENCH); -> { "<abbr title=\"octets\">o</abbr>","<abbr title=\"kilo octets\">Ko</abbr>","<abbr title=\"mega octets\">Mo</abbr>","<abbr title=\"giga octets\">Go</abbr>","<abbr title=\"tera octets\">To</abbr>","<abbr title=\"peta octets\">Po</abbr>" } Util.getFileSizeUnitLabels(Locale.of("tlh")); -> { "<abbr title=\"bytes\">B</abbr>","<abbr title=\"kilo bytes\">KB</abbr>","<abbr title=\"mega bytes\">MB</abbr>","<abbr title=\"giga bytes\">GB</abbr>","<abbr title=\"tera bytes\">TB</abbr>","<abbr title=\"peta octets\">PB</abbr>" }- Parameters:
locale- the Locale in which to retrieve the label- Returns:
- an array of 6 labels, in the specified Locale if it exists, otherwise in english, never return null.
-
generatePassword
Generates a basic password (consonnants / voyels) of 8 characters.- Returns:
- the generated password
- Since:
- jcms-4.0
-
generatePassword
Generates a basic password (consonnants / voyels) of the specified length.- Parameters:
length- the length of the password to be generated- Returns:
- the generated password
- Since:
- jcms-4.0
-
generatePronounceablePassword
Generates pronounceable passwords of specified length. See www.multicians.org/thvv/gpw.html for history and info. Tom Van Vleck- Parameters:
pwdLength- The length of the password to be generated- Returns:
- The generated password
- Since:
- jcms-4.0
-
getStackTrace
This method print the stack trace into a String and return it. This is a convenient method for JSP that doesn't have PrintWriter.- Parameters:
throwable- the exception or throwable to print- Returns:
- String the full stack trace.
-
getCurrentStackTrace
Returns the current StackTrace in a String.- Returns:
- the current StackTrace in a String.
- Since:
- jcms-6.1.2
-
forceFullGarbageCollection
public static boolean forceFullGarbageCollection(long timeout) Force the garbage collection- Parameters:
timeout- in millisecond if timeout is reached stop the GC forcing- Returns:
- false if the timeout has been reached
-
getClassShortName
Returns the short name of the given object's class (e.g. String for java.lang.String)- Parameters:
object- the object- Returns:
- the short name of the object's class
- Since:
- jcms-4.1
-
getClassShortName
Returns the short name of the given class (e.g. String for java.lang.String)- Parameters:
clazz- the class- Returns:
- the short name of the class
-
getClassShortName
Returns the short name of the given class name (e.g. String for java.lang.String)- Parameters:
fullname- the full class name- Returns:
- the short name of the class
-
getClassFiles
Returns a Set of relative path to all class files including inner class and java. Pay attention to ending / to parameter.- Parameters:
realPath- the Webapp realpath (i.e. C:/project/appserver/webapps/webapp-name)fullname- the Class fullname (i.e. com.jalios.jcms.Category)java- boolean true to include java file- Returns:
- Set a set of relative path (i.e. WEB-INF/classes/com/jalios/jcms/Category.class)
-
getPackageClassFiles
public static Set<String> getPackageClassFiles(String realPath, String fullPackage, boolean sources, String excludesPattern) Returns a Set of relative path to all class files including inner class and java. Pay attention to ending / to parameter.- Parameters:
realPath- the Webapp realpath (i.e. C:/project/appserver/webapps/webapp-name)fullPackage- the Package fullname (i.e. com.jalios.jcms.Category)sources- boolean true to include java fileexcludesPattern- Ant-style path patterns to exclude files or folders (seeAntPathMatcher)- Returns:
- Set a set of relative path (i.e. WEB-INF/classes/com/jalios/jcms/Category.class)
-
getClassNameFromFilename
Returns the class name from the filename of a class (e.g. it returns "com.jalios.util.Util" for "com/jalios/util/Util.class")- Parameters:
filename- the filename of the class- Returns:
- the class name or
nullif an error occurred. - Since:
- jcms-5.5.0
-
getFirstCommonClass
Follow class tree of parent to find a class or an interface that is also parent of the child. If child is null return parent.- Parameters:
parent- parent classchild- child class- Returns:
- Class
-
getSuperclassList
public static List getSuperclassList(Class clazz, Class ancestor, boolean addClass, boolean addAncestor) Returns a list of classes the given class is an ancestor of.- Parameters:
clazz- the class to extract the ancestorsancestor- the greater ancestoraddClass- if true, add the class in the listaddAncestor- if true, add the ancestor in the list- Returns:
- a list from the given class to the ancestor class
- Since:
- jcms-4.2
-
escapeHtml
Escapes some special HTML characters such as <, >, & and ". If str is null return an empty string.- Parameters:
str- the string to escape- Returns:
- the escaped string
-
indexOf
Searches for the first occurrence of the given argument in a given array, testing for equality using theequalsmethod.- Parameters:
elem- an object.array- an array that may containelem- Returns:
- the index of the first occurrence of the argument in this
* list; returns
-1if the object is not found. - See Also:
-
hasAppenderDefined
public static boolean hasAppenderDefined(org.apache.log4j.Logger logger) Checks if the givenLoggerhas any appender defined.- Parameters:
logger- the Logger to check- Returns:
- true if logger has any appender defined, false otherwise
- Since:
- jcms-5.0.5
-
validateRegexp
Tell if a String is a valid Perl 5 regexp.- Parameters:
regexp- The pattern to validate- Returns:
- true if it is a valid Perl 5 syntax
- Since:
- JCMS-6.0
-
reduceBlankLines
Right trim all the lines in the message and reduced many CRLF to only one line.- Parameters:
text- the original text- Returns:
- the text, right trimed and with less line feed.
-
randomString
-
exec
Executes the specified command and arguments in a separate process.Warning: This method execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution.
Only use with trusted input.- Parameters:
cmdList- list containing the command to call and its arguments.- Returns:
- the exit code
- Throws:
IOException- if an error occursInterruptedException- if an error occurs- Since:
- jcms-6.1.2
-
exec
Executes the specified command and arguments in a separate process.Warning: This method execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution.
Only use with trusted input.- Parameters:
cmdarray- array containing the command to call and its arguments.- Returns:
- the exit code
- Throws:
IOException- if an error occursInterruptedException- if an error occurs- Since:
- jcms-6.1.2
-
exec
public static int exec(String[] cmdarray, OutputStream stdout, OutputStream stderr) throws IOException, InterruptedException Executes the specified command and arguments in a separate process.Warning: This method execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution.
Only use with trusted input.- Parameters:
cmdarray- array containing the command to call and its arguments.stdout- the OutputStream for stdout (ignored if null)stderr- the OutputStream for stderr (ignored if null)- Returns:
- the exit code
- Throws:
IOException- if an error occursInterruptedException- if an error occurs- Since:
- jcms-6.1.2
-
exec
public static int exec(String[] cmdarray, StringBuilder stdout, StringBuilder stderr) throws IOException, InterruptedException Executes the specified command and arguments in a separate process.Warning: This method execute a system command. If unfiltered input is passed to this API, it can lead to arbitrary command execution.
Only use with trusted input.- Parameters:
cmdarray- array containing the command to call and its arguments.stdout- the result of the stdout (ignored if null)stderr- the result of the stderr (ignored if null)- Returns:
- the exit code
- Throws:
IOException- if an error occursInterruptedException- if an error occurs- Since:
- jcms-6.1.2
-
getCommonSuperClass
Retrieve the common super class of the specified classes. The following rules applies (CSC stands for Common Super Class):- CSC of null and any type is null.
- CSC of interface and any class is the interface if the class implements it, or Object otherwise.
- CSC of interface and any other interface is whichever interface extends (including indirectly) the other one, or Object if neither does.
- CSC of primitive type and any distinct type is null.
- CSC of array type and any distinct class is Object.
- Parameters:
classes- the classes for which superclass must be found, must not be null nor empty- Returns:
- the common class
-
getBytesUtf8
Encodes the specifiedStringinto a sequence of bytes using the given UTF-8 charset, storing the result into a new byte array.This method is provided as convenient method and as a workaround for performance bottleneck of Java native
string.getBytes(StandardCharsets.UTF_8);method.
See issue issue http://issues.jalios.com/browse/JCMS-2570 for more information.- Parameters:
string- The string to be encoded- Returns:
- The resultant byte array
- Since:
- jcms-7.1
-
getStringUtf8
Decode the specified array of bytes into a newStringusing the UTF-8 charset. The length of the newStringis a function of the charset, and hence may not be equal to the length of the byte array.This method is provided as convenient method and as a workaround for performance bottleneck of Java native
new String(bytes, StandardCharsets.UTF_8)method.
See issue issue http://issues.jalios.com/browse/JCMS-2570 for more information.- Parameters:
bytes- The bytes to be decoded into characters- Returns:
- The resultant String
- Since:
- jcms-7.1
-
getBatchSet
Convenient method to convert a Collection of object into many smaller collections allowing batch processing.Example :
List<String> abcdeList = Arrays.asList(new String[] {"a", "b", "c", "d", "e"}); Set<Set<String>> batchSet = Util.getBatchSet(abcdeList, 2); assertEquals(3, batchSet.size()); Iterator<Set<String>> batchIterator = batchSet.iterator(); assertEquals("a,b", Util.join(batchIterator.next(), ",")); assertEquals("c,d", Util.join(batchIterator.next(), ",")); assertEquals("e", Util.join(batchIterator.next(), ""));- Parameters:
coll- a collection of object, may be null (empty set returned)batchSize- the size of subset to be create, must be a positive integer otherwise- Returns:
- a Set containing subset of objects, never return null, always return at least one set of one empty batch
- Since:
- jcms-7.1.2
-
sum
Returns the sum of the collection of numbers.- Parameters:
values- the values to sum- Returns:
- the sum of the collection of numbers.
- Since:
- jcms-9.0.0
-
mean
Returns the mean of the collection of values.- Parameters:
values- the values to compute the mean- Returns:
- the mean of the collection of values.
- Since:
- jcms-9.0.0
-
sliceList
Slices the given list in a list of sub list containing less than max value per list.- Parameters:
list- the original listmax- the maximum size of each sub list- Returns:
- a List of sub list containing the original values with less than max value per sub list.
- Since:
- jcms-9.0.2
-
map2json
Returns the JSON for the given Map.- Parameters:
map- the Map.- Returns:
- the JSON for the given Map.
- Since:
- jcms-10.0.0
-
json2map
Returns the Map from the given JSON.- Parameters:
json- the JSON encoded map- Returns:
- the Map from the given JSON.
- Since:
- jcms-10.0.0
-
isValidEmail
Returns true if all the given emails are either null, empty or valid.- Parameters:
emails- the emails to test.- Returns:
- true if all the given emails are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidEmail
Checks that the given email is empty or has a valid email syntax.- Parameters:
email- the email to test.- Returns:
- true if the email is empty or valid
- Since:
- jcms-10.0.0
- See Also:
-
isValidEmail
Returns true if all the given emails are either null, empty or valid.- Parameters:
emails- the emails to test.- Returns:
- true if all the given emails are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidEmail
Returns true if all the given emails contained as value of the map are either null, empty or valid.- Parameters:
emailMap- a Map<String,String> or a Map<String,String[]>- Returns:
- true if all the given emails contained as value of the map are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUrl
Returns true if all the given urls are either null, empty or valid.- Parameters:
urls- the urls to test.- Returns:
- true if all the given urls are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUrl
Return true if the given url is null, empty or valid.- Parameters:
url- the url to test.- Returns:
- true if the given url is null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUrl
Returns true if all the given urls are either null, empty or valid.- Parameters:
urls- the urls to test.- Returns:
- true if all the given urls are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUrl
Returns true if all the given urls contained as value of the map are either null, empty or valid.- Parameters:
urlMap- a Map<String,String> or a Map<String,String[]>- Returns:
- true if all the given urls contained as value of the map are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUri
Returns true if all the given uris are either null, empty or valid.- Parameters:
uris- the uris to test.- Returns:
- true if all the given uris are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUri
Return true if the given uri is null, empty or valid.- Parameters:
uri- the uri to test.- Returns:
- true if the given uri is null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUri
Returns true if all the given uris are either null, empty or valid.- Parameters:
uris- the uris to test.- Returns:
- true if all the given uris are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidUri
Returns true if all the given uris contained as value of the map are either null, empty or valid.- Parameters:
uriMap- a Map<String,String> or a Map<String,String[]>- Returns:
- true if all the given uris contained as value of the map are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidString
Return true if the given string is null, empty or valid.- Parameters:
string- the url to test.p- the Predicate to validate the string- Returns:
- true if the given string is null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidString
Returns true if all the given strings are either null, empty or valid.- Parameters:
strings- the strings to test.p- the Predicate to validate the string- Returns:
- true if all the given strings are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidString
Returns true if all the given strings are either null, empty or valid.- Parameters:
strings- the strings to test.p- the Predicate to validate the string- Returns:
- true if all the given strings are either null, empty or valid.
- Since:
- jcms-10.0.0
-
isValidString
Returns true if all the given strings contained as value of the map are either null, empty or valid.- Parameters:
stringMap- a Map<String,String> or a Map<String,String[]>p- the Predicate to validate the string- Returns:
- true if all the given strings contained as value of the map are either null, empty or valid.
- Since:
- jcms-10.0.0
-
truncateVarchar
Truncates the given value to be compliant with standard VARCHAR limit (ie 255 chars)- Parameters:
v- the value- Returns:
- the given value if length is less than 255 or a truncated version.
- Since:
- jcms-9.0.5
-
truncateVarchar
Truncates the content of the given list to be compliant with standard VARCHAR limit (ie 255 chars)- Parameters:
list- the list- Returns:
- the received list with value truncated to 255 chars.
- Since:
- jcms-9.0.5
-
truncateVarchar
Truncates the content of the given set to be compliant with standard VARCHAR limit (ie 255 chars)- Parameters:
set- the set- Returns:
- the received set with value truncated to 255 chars.
- Since:
- jcms-9.0.5
-
getJVMVersion
public static int getJVMVersion()
-
If you need to encrypt data, use a dedicated library.