Class GrouperUtil
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfacehas fieldValue method -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final Stringstring format of datesstatic final Stringstring format of datesstatic final Stringstatic final Stringformat including minutes and seconds: yyyy/MM/dd HH:mm:ssstatic final Stringformat including minutes and seconds: yyyyMMdd HH:mm:ssstatic final intThe name says it all.static final StringThe empty String"".static final Object[]An empty immutableObjectarray.static final String[]An empty immutableStringarray.static final String[]array for converting HTML to stringstatic final String[]array for converting HTML to stringstatic final String[]array for converting HTML to stringstatic final intRepresents a failed index search.static final Stringstatic final Stringstatic final intspecial number when a number is not foundstatic final com.fasterxml.jackson.databind.ObjectMapperObject mapper to serialize and deserialize json string and beansstatic final longThe number of bytes in a gigabyte.static final longThe number of bytes in a kilobyte.static final longThe number of bytes in a megabyte.static Stringprompt key for reset datastatic Stringprompt key for schema exportstatic booleandont prompt while testing etc, but make sure there has been at least one promptmap of class to the list of fields which are string typestatic final Stringstring format of dates for file namesstatic final Stringformat on screen of config for milestone: yyyy/MM/dd HH:mm:ss.SSSstatic final Stringformat on screen of config for milestone: yyyyMMdd HH:mm:ss.SSSstatic final DateFormatstatic final DateFormatstatic final DateFormatstatic final DateFormatstatic final DateFormatstatic final DateFormatstatic final DateFormat -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic Stringabbreviate(String str, int maxWidth) Abbreviates a String using ellipses.static Stringabbreviate(String str, int offset, int maxWidth) Abbreviates a String using ellipses.static <T> voidaddIfNotThere(Collection<T> list, Collection<T> listToAdd) add each element of listToAdd if it is not already in liststatic voidappend(StringBuilder result, String separatorIfResultNotEmpty, String stringToAppend) append and maybe put a separator in therestatic booleanappendIfNotBlank(StringBuilder result, Object theStringOrArrayOrList) if theString is not blank, apppend it to the result, and if appending,static booleanappendIfNotBlank(StringBuilder result, String prefix, Object theStringOrArrayOrList) if theString is not Blank, apppend it to the result, and if appending, add a prefix (if not null)static booleanappendIfNotBlank(StringBuilder result, String prefix, Object theStringOrArrayOrList, String suffix) if theString is not Blank, apppend it to the result, and if appending, add a prefix and suffix (if not null)static booleanappendIfNotBlank(StringBuilder result, String prefix, String prefixIfNotBlank, Object theStringOrArrayOrList, String suffix) if theString is not Blank, apppend it to the result, and if appending, add a prefix and suffix (if not null)static StringappendIfNotBlankString(String string, String separator, String suffix) append a string to another string if both not blank, with separator.static booleanappendIfNotEmpty(StringBuilder result, Object theStringOrArrayOrList) if theString is not empty, apppend it to the result, and if appending,static booleanappendIfNotEmpty(StringBuilder result, String prefix, Object theStringOrArrayOrList) if theString is not empty, apppend it to the result, and if appending, add a prefix (if not null)static booleanappendIfNotEmpty(StringBuilder result, String prefix, Object theStringOrArrayOrList, String suffix) if theString is not empty, apppend it to the result, and if appending, add a prefix and suffix (if not null)static booleanappendIfNotEmpty(StringBuilder result, String prefix, String prefixIfNotEmpty, Object theStringOrArrayOrList, String suffix) if theString is not empty, apppend it to the result, and if appending, add a prefix and suffix (if not null)static StringappendPrefixIfStringNotBlank(String prefix, String separator, String string) append a prefix to another string if both not blank.static Stringreturn the arg after the argBefore, or null if not there, or exception if argBefore is not foundstatic <T> TarrayPopOne(T[] array) Return the zero element of the array, if it exists, null if the array is empty.static voidIf false, throw an assertException, and give a reasonstatic voidassignField(Class theClass, Object invokeOn, String fieldName, Object dataToAssign, boolean callOnSupers, boolean overrideSecurity, boolean typeCast, Class<? extends Annotation> annotationWithValueOverride) assign data to a fieldstatic voidassignField(Class theClass, Object invokeOn, String fieldName, Object dataToAssign, Class<? extends Annotation> annotationWithValueOverride) assign data to a field.static voidassignField(Object invokeOn, String fieldName, Object dataToAssign) assign data to a field.static voidassignField(Field field, Object invokeOn, Object dataToAssign, boolean overrideSecurity, boolean typeCast) assign data to a fieldstatic voidassignField(Field field, Object invokeOn, Object dataToAssign, boolean overrideSecurity, boolean typeCast, Class<? extends Annotation> annotationWithValueOverride) assign data to a fieldstatic voidassignSetter(Object invokeOn, String fieldName, Object dataToAssign, boolean typeCast) assign data to a setter.static <T> List<T>retrieve a batch by 0 index.static intbatchNumberOfBatches(int count, int batchSize) Deprecated.use batchNumberOfBatches(Collection<?static intbatchNumberOfBatches(int count, int batchSize, boolean haveAtLeastOne) If batching this is the number of batchesstatic intbatchNumberOfBatches(Collection<?> collection, int batchSize) Deprecated.use batchNumberOfBatches(Collection<?static intbatchNumberOfBatches(Collection<?> collection, int batchSize, boolean haveAtLeastOne) If batching this is the number of batches, will return at least 1static BigDecimalbigDecimalObjectValue(Object input) Convert an object to a byte, allow nullsstatic BooleanbooleanObjectValue(Object object) get the Boolean value for an objectstatic booleanbooleanValue(Object object) get the boolean value for an object, cant be null or blankstatic booleanbooleanValue(Object object, boolean defaultBoolean) get the boolean value for an objectstatic StringbyteCountToDisplaySize(long size) Returns a human-readable version of the file size (original is in bytes).static BytebyteObjectValue(Object input) Convert an object to a byte, allow nullsstatic byteconvert an object to a bytestatic ObjectcallMethod(Class theClass, Object invokeOn, String methodName) helper method for calling a method with no params (could be in superclass)static ObjectcallMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray) helper method for calling a method (could be in superclass)static ObjectcallMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray, boolean callOnSupers) helper method for calling a methodstatic ObjectcallMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray, boolean callOnSupers, boolean overrideSecurity) helper method for calling a methodstatic ObjectcallMethod(Class theClass, String methodName) helper method for calling a static method up the stack. method takes no args (could be in superclass)static ObjectcallMethod(Class theClass, String methodName, boolean callOnSupers) helper method for calling a static method with no paramsstatic ObjectcallMethod(Class theClass, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray) helper method for calling a static method up the stackstatic ObjectcallMethod(Object invokeOn, String methodName) helper method for calling a method with no params (could be in superclass), will override securitystatic ObjectcallMethodWithMoreParams(Object instance, Class<?> theType, String methodName, Object[] params) call method with more params.static Stringcapitalize(String str) Capitalizes a String changing the first letter to title case as perCharacter.toTitleCase(char).static Stringcapitalize(String str, char... delimiters) Capitalizes all the delimiter separated words in a String.static StringcapitalizeFully(String str) Converts all the whitespace separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.static StringcapitalizeFully(String str, char... delimiters) Converts all the delimiter separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.static ObjectchangeToVersion(Object input, String newPackage) convert an object from one version to anotherstatic ObjectchangeToVersionHelper(Object input, String newPackage, int timeToLive) convert an object from one version to anotherstatic booleancharacterMatchesRegex(Character character, String regex) static CharactercharObjectValue(Object input) get the Character wrapper value for the inputstatic charconvert an object to a charstatic booleancheckIfMembershipsMayPropagate(Set<Group> groups) static StringclassesString(Object object) print the simple names of a list of classesstatic ClassLoaderfast class loaderstatic Stringnull safe classname method, gets the unenhanced namestatic StringclassNameCollection(Object object) null safe classname method, max out at 20static <T> Tclone an object, assign primitives, Strings, maps of string attributes.static <T> voidcloneFields(T object, T result, Set<String> fieldsToClone) clone an object, assign primitives, Strings, maps of string attributes.static <T> TcloneValue(T value) helper method to clone the value of a field.static voidcloseQuietly(Closeable closeable) close a writer quietlystatic voidcloseQuietly(InputStream input) Unconditionally close anInputStream.static voidcloseQuietly(OutputStream output) Unconditionally close anOutputStream.static voidcloseQuietly(Reader input) Unconditionally close anReader.static voidcloseQuietly(Writer writer) close a writer quietlystatic voidcloseQuietly(Connection connection) close a connection null safe and dont throw exceptionstatic voidcloseQuietly(ResultSet resultSet) close a resultSet null safe and dont throw exceptionstatic voidcloseQuietly(Statement statement) close a statement null safe and dont throw exceptionstatic voidcloseQuietly(XMLStreamWriter writer) close a writer quietlystatic voidcloseQuietly(org.hibernate.Session session) close a session null safe and dont throw exceptionstatic booleancollectionContains(Collection<Object> collection, Object object) static <T> TcollectionPopOne(Collection<T> collection, boolean exceptionIfMoreThanOne) Return the zero element of the list, if it exists, null if the list is empty.static voidcollectionRemoveNulls(Collection<?> input) static StringcollectionToString(Collection collection) convert a set to a string (comma separate)static intcompare(Comparable first, Comparable second) compare null safecompare two objects, compare primitives, Strings, maps of string attributes.static URLcomputeUrl(String resourceName, boolean canBeNull) compute a url of a resourcestatic Stringconcat two stringsstatic Stringconcat stringsstatic Stringconcat stringsstatic Stringconcat stringsstatic <T> Tconstruct an instance by reflectionstatic booleanChecks if the object is in the given array.static booleanChecks if String contains a search character, handlingnull.static booleanChecks if String contains a search String, handlingnull.static booleancontainsConvertType(Collection set, Object value) static booleancontainsNewline(String string) contains newline since JSP cant have a quoted newlinesstatic StringconvertAdMemberDnToSpecificValue(String ldapConfigId, String dn, String baseDn, String grouperBaseStem, boolean idOrIdentifier) Deprecated.use ldapConvertAdMemberDnToSpecificValuestatic StringconvertDnToGroupName(String dn, String baseDn, String grouperBaseStem) Deprecated.use ldapConvertDnToGroupNamestatic StringDeprecated.use GrouperUtil.ldapConvertDnToSpecificValue(String)static StringconvertDnToSpecificValueOrGroup(String dn, String groupPrefix, String groupSuffix, boolean createGroupIfNotThere, boolean idOrIdentifier) Deprecated.use GrouperUtil.ldapConvertDnToSpecificValueOrGroup(String, String, String, boolean, boolean)static StringconvertDnToSubPath(String dn, String baseDn, String searchDn) Deprecated.use GrouperUtil.ldapConvertDnToSubPath(String, String, String)static StringconvertLDAPMemberDnToSubjectIdOrGroup(String dn, String baseOu, String grouperBaseStem, String serverId, String uniqueAttribute, boolean idOrIdentifier) Deprecated.use ldapConvertLDAPMemberDnToSubjectIdOrGroupstatic StringconvertLongToChar(long theLong) this method takes a long (less than 62) and converts it to a 1 character string (a-z, A-Z, 0-9)static StringconvertLongToCharSmall(long theLong) this method takes a long (less than 36) and converts it to a 1 character string (A-Z, 0-9)static StringconvertLongToString(long theLong) convert a long to a string by converting it to base 62 (26 lower, 26 upper, 10 digits)static StringconvertLongToStringSmall(long theLong) convert a long to a string by converting it to base 36 (26 upper, 10 digits)static StringconvertMillisToFriendlyString(Integer duration) convert millis to friendly stringstatic StringconvertMillisToFriendlyString(Long duration) convert millis to friendly stringconvertSources(String sources) e.g.convertSources(String[] sourceIds) e.g.static StringconvertSourcesToSqlInString(Set<Source> sources) Deprecated.moved to @See HibUtilsstatic voidcopy(InputStream input, Writer output) Copy bytes from anInputStreamto chars on aWriterusing the default character encoding of the platform.static voidcopy(InputStream input, Writer output, String encoding) Copy and convert bytes from anInputStreamto chars on aWriter, using the specified encoding.static intCopy chars from aReaderto aWriter.static voidcreateParentDirectories(File file) Create the parent directories for a file if they do not already existstatic LongdateLongValue(String date) convert a string date into a long date (e.g. for xml export)static StringdateStringValue(Long theDate) date object to a string:static StringdateStringValue(Date date) date object to a string:static StringdateToString(Date date) convert a date to a string using the standard web service pattern yyyy/MM/dd HH:mm:ss.SSS Note that HH is 0-23static DateConvert an object to a java.util.Date.static StringdbVersionDescribeDifferences(Object theOld, Object theNew, Set<String> differentFieldNames) put in english how an object changedstatic StringdefaultIfBlank(String string, String defaultStringIfBlank) return the string or the other if the first is blankstatic StringdefaultIfEmpty(String str, String defaultStr) Returns either the passed in String, or if the String is empty ornull, the value ofdefaultStr.static <T> TdefaultIfNull(T theValue, T defaultIfTheValueIsNull) genericized method to see if first is null, if so then return second, else first.static StringdefaultString(String str) Returns either the passed in String, or if the String isnull, an empty String ("").static StringdefaultString(String str, String defaultStr) Returns either the passed in String, or if the String isnull, the value ofdefaultStr.static voiddeleteFile(File file) Delete a file, throw exception if cannotstatic DoubledoubleObjectValue(Object input, boolean allowNullBlank) get the Double value of an objectstatic doubledoubleValue(Object input) get the double value of an objectstatic doubledoubleValueNoError(Object input) get the double value of an object, do not throw an exception if there is an errorstatic StringencryptSha(String plaintext) encrypt a message to SHAstatic StringencryptShaHex(String plaintext) encrypt a message to SHAstatic <E extends Enum<?>>
EenumValueOfIgnoreCase(Class<E> theEnumClass, String string, boolean exceptionOnBlank) do a case-insensitive matchingstatic <E extends Enum<?>>
EenumValueOfIgnoreCase(Class<E> theEnumClass, String string, boolean exceptionOnBlank, boolean exceptionIfInvalid) do a case-insensitive matchingstatic booleanCompares two objects for equality, where either one or both objects may benull.static booleannull safe string comparestatic booleanequalsCollectionStringLong(Collection<?> collection1, Collection<?> collection2) see if two collections are deep equals based on strings or longs (or conversions)static booleanequalsIgnoreCase(String str1, String str2) equalsignorecasestatic booleanequalsIgnoreCaseObject(Object object1, Object object2) Compares two objects for equality, where either one or both objects may benull.static booleanequalsList(List<?> list1, List<?> list2) see if two lists are deep equals using the equals() method on each itemstatic booleanequalsLong(Object thisValue, Object thatValue) see if two objects long value is the samestatic booleansee if two sets are deep equals using the equals() method on each itemstatic booleanequalsString(Object thisValue, Object thatValue) see if two strings are equal (or the strings they convert into)static StringescapeDoubleQuotes(String string) escape double quotes in javascriptstatic StringescapeDoubleQuotesForString(String string) escape double quotes in javascriptstatic Stringescape double quotes in javascriptstatic StringescapeHtml(String input, boolean isEscape) Convert an XML string to HTML to display on the screenstatic StringescapeHtml(String input, boolean isEscape, boolean escapeSingleQuotes) Convert an XML string to HTML to display on the screenstatic StringescapeNewlinesForString(String string) escape double quotes in javascriptstatic StringescapeSingleQuotes(String string) escape single quotes in javascriptstatic StringescapeSlashesForString(String string) escape slashesstatic StringescapeUrlDecode(String string) unescape url chars (e.g. a space is %20)static StringescapeUrlEncode(String string) escape url chars (e.g. a # is %23)static Stringexception4kZipBase64(String exception) take out packages and whitespace from stackstatic RuntimeExceptionstatic RuntimeExceptionexceptionConvertToRuntime(Throwable t, String inject) static voidexceptionFinallyInjectOrThrow(Exception tryException, Exception finallyException) in a finally block, take an exception and inject and throw the existing exception, or just throw the finally exceptionstatic StringexceptionTruncate(String exception) truncate an exception stack to be less than 3.5kstatic StringexceptionWithoutClasses(String exception) take out packages and whitespace from stackstatic StringexceptionWithoutDupes(String exception) take out packages and whitespace from stackstatic StringexceptionWithoutPackages(String exception) take out packages and whitespace from stackstatic GrouperFutureexecutorServiceSubmit(ExecutorService executorService, GrouperCallable callable, boolean willRetry) static <T> GrouperFuture<T>executorServiceSubmit(ExecutorService executorService, Callable<T> callable) you should probably use the GrouperCallable method, not this onestatic voidexecutorServiceSubmit(ExecutorService executorService, List<GrouperCallable<Void>> callables) static StringextensionFromName(String name) get the extension from name.static Fieldget a field object for a class, potentially in superclassesfieldNames(Class theClass, Class fieldType, boolean includeStaticFields) return a set of Strings for a class and type.fieldNames(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields) get all field names from a class, including superclasses (if specified)fieldNames(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields, Class<? extends Annotation> markerAnnotationToIngore) get all field names from a class, including superclasses (if specified).fieldNames(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotationToIngore) get all field names from a class, including superclasses (if specified) (up to and including the specified superclass). ignore a certain marker annotation.fields(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get all fields from a class, including superclasses (if specified) (up to and including the specified superclass). ignore a certain marker annotation, or only include it.fields(Class theClass, Class superclassToStopAt, Class fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get all fields from a class, including superclasses (if specified)static ObjectfieldValue(Class theClass, Object invokeOn, String fieldName, boolean callOnSupers, boolean overrideSecurity, boolean considerFieldValuable) find out a field valuestatic ObjectfieldValue(Object invokeOn, String fieldName) find out a field value (invoke on supers, override security)static ObjectfieldValue(Field field, Object invokeOn) get the value of a field, override security if needbestatic ObjectfieldValue(Field field, Object invokeOn, boolean overrideSecurity) get the value of a fieldstatic StringfileCanonicalPath(File file) get canonical path of filestatic voidstatic voidfileCopyExampleResourceIfNotExist(String exampleResource, String resource) static booleanfileCreateNewFile(File file) create a new filefileDescendantDirsRelativePaths(File parentDir) get the relative paths of descendant filesfileDescendantRelativePaths(File parentDir) get the relative paths of descendant filesstatic FilefileFromResourceName(String resourceName) get a file name from a resource namefileListRecursive(File parent) list files recursively from parent, dont includefileListRecursiveDirs(File parent) list dirs recursively from parent, dont includestatic booleanfindGrouperPropertiesDbMatch(boolean whitelist, String user, String url) see if there is a grouper properties db matchfindParentStemNames(String objectName) if the groups are: a:b:c:d, then return the strings: :, a, a:b, a:b:cfindParentStemNames(Collection<Group> groups) if the groups are: a:b:c:d and a:d:r, then return the strings: :, a, a:b, a:b:c, a:dstatic StringfixRelativePath(String inPath) static FloatfloatObjectValue(Object input, boolean allowNullBlank) get the Float value of an objectstatic floatfloatValue(Object input) get the float value of an objectstatic floatfloatValue(Object input, float defaultValue) get the float value of an objectstatic floatfloatValueNoError(Object input) get the float value of an object, do not throw an exception if there is an errorstatic StringformatNumberWithCommas(Long number) static ClassReturns the class object.static String[]generateRsaKeypair(int keySize) generate RSA key public private pair.static ObjectGet a specific index of an array or collection (note for collections and iterating, it is more efficient to get an iterator and iteratestatic StemReturns the first existing parent stem of a given name.static StringReturn a string that combines the standard and daylight timezones of the server into one string separated by a slash that can be used in an input description to inform the user of the server timezone.static StringgetFullStackTrace(Throwable throwable) A way to get the entire nested stack-trace of an throwable.static StringgetFullStackTraceHtml(Throwable throwable) A way to get the entire nested stack-trace of an throwable.static Stringstatic StringgetLocationFromResourceName(String resourceName) get a full path from a resource namestatic org.apache.commons.logging.Logget a logger, and auto-create log dirs if havent done yetstatic LonggetMaxLongValue(Long... values) static LonggetMinLongValue(Long... values) static Methodget a getter method object for a class, potentially in superclassesstatic MethodgetterHelper(Class theClass, String fieldName, String getterName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a setter method object for a class, potentially in superclassesstatic StringgetterNameFromPropertyName(Class theClass, String propertyName) generate getBb from bbgetters(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotation, Boolean includeAnnotation) get all getters from a class, including superclasses (if specified) (up to and including the specified superclass).static voidget out of gsh with normal return codestatic voidgshReturn(int returnCode) get out of GSH with return codestatic StringgshRunScript(String script) run a GSH scriptstatic StringgshRunScript(String script, boolean lightWeight) run a GSH scriptgshRunScriptReturnResult(String script, boolean lightWeight) run a GSH scriptstatic booleanhasOption(int options, int option) see if options have a specific option by int bitsstatic Stringhostname()get the hostname of this machinestatic charincrementChar(char theChar) increment a character (A-Z then 0-9)static char[]incrementStringInt(char[] string) Increment a string with A-Z and 0-9 (no lower case so case insensitive apps like windows IE will still work)static Stringthis method will indent xml or json.static intFind the index of the given object in the array.static intFind the index of the given object in the array starting at the given index.static booleaninjectInException(Throwable t, String message) If we can, inject this into the exception, else return falsestatic IntegerintObjectValue(Object input, boolean allowNullBlank) get the Integer value of an objectstatic intconvert an object to a intstatic intconvert an object to a intstatic intintValueNoError(Object input) get the int value of an object, do not throw an exception if there is an errorstatic ObjectinvokeMethod(Method method, Object invokeOn) Safely invoke a reflection method that takes no argsstatic ObjectinvokeMethod(Method method, Object invokeOn, Object paramsOrListOrArray) Safely invoke a reflection methodstatic intget the ip addres integer from a string ip addressstatic booleanipOnNetwork(String ipString, String networkIpString, int mask) see if an ip address is on a networkstatic booleanipOnNetworks(String ipString, String networkIpStrings) see if an ip address is on a networkstatic intipReadyForAnd(int ip, int maskLength) get the ip address after putting 1's where the subnet mask is notstatic booleanisArrayOrCollection(Object arrayOrCollection) is array or collectionstatic booleanisAscii(char input) is ascii charstatic booleanSee if the input is null or if string, if it is empty or blank (whitespace)static booleanChecks if a String is whitespace, empty ("") or null.static booleanSee if the input is null or if string, if it is empty (whitespace)static booleanChecks if a String is empty ("") or null.static booleanif the method name starts with get, and takes no args, and returns something, then getterstatic booleanstatic booleanisNotBlank(String str) static booleanif the grouper logs go to the console or notstatic booleansee if a class is a scalar (not bean, not array or list, etc)static booleanif the method name starts with get, and takes no args, and returns something, then getterstatic booleansee if we are running on windowsstatic Iteratornull safe iterator getter if the type if collectionstatic Stringget the source IP address or null if cantstatic Fileget a jar file from a sample classstatic StringJoins the elements of the provided array into a single String containing the provided list of elements.static StringJoins the elements of the provided array into a single String containing the provided list of elements.static StringJoins the elements of the provided array into a single String containing the provided list of elements.static StringJoins the elements of the providedIteratorinto a single String containing the provided elements.static StringJoins the elements of the providedIteratorinto a single String containing the provided elements.static <T> TjsonConvertFrom(com.fasterxml.jackson.databind.JsonNode jsonNode, Class<T> theClass) convert a jsonNode into POJO.static <T> TjsonConvertFrom(String json, Class<T> theClass) convert an object from json.static ObjectjsonConvertFrom(Map<String, Class<?>> conversionMap, String json) convert an object from json.static <T> TjsonConvertFromMap(Map<String, Object> jsonMap, Class<T> theClass) convert an object from Map.static com.fasterxml.jackson.databind.node.ObjectNodeconvert a POJO into ObjectNodestatic StringjsonConvertTo(Object object) convert an object to json.static StringjsonConvertTo(Object object, boolean includeObjectNameWrapper) convert an object to json.static voidjsonConvertTo(Object object, Writer writer) convert an object to json.static StringjsonConvertToNoWrap(Object object) convert an object to json without wrapping it with the simple class name.static com.fasterxml.jackson.databind.node.ArrayNodestatic voidjsonJacksonAssignBoolean(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Boolean value) assign a jackson fieldstatic voidjsonJacksonAssignJsonPointerString(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Object value) assign a jackson fieldstatic voidjsonJacksonAssignLong(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Long value) assign a jackson fieldstatic voidjsonJacksonAssignObjectNodeArray(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Collection<com.fasterxml.jackson.databind.node.ObjectNode> values) assign a jackson arraystatic voidjsonJacksonAssignString(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, String value) assign a jackson fieldstatic voidjsonJacksonAssignStringArray(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Collection<String> values) assign a jackson fieldjsonJacksonFieldNames(com.fasterxml.jackson.databind.JsonNode jsonNode) get field names from json node, assume field names are uniquestatic com.fasterxml.jackson.databind.node.ArrayNodejsonJacksonGetArrayNode(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as node or array.static BooleanjsonJacksonGetBoolean(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as boolean and handle nullstatic BooleanjsonJacksonGetBoolean(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, Boolean defaultBoolean) get a field as boolean and handle nullstatic BooleanjsonJacksonGetBooleanFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as boolean and handle nullstatic BooleanjsonJacksonGetBooleanFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Boolean defaultBoolean) get a field as boolean and handle nullstatic IntegerjsonJacksonGetInteger(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as integer and handle nullstatic IntegerjsonJacksonGetInteger(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, Integer defaultInteger) get a field as integer and handle nullstatic IntegerjsonJacksonGetIntegerFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as integer and handle nullstatic IntegerjsonJacksonGetIntegerFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Integer defaultInteger) get a field as integer and handle nullstatic LongjsonJacksonGetLong(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as long and handle nullstatic LongjsonJacksonGetLong(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, Long defaultLong) get a field as long and handle nullstatic LongjsonJacksonGetLongFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as long and handle nullstatic LongjsonJacksonGetLongFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Long defaultLong) get a field as long and handle nullstatic com.fasterxml.jackson.databind.JsonNodejsonJacksonGetNode(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as node or array.static com.fasterxml.jackson.databind.JsonNodejsonJacksonGetNodeFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as node or array.static StringjsonJacksonGetString(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as string and handle nullstatic StringjsonJacksonGetString(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, String defaultString) get a field as string and handle nullstatic StringjsonJacksonGetString(com.fasterxml.jackson.databind.node.ArrayNode arrayNode, int index) get a field as string and handle nullstatic StringjsonJacksonGetStringFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as string and handle nullstatic StringjsonJacksonGetStringFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, String defaultString) get a field as string and handle nulljsonJacksonGetStringSet(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as string set.jsonJacksonGetStringSetFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as string set.jsonJacksonListObjectArrayFromJsonPointers(com.fasterxml.jackson.databind.JsonNode rootJsonNode, String jsonPointerOfArrayNode, List<String> jsonPointersOfSubFields) start the sub field with JSON_NODE_ROOT if you want the pointer from root node instead of array nodestatic com.fasterxml.jackson.databind.node.ObjectNodestatic com.fasterxml.jackson.databind.JsonNodejsonJacksonNode(String json) static StringjsonJacksonToString(com.fasterxml.jackson.databind.JsonNode jsonNode) convert a json node to actual jsonstatic longactive directory date from millis 1970 datestatic longldapAdDateFromMillis1970(long millisSince1970) active directory date from millis 1970 datestatic StringldapBushyDn(String groupName, String rdnAttributeName, String ouAttributeName, boolean performRdnEscaping, boolean performFilterEscaping) static StringldapBushyDn(String groupName, String rdnAttributeName, String rdnAttributeValue, String ouAttributeName, boolean performRdnEscaping, boolean performFilterEscaping) static StringldapConvertAdMemberDnToSpecificValue(String ldapConfigId, String dn, String baseDn, String grouperBaseStem, boolean idOrIdentifier) convert a user dn to a user CN, and a group dn to a group ID or Uuidstatic StringldapConvertDnToGroupName(String dn, String baseDn, String grouperBaseStem) convert a DN to a group namestatic Stringconvert from uid=someapp,ou=people,dc=myschool,dc=edu to someappstatic StringldapConvertDnToSpecificValueOrGroup(String dn, String groupPrefix, String groupSuffix, boolean createGroupIfNotThere, boolean idOrIdentifier) convert from uid=someapp,ou=people,dc=myschool,dc=edu to someapp and allow groupsstatic StringldapConvertDnToSubPath(String dn, String baseDn, String searchDn) convert from uid=someapp,ou=people,dc=myschool,dc=edu baseDn is edu searchDn is myschool to people:someapp i.e. take apart a bushy dnsstatic StringldapConvertLDAPMemberDnToSubjectIdOrGroup(String dn, String baseOu, String grouperBaseStem, String serverId, String uniqueAttribute, boolean idOrIdentifier) convert a subject dn to a user RDN value, and a group dn to a group ID or Uuidstatic StringldapEscapeRdn(String rdnString) This takes a string of attribute=value and makes sure that special, dn-relevant characters are escaped, particularly commas, pluses, etcstatic StringldapEscapeRdnValue(String rdnValue) This takes a string of value and makes sure that special, dn-relevant characters are escaped, particularly commas, pluses, etcstatic Stringstatic StringLeft pad a String with spaces (' ').static StringLeft pad a String with a specified character.static StringLeft pad a String with a specified String.static intNull safe array length or mapstatic intlengthAscii(String input) find the length of ascii chars (non ascii are counted as two)static <T> List<T>listFromCollection(Collection<T> collection) null safe convert collection to liststatic <T> TlistPopOne(List<T> list) Return the zero element of the list, if it exists, null if the list is empty.static <K,V> Map<K, V> turn a list into mapstatic Stringprint the log dir to the console so the logs are easy to findstatic voidauto-create log dirs if not done yetstatic voidlogErrorNextException(org.apache.commons.logging.Log log, Throwable throwable, int timeToLive) find a next exception in the stack and log itstatic StringlogFirstMax(Collection<?> collection, int numberToLog) log first few items, separate with semicolons and spacesstatic LonglongObjectValue(Object input, boolean allowNullBlank) get the Long value of an objectstatic longconvert an object to a longstatic longconvert an object to a longstatic longlongValueNoError(Object input) get the long value of an object, do not throw an exception if there is an errorstatic voidstatic voidmapAddValue(Map<String, Object> map, String key, int numberToAdd) in a map get a value if there and increment or set a valuestatic voidmapAddValue(Map<String, Object> map, String key, long numberToAdd) in a map get a value if there and increment or set a valuestatic intmapAddValueObjectKey(Map<Object, Object> map, Object key, int numberToAdd) in a map get a value if there and increment or set a valuestatic longmapAddValueObjectKey(Map<Object, Object> map, Object key, long numberToAdd) in a map get a value if there and increment or set a valuestatic <K,V> void mapDifferences(Map<K, V> first, Map<K, V> second, Set<K> differences, String prefix) see if two maps are the equivalent (based on number of entries, and the equals() method of the keys and values)static <K,V> boolean see if two maps are the equivalent (based on number of entries, and the equals() method of the keys and values)static StringmapToString(Map map) convert a set to a string (comma separate)static StringMapToString(Map map) Deprecated.use mapToString(map)static booleanmatchSqlString(String sqlMatcher, String testText) match sqlLike string see if a sql like string matches a real string.static Methodmethod(Class<?> theClass, String methodName, Object paramTypesOrArrayOrList, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean isStaticOrInstance, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get the set of methodsstatic MethodmethodByName(Class<?> theClass, String methodName, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, boolean exceptionIfNotFound) simple method to get method namesmethodNames(Class<?> theClass, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods) simple method to get method namesstatic voidmethodsByNameHelper(Class<?> theClass, String methodName, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation, Set<Method> methodSet) get the set of methodsstatic voidmethodsHelper(Class<?> theClass, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation, Set<Method> methodSet) get the set of methodsstatic voidCreate directories, throw exception if not possible.static intconvert a month string to an int (1 indexed).multiKeySet(Collection<Object[]> collection) take a collection of Objectp[static booleannameInFolderDirect(String name, String folder) see if a name is in a folder (not subfolder).static FilenewFileUniqueName(String parentDirName, String namePrefix, String nameSuffix, boolean createFile) make a new file in the name prefix dir.static <T> TnewInstance(Class<T> theClass) Construct a classstatic ObjectIf array, get the element based on index, if Collection, get it based on iterator.static <T> Collection<T>nonNull(Collection<T> list) make sure a collection is non null.static <T> List<T>make sure a list is non null.static <K,V> Map<K, V> make sure it is non null, if null, then give new mapstatic <T> Set<T>make sure a list is non null.static <T> T[]make sure a array is non null.static StringDeprecated.use this instead org.apache.commons.lang3.StringUtils.stripAccents((String)currentValue);static StringnormalizeEmailAddresses(String emailAddresses) take email addresses from a textarea and turn them into semi separatedstatic booleannullOrBlank(Object object) is an object null or blankstatic StringoracleStandardNameFromJava(String javaName) get the oracle underscore name e.g. javaNameHere -> JAVA_NAME_HEREstatic longpackInts(int first, int second) pack two ints into a long.static StringparentStemNameFromName(String name) Deprecated.dont use this!static StringparentStemNameFromName(String name, boolean nullForRoot) get the parent stem name from name.static booleanportAvailable(int port, String ipAddress) Checks to see if a specific port is available.static booleanportAvailableWait(int port, String ipAddress, int seconds, boolean expectingListening) static StringprefixOrSuffix(String startString, String separator, boolean isPrefix) get the prefix or suffix of a string based on a separatorstatic voidpromptUserAboutChanges(String reason, boolean checkResponse, String dbType, String url, String user) prompt the user about db changesstatic voidpromptUserAboutDbChanges(String reason, boolean checkResponse) prompt the user about db changesstatic PropertiespropertiesFromFile(File file, boolean useCache) properties from filestatic PropertiespropertiesFromResourceName(String resourceName) read properties from a resource, dont modify the properties returned since they are cachedstatic PropertiespropertiesFromResourceName(String resourceName, boolean useCache, boolean exceptionIfNotExist) read properties from a resource, dont modify the properties returned since they are cachedstatic PropertiespropertiesFromUrl(String urlString, boolean useCache, boolean useFailSafeCache, GrouperHtmlFilter grouperHtmlFilter) this will get the properties from an external url.propertiesThreadLocalOverrideMap(String propertiesFileName) override map for properties in thread local to be used in a web server or the like, based on property file namestatic StringpropertiesToString(Properties properties) convert properties to a string (comma separate)static StringpropertiesValue(Properties properties, String key) get a value (trimmed to e) from a property filestatic StringpropertiesValue(Properties properties, Map<String, String> overrideMap, String key) get a value (trimmed to e) from a property filestatic StringpropertiesValue(Properties properties, Map<String, String> overrideMap, Map<String, String> overrideMap2, String key) get a value (trimmed to e) from a property filestatic booleanpropertiesValueBoolean(Properties properties, String propertyName, boolean defaultValue) get a boolean property, or the default if cant findstatic booleanpropertiesValueBoolean(Properties properties, Map<String, String> overrideMap, String propertyName, boolean defaultValue) get a boolean property, or the default if cant findstatic booleanpropertiesValueBoolean(Properties properties, Map<String, String> overrideMap, Map<String, String> overrideMap2, String propertyName, boolean defaultValue) get a boolean property, or the default if cant findstatic <T> List<T>propertyList(Collection<?> collection, String propertyName, Class<T> fieldType) take a collection of beans, and go through and get all the values of one of the javabean properties, and make a list of those values.static StringpropertyName(Method method) If this is a getter or setter, then get the property namestatic ClasspropertyType(Class theClass, String propertyName) use reflection to get a property type based on getter or setter or fieldstatic ObjectpropertyValue(Object object, String property) this assumes the property exists, and is a simple propertystatic StringreadFileIntoString(File file) static StringreadFileToString(File file, String encoding) Reads the contents of a file into a String.static StringreadFromFileIfFile(String in, boolean disableExternalFileLookup) if the input is a file, read string from file.static StringreadResourceIntoString(String resourceName, boolean allowNull) static StringregexGroup(String regex, String input) run a regex on a string and return first group or null if not matches.static ObjectRemove the iterator or indexstatic ObjectRemove the iterator or indexstatic StringRepeat a Stringrepeattimes to form a new String.static voidreplace a string or strings from a string, and put the output in a string buffer.static voidreplace a string or strings from a string, and put the output in a string bufferstatic voidreplace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith) replace a string or strings from a string, and put the output in a string buffer.static voidreplace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith, boolean recurse) replace a string or strings from a string, and put the output in a string bufferstatic Stringreplace a string or strings from a string, and put the output in a string buffer.static Stringreplace a string or strings from a string, and put the output in a string bufferstatic Stringreplace a string or strings from a string, and put the output in a string bufferstatic StringReplaces all occurrences of a String within another String.static StringReplaces a String with another String inside a larger String, for the firstmaxvalues of the search String.static StringreplaceWhitespaceWithSpace(String input) replace all whitespace with spacestatic <T> TretrieveByProperties(Collection<T> collection, List<String> propertyNames, List<Object> propertyValues) find an object (or objects) in a collection based on fieldsstatic <T> TretrieveByProperty(Collection<T> collection, String propertyName, Object propertyValue) find an object (or objects) in a collection based on fieldsstatic ExecutorServicemight want to use GrouperCallable with this.static <T> List<T>retrieveListByProperties(Collection<T> collection, List<String> propertyNames, List<Object> propertyValues) find an object (or objects) in a collection based on fieldsstatic <T> List<T>retrieveListByProperty(Collection<T> collection, String propertyName, Object propertyValue) find an object (or objects) in a collection based on fieldsstatic StringretrievePasswordFromStdin(boolean dontMask, String prompt) retrieve a password from stdinstatic final char[]retrievePasswordFromStdin(InputStream in, String prompt) static PropertyDescriptorretrievePropertyDescriptor(Object object, String property) if there is a valid accessible property descriptor, get itstatic StringRight pad a String with spaces (' ').static StringRight pad a String with a specified character.static StringRight pad a String with a specified String.static voidrollbackQuietly(Connection connection) rollback a connection quietlystatic voidrollbackQuietly(org.hibernate.Transaction transaction) rollback a transaction quietlystatic voidsaveStringIntoFile(File file, String contents) save a string into a file, file does not have to existstatic booleansaveStringIntoFile(File file, String contents, boolean onlyIfDifferentContents, boolean ignoreWhitespace) save a string into a file, file does not have to existsetAppendStringToItems(Set<String> setOfStrings, String suffix) static voidsetClear(Collection<?> set) static <T> TReturn the zero element of the set, if it exists, null if the list is empty.static <T> Set<T>setShorten(Set<T> theSet, int maxSize) shorten a set if it is too longstatic Methodget a setter method object for a class, potentially in superclassesstatic MethodsetterHelper(Class theClass, String fieldName, String setterName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a setter method object for a class, potentially in superclassesstatic StringsetterNameFromPropertyName(String propertyName) generate setBb from bbsetters(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get all setters from a class, including superclasses (if specified)static StringsetToString(Set set) convert a set to a string (comma separate)static ShortshortObjectValue(Object input) get the Short value of an object.static shortshortValue(Object input) convert an object to a shortstatic voidsleep(long millis) sleep, if interrupted, throw runtimestatic voidsleepWithStdoutCountdown(int seconds) sortByIds(Collection<String> ids, Collection<T> grouperObjects) based on some ids, sort a set of grouper objects by thatstatic String[]Splits the provided text into an array, using whitespace as the separator.static String[]Splits the provided text into an array, separator specified.static String[]Splits the provided text into an array, separators specified.static String[]Splits the provided text into an array with a maximum length, separators specified.static String[]splitByWholeSeparator(String str, String separator) Splits the provided text into an array, separator string specified.static String[]splitByWholeSeparator(String str, String separator, int max) Splits the provided text into an array, separator string specified.splitFileLines(String fileContents) split a file on whitespacestatic String[]Splits the provided text into an array, using whitespace as the separator, preserving all tokens, including empty tokens created by adjacent separators.static String[]splitPreserveAllTokens(String str, char separatorChar) Splits the provided text into an array, separator specified, preserving all tokens, including empty tokens created by adjacent separators.static String[]splitPreserveAllTokens(String str, String separatorChars) Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.static String[]splitPreserveAllTokens(String str, String separatorChars, int max) Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.static String[]split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)static String[]split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)splitTrimCommas(String input, String commaSeparatedAttributes, String regexAllowedChars, String replaceChar) split by commas.splitTrimCurlyColons(String input, String commaSeparatedAttributes, String regexAllowedChars, String replaceChar) split by curly colons.static StringsplitTrimEmailAddresses(String emailAddresses) take email addresses from a textarea and turn them into semi separatedsplitTrimToList(String input, String separator) split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)splitTrimToSet(String input, String separator) split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)static Stringstack()get a couple of lines of stackstatic Stringget a short stack trace from a throwable, only edu.internet2 linesstemCalculateTopLevelStems(Set<String> stems) if these are the stems to sync: a:b:c, a:b, a:d, a:b:d, then the top level are: a:b, a:dstatic voidstemRemoveAncestorStemsOfChildStem(Collection<String> stemNames) remove stems that are ancestor of the child stemstatic voidstemRemoveChildStemsOfTopStem(List<Stem> stems) remove stems that are children of the top level stemstatic voidstemRemoveChildStemsOfTopStemName(Collection<String> stemNames) remove stems that are children of the top level stemstringFieldNames(Class<?> theClass) get the list of string field names based on class, and cache thisstatic StringstringFormatNameReverseReplaceTruncate(String name, String newSeparator, int maxLength) assertEquals("c.b.a", edu.internet2.middleware.grouper.util.GrouperUtil.stringFormatNameReverseReplaceTruncate("a:b:c", ".", -1)); assertEquals("c.b.", edu.internet2.middleware.grouper.util.GrouperUtil.stringFormatNameReverseReplaceTruncate("a:b:c", ".", 4));static intstringLength(String string) string lengthstatic DatestringToDate(String dateString) convert a string to a date using the standard web service pattern Note that HH is 0-23static DatestringToDate2(String input) take as input: yyyy/mm/dd yyyy-mm-dd dd-mon-yyyy yyyy/mm/dd hh:mm:ss dd-mon-yyyy hh:mm:ss yyyy/mm/dd hh:mm:ss.SSS dd-mon-yyyy hh:mm:ss.SSSstatic DatestringToDate3(String dateString, String configuredDateFormat) Parse a date string from the UI.static TimestampstringToTimestamp(String input) convert a string to timestamp based on the following formats: yyyyMMdd yyyy/MM/dd yyyy/MM/dd HH:mm:ss yyyy/MM/dd HH:mm:ss.SSS yyyy/MM/dd HH:mm:ss.SSSSSSstatic Timestampconvert a string to timestamp based on the following formats: 2022-02-15T15:27:42 2022-02-15T15:27static Timestampconvert a string to timestamp based on the following formats: 2011-07-18T15:24+02:00 2011/07/18 15:24 2011/07/18 3:24 PMstatic StringstringValue(Object input) convert an object to a stringstatic StringstringValue(Date date) convert a date to the standard string yyyymmddstatic StringDeprecated.use stripSuffix insteadstatic StringstripFirstSlashIfExists(String input) strip the first slash (/ or \) from a string if it existsstatic Stringstrip the last comma or semi from a string if it existsstatic StringstripLastSlashIfExists(String input) strip the last slash (/ or \) from a string if it existsstatic StringstripPrefix(String string, String prefix) strip the prefix offstatic StringstripStart(String str, String stripChars) Strips any of a set of characters from the start of a String.static StringstripSuffix(String string, String suffix) strip the suffix offstatic booleansubjectHasAttribute(Subject subject, String attributeName) see if a subject has an attributestatic StringsubjectToString(Subject subject) convert a subject to string safelystatic StringsubstituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap) substitute an EL for objectsstatic StringsubstituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses) Deprecated.static StringsubstituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent) substitute an EL for objectsstatic StringsubstituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) substitute an EL for objectsstatic ObjectsubstituteExpressionLanguageScript(String script, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) substitute an EL for objectsstatic StringsubstituteExpressionLanguageScriptsNotExpressions(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) Template-mode substitution where each ${...} block is evaluated as a JEXL script (multi-statement, supports `var` declarations, can return a non-string value) rather than a single expression.static StringsubstituteExpressionLanguageTemplate(String script, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) substitute an EL for objectsstatic voidsubstituteExpressionPrintNode(org.apache.commons.jexl2.parser.JexlNode jexlNode, String prefix) static booleansubstituteStrings(Map<String, String> stringSubstituteMap, Object object) see if the object has string fields with members in them (by memberUuid), and if so, export that memberstatic voidsubstituteVariableMapPrint(Map<String, Object> variableMap) print out a variable map as java to try to debug whats going onstatic StringsubstringAfter(String str, String separator) Gets the substring after the first occurrence of a separator.static StringsubstringAfterLast(String str, String separator) Gets the substring after the last occurrence of a separator.static StringsubstringBefore(String str, String separator) Gets the substring before the first occurrence of a separator.static StringsubstringBeforeLast(String str, String separator) Gets the substring before the last occurrence of a separator.static StringsuffixAfterChar(String input, char theChar) return the suffix after a char.static voidthreadJoin(Thread thread) join a threadstatic voidthreadJoin(Thread thread, long millis) join a threadstatic voidused to indicate if we're in code that would be retried if there's a failurestatic voidused to indicate if we're in code that would be retried if there's a failure call within a finally block to removestatic TimestamptimestampIsoUtcMicrosConvertFromString(String utcStringWithMicros) 2023-06-29T18:27:01.227972Zstatic StringtimestampIsoUtcMicrosConvertToString(Timestamp timestamp) 2024-06-24T08:00:53.123456Zstatic Timestampallow: 2023-06-29T18:27:01Z allow: 2023-06-29T18:27:01.227972Zstatic StringtimestampIsoUtcSecondsConvertToString(Timestamp timestamp) static TimestamptimestampObjectValue(Object input, boolean allowNullBlank) get the Timestamp value of an objectstatic StringtimestampToFileString(Date timestamp) Convert a timestamp into a string: yyyy_MM_dd__HH_mm_ss_SSSstatic StringtimestampToString(Date timestamp) Convert a timestamp into a string: yyyy/MM/dd HH:mm:ss.SSSstatic StringtmpDir()return the temp dir, either what is in the java env var, or something in the grouper confstatic StringtmpDir(boolean appendSlashIfNotThere) return the temp dir, either what is in the java env var, or something in the grouper confstatic ObjectConvert a list to an array with the type of the first element e.g. if it is a list of Person objects, then the array is Person[]static <T> T[]toArray(Collection collection, Class<T> theClass) convert a list into an array of type of theClassstatic Object[]toArrayObject(Object... objects) return an array of objects from varargs for JEXLstatic <T> List<T>toList(T... objects) return a list of objects from varargs.toListClasses(Class<?>... classes) convert classes to a listtoListObject(Object... objects) return a list of objects from varargs.static StringtoLowerCase(String input) null safe to lower methodturn some strings into a mapstatic <T> Set<T>toSet(T... objects) return a set of objects from varargs.static <T> Set<T>toSetObject(T object) return a set of stringtoSetObjectType(T... objects) return a set of objects from varargs.static StringtoString(InputStream input, String encoding) Get the contents of anInputStreamas a String.static StringtoString(Collection<Source> sources) convert a collection of sources to a stringstatic StringtoStringFields(Object object, Set<String> fieldNames) print out an object by fieldsstatic StringtoStringForLog(Object object) print out various types of objectsstatic StringtoStringForLog(Object object, boolean newLines) print out various types of objectsstatic StringtoStringForLog(Object object, int maxChars) print out various types of objectsstatic StringtoStringForLogHtml(Object object) print out various types of objectstoStringObjectMap(Object... stringObjects) turn some strings into a mapstatic StringtoStringSafe(Object object) fail safe toString for Exception blocks, and include the stack if there is a problem with toString()static TimestamptoTimestamp(Object input) Convert a string or object to a timestamp (could be string, date, timestamp, etc) yyyymmdd or yyyy/MM/dd or yyyy-MM-dd or yyyy/MM/dd HH:mm:ss or yyyy/MM/dd HH:mm:ss.SSS or yyyy/MM/dd HH:mm:ss.SSSSSSstatic StringtoUpperCase(String input) null safe to upper methodstatic Stringtrim whitespace from stringstatic StringtrimToEmpty(String str) trim to empty, convert null to emptystatic StringtruncateAscii(String input, int requiredLength) find the length of ascii chars (non ascii are counted as three)static voidtryMultipleTimes(int times, Runnable runnable) static <T> TIf necessary, convert an object to another type.static <T> TtypeCast(Object value, Class<T> theClass, boolean convertNullToDefaultPrimitive, boolean useNewInstanceHooks) If necessary, convert an object to another type.typeCastStringStringMap(Map<String, Object> limitEnvVars) process a string / string map and convert the values to a string/object map.static ClassunenhanceClass(Class theClass) if a class is enhanced, get the unenhanced versionstatic StringuniqueId()get a unique string identifier based on the current time, this is not globally unique, just unique for as long as this server is running...static intunpackInt(long theLong, boolean isFirst) take a longstatic booleanvalidEmail(String email) static voidwait for inputstatic intwhitespaceCountNewLines(String input) normalize newlines then count newlinesstatic Stringnormalize new lines to unixstatic StringwhitespaceRemove(String input) remove whitespace from stringstatic voidwriteStringToFile(File file, String data, String encoding) Writes data to a file.static voidxmlAttribute(Writer writer, String attributeName, String attributeValue) static StringConvert an XML string to HTML to display on the screenstatic StringConvert an XML string to HTML to display on the screenstatic byte[]zipGzipCompress(String str) static StringzipGzipDecompress(byte[] compressed) static booleanzipGzipIsCompressed(byte[] compressed) static StringzipUnBase64UnGzip(String zippedBase64Exception) if a string has zips and base 64s (e.g. for stack), then remove
-
Field Details
-
objectMapper
public static final com.fasterxml.jackson.databind.ObjectMapper objectMapperObject mapper to serialize and deserialize json string and beans -
LOG_ERROR
- See Also:
-
ONE_KB
public static final long ONE_KBThe number of bytes in a kilobyte.- See Also:
-
ONE_MB
public static final long ONE_MBThe number of bytes in a megabyte.- See Also:
-
ONE_GB
public static final long ONE_GBThe number of bytes in a gigabyte.- See Also:
-
PROMPT_KEY_SCHEMA_EXPORT_ALL_TABLES
prompt key for schema export -
PROMPT_KEY_RESET_DATA
prompt key for reset data -
stopPromptingUser
public static boolean stopPromptingUserdont prompt while testing etc, but make sure there has been at least one prompt -
timestampIsoUtcMicrosWithoutZtoString
-
timestampIsoUtcSeconds
-
timestampIsoHoursMinutesTZ
-
timestampHoursMinutesLocalDateTime
-
timestampHoursMinutesSecondsLocalDateTime
-
timestampHoursMinutes
-
timestampHoursMinutesAMPM
-
DATE_FORMAT
string format of dates- See Also:
-
TIMESTAMP_FILE_FORMAT
string format of dates for file names- See Also:
-
DATE_FORMAT2
string format of dates- See Also:
-
DATE_FORMAT3
- See Also:
-
DATE_MINUTES_SECONDS_FORMAT
format including minutes and seconds: yyyy/MM/dd HH:mm:ss- See Also:
-
DATE_MINUTES_SECONDS_NO_SLASH_FORMAT
format including minutes and seconds: yyyyMMdd HH:mm:ss- See Also:
-
TIMESTAMP_FORMAT
format on screen of config for milestone: yyyy/MM/dd HH:mm:ss.SSS- See Also:
-
TIMESTAMP_NO_SLASH_FORMAT
format on screen of config for milestone: yyyyMMdd HH:mm:ss.SSS- See Also:
-
NOT_FOUND
public static final int NOT_FOUNDspecial number when a number is not found- See Also:
-
DEFAULT_BUFFER_SIZE
public static final int DEFAULT_BUFFER_SIZEThe name says it all.- See Also:
-
EMPTY_STRING_ARRAY
An empty immutableStringarray. -
EMPTY_OBJECT_ARRAY
An empty immutableObjectarray. -
EMPTY
The empty String"".- Since:
- 2.0
- See Also:
-
INDEX_NOT_FOUND
public static final int INDEX_NOT_FOUNDRepresents a failed index search.- Since:
- 2.1
- See Also:
-
stringFieldNames
map of class to the list of fields which are string type -
JAVA_IO_TMPDIR
-
HTML_REPLACE
array for converting HTML to string -
HTML_REPLACE_NO_SINGLE
array for converting HTML to string -
HTML_SEARCH_NO_SINGLE
array for converting HTML to string
-
-
Constructor Details
-
GrouperUtil
public GrouperUtil()
-
-
Method Details
-
main
- Throws:
Exception
-
jsonJacksonListObjectArrayFromJsonPointers
public static List<Object[]> jsonJacksonListObjectArrayFromJsonPointers(com.fasterxml.jackson.databind.JsonNode rootJsonNode, String jsonPointerOfArrayNode, List<String> jsonPointersOfSubFields) start the sub field with JSON_NODE_ROOT if you want the pointer from root node instead of array node- Parameters:
rootJsonNode-jsonPointerOfArrayNode- json path that returns a list e.g. /a/bjsonPointersOfSubFields- from the perspective of the array node, e.g. /c/d- Returns:
- the list of object arrays not null
-
substituteExpressionPrintNode
public static void substituteExpressionPrintNode(org.apache.commons.jexl2.parser.JexlNode jexlNode, String prefix) -
generateRsaKeypair
generate RSA key public private pair.- Parameters:
keySize- e.g 2048- Returns:
-
gshRunScript
run a GSH script- Parameters:
script-lightWeight- will use an abbreviated groovysh.profile for faster speed. built in commands arent there and imports largely arent there- Returns:
- the output
-
gshRunScript
run a GSH script- Parameters:
script-lightWeight- will use an abbreviated groovysh.profile for faster speed. built in commands arent there and imports largely arent thereinputMap- puts variables in a context to be retrieved with GrouperUtil.gshRetrieveInputValueObject(), GrouperUtil.gshRetrieveInputValueString(), GrouperUtil.gshRetrieveInputValueInteger(), GrouperUtil.gshRetrieveInputValueBoolean()- Returns:
- the full output
-
gshRunScriptReturnResult
public static GrouperGroovysh.GrouperGroovyResult gshRunScriptReturnResult(String script, boolean lightWeight) run a GSH script- Parameters:
script-lightWeight- will use an abbreviated groovysh.profile for faster speed. built in commands arent there and imports largely arent thereinputMap- puts variables in a context to be retrieved with GrouperUtil.gshRetrieveInputValueObject(), GrouperUtil.gshRetrieveInputValueString(), GrouperUtil.gshRetrieveInputValueInteger(), GrouperUtil.gshRetrieveInputValueBoolean()- Returns:
- the full output
-
setClear
-
exceptionFinallyInjectOrThrow
public static void exceptionFinallyInjectOrThrow(Exception tryException, Exception finallyException) in a finally block, take an exception and inject and throw the existing exception, or just throw the finally exception- Parameters:
tryException-finallyException-
-
j2eeRetrieveSourceIpAddress
get the source IP address or null if cant- Returns:
- IP address
-
normalize
Deprecated.use this instead org.apache.commons.lang3.StringUtils.stripAccents((String)currentValue);take out accented chars with grouperUtil.normalize("NFD", groupAttribute).replaceAll("\\p{M}", "")- Parameters:
form-text-- Returns:
- the normalized string
-
isInRetriableCode
public static boolean isInRetriableCode()- Returns:
- true if we're in code that would be retried if there's a failure
-
threadLocalInRetriableCodeAssign
public static void threadLocalInRetriableCodeAssign()used to indicate if we're in code that would be retried if there's a failure -
threadLocalInRetriableCodeClear
public static void threadLocalInRetriableCodeClear()used to indicate if we're in code that would be retried if there's a failure call within a finally block to remove -
splitTrimEmailAddresses
take email addresses from a textarea and turn them into semi separated- Parameters:
emailAddresses-- Returns:
- string of email addresses
-
normalizeEmailAddresses
take email addresses from a textarea and turn them into semi separated- Parameters:
emailAddresses- can be whitespace, comma, or semi separated- Returns:
- the email addresses semi separated
-
validEmail
- Parameters:
email-- Returns:
- true if valid, false if not
-
subjectHasAttribute
see if a subject has an attribute- Parameters:
subject-attributeName-- Returns:
- true if the subject has an attribute
-
matchSqlString
match sqlLike string see if a sql like string matches a real string. e.g. if the input is a:b:%, and the input is: a:b:test:that, then it returns true- Parameters:
sqlMatcher-testText-- Returns:
- true if matches, false if not
-
setShorten
shorten a set if it is too long- Type Parameters:
T-- Parameters:
theSet-maxSize-- Returns:
- the new set
-
formatNumberWithCommas
- Parameters:
number- e.g. 12345678- Returns:
- the string, e.g. 12,345,678
-
compare
compare null safe- Parameters:
first-second-- Returns:
- 0 for equal, 1 for greater, -1 for less
-
convertSources
e.g. ('g:gsa', 'jdbc')- Parameters:
sources- is comma separated source id's- Returns:
- the set of sources
-
convertSources
e.g. ['g:gsa', 'jdbc']- Parameters:
sourceIds- is an array of source ids- Returns:
- the set of sources
-
escapeSingleQuotes
escape single quotes in javascript- Parameters:
string-- Returns:
- the escaped string
-
escapeDoubleQuotes
escape double quotes in javascript- Parameters:
string-- Returns:
- the escaped string
-
escapeDoubleQuotesForString
escape double quotes in javascript- Parameters:
string-- Returns:
- the escaped string
-
escapeDoubleQuotesSlashesAndNewlinesForString
escape double quotes in javascript- Parameters:
string-- Returns:
- the escaped string
-
escapeNewlinesForString
escape double quotes in javascript- Parameters:
string-- Returns:
- the escaped string
-
escapeSlashesForString
escape slashes- Parameters:
string-- Returns:
- the escaped string
-
convertSourcesToSqlInString
Deprecated.moved to @See HibUtilse.g. ('g:gsa', 'jdbc')- Parameters:
sources-- Returns:
- the in string, of sources sorted alphabetically
-
toMap
turn some strings into a map- Parameters:
strings-- Returns:
- the map (never null)
-
toStringObjectMap
turn some strings into a map- Parameters:
stringObjects- is an array of String,Object,String,Object etc where the Strings are the key, and the Object is the value- Returns:
- the map (never null)
-
convertMillisToFriendlyString
convert millis to friendly string- Parameters:
duration-- Returns:
- the friendly string
-
convertMillisToFriendlyString
convert millis to friendly string- Parameters:
duration-- Returns:
- the friendly string
-
deleteFile
Delete a file, throw exception if cannot- Parameters:
file-
-
argAfter
return the arg after the argBefore, or null if not there, or exception if argBefore is not found- Parameters:
args-argBefore-- Returns:
- the arg
-
append
public static void append(StringBuilder result, String separatorIfResultNotEmpty, String stringToAppend) append and maybe put a separator in there- Parameters:
result-separatorIfResultNotEmpty-stringToAppend-
-
byteCountToDisplaySize
Returns a human-readable version of the file size (original is in bytes).- Parameters:
size- The number of bytes.- Returns:
- A human-readable display value (includes units).
-
getLog
get a logger, and auto-create log dirs if havent done yet- Parameters:
theClass-- Returns:
- the logger
-
fileCopy
-
fileCopyExampleResourceIfNotExist
- Parameters:
exampleResource-resource-
-
logDirsCreateIfNotDone
public static void logDirsCreateIfNotDone()auto-create log dirs if not done yet -
logErrorNextException
public static void logErrorNextException(org.apache.commons.logging.Log log, Throwable throwable, int timeToLive) find a next exception in the stack and log it- Parameters:
log- loggerthrowable- exception to look for next exceptions intimeToLive- so we dont loop forever
-
hasOption
public static boolean hasOption(int options, int option) see if options have a specific option by int bits- Parameters:
options-option-- Returns:
- if the option is there
-
isPrintGrouperLogsToConsole
public static boolean isPrintGrouperLogsToConsole()if the grouper logs go to the console or not- Returns:
- if
-
fileCanonicalPath
get canonical path of file- Parameters:
file-- Returns:
- the path
-
logDirPrint
print the log dir to the console so the logs are easy to find- Returns:
- the log dir message
-
suffixAfterChar
return the suffix after a char. If the char doesnt exist, just return the string- Parameters:
input- stringtheChar- char- Returns:
- new string
-
oracleStandardNameFromJava
get the oracle underscore name e.g. javaNameHere -> JAVA_NAME_HERE- Parameters:
javaName- the java convention name- Returns:
- the oracle underscore name based on the java name
-
mapEquals
see if two maps are the equivalent (based on number of entries, and the equals() method of the keys and values)- Type Parameters:
K-V-- Parameters:
first-second-- Returns:
- true if equal
-
mapDifferences
public static <K,V> void mapDifferences(Map<K, V> first, Map<K, V> second, Set<K> differences, String prefix) see if two maps are the equivalent (based on number of entries, and the equals() method of the keys and values)- Type Parameters:
K-V-- Parameters:
first- map to check diffssecond- map to check diffsdifferences- set of keys (with prefix) of the diffsprefix- for the entries in the diffs (e.g. "attribute__"
-
sleep
public static void sleep(long millis) sleep, if interrupted, throw runtime- Parameters:
millis-
-
sleepWithStdoutCountdown
public static void sleepWithStdoutCountdown(int seconds) - Parameters:
seconds-
-
encryptSha
encrypt a message to SHA- Parameters:
plaintext-- Returns:
- the hash
-
encryptShaHex
encrypt a message to SHA- Parameters:
plaintext-- Returns:
- the hash
-
injectInException
If we can, inject this into the exception, else return false- Parameters:
t-message-- Returns:
- true if success, false if not
-
findGrouperPropertiesDbMatch
see if there is a grouper properties db match- Parameters:
whitelist- true if whitelist, false if blacklistuser- is the db userurl- is the db url- Returns:
- true if found match, false if not
-
promptUserAboutDbChanges
prompt the user about db changes- Parameters:
reason- e.g. delete all tablescheckResponse- true if the response from the user should be checked, or just display the prompt
-
ldapConvertDnToSubPath
convert from uid=someapp,ou=people,dc=myschool,dc=edu baseDn is edu searchDn is myschool to people:someapp i.e. take apart a bushy dns- Parameters:
dn-baseDn- if there is one, take it offsearchDn- if there is one after the baseDn is off, take it off- Returns:
- the subpath
-
ldapConvertDnToSpecificValue
convert from uid=someapp,ou=people,dc=myschool,dc=edu to someapp- Parameters:
dn-- Returns:
-
ldapEscapeRdn
This takes a string of attribute=value and makes sure that special, dn-relevant characters are escaped, particularly commas, pluses, etc- Parameters:
rdnString- An RDN: attribute=value- Returns:
-
ldapEscapeRdnValue
This takes a string of value and makes sure that special, dn-relevant characters are escaped, particularly commas, pluses, etc- Parameters:
rdnValue- An RDN value: value- Returns:
- the escaped value
-
ldapAdDateCurrent
public static long ldapAdDateCurrent()active directory date from millis 1970 date- Returns:
- the AD date
-
ldapAdDateFromMillis1970
public static long ldapAdDateFromMillis1970(long millisSince1970) active directory date from millis 1970 date- Parameters:
millisSince1970-- Returns:
- the AD date
-
ldapBushyDn
public static String ldapBushyDn(String groupName, String rdnAttributeName, String ouAttributeName, boolean performRdnEscaping, boolean performFilterEscaping) - Parameters:
groupName-rdnAttributeName-ouAttributeName-performRdnEscaping-performFilterEscaping-- Returns:
-
ldapBushyDn
public static String ldapBushyDn(String groupName, String rdnAttributeName, String rdnAttributeValue, String ouAttributeName, boolean performRdnEscaping, boolean performFilterEscaping) - Parameters:
groupName-rdnAttributeName-rdnAttributeValue-ouAttributeName-performRdnEscaping-performFilterEscaping-- Returns:
-
ldapFilterEscape
-
convertDnToSpecificValue
Deprecated.use GrouperUtil.ldapConvertDnToSpecificValue(String)- See Also:
-
convertDnToSpecificValueOrGroup
@Deprecated public static String convertDnToSpecificValueOrGroup(String dn, String groupPrefix, String groupSuffix, boolean createGroupIfNotThere, boolean idOrIdentifier) Deprecated.use GrouperUtil.ldapConvertDnToSpecificValueOrGroup(String, String, String, boolean, boolean) -
ldapConvertDnToSpecificValueOrGroup
public static String ldapConvertDnToSpecificValueOrGroup(String dn, String groupPrefix, String groupSuffix, boolean createGroupIfNotThere, boolean idOrIdentifier) convert from uid=someapp,ou=people,dc=myschool,dc=edu to someapp and allow groups- Parameters:
dn- full dngroupSuffix- group suffix e.g. ,OU=Groups,DC=dev,DC=umontreal,DC=cagroupPrefix- group prefix e.g. umontreal:adgroups: if null then no prefixcreateGroupIfNotThere- if we should see if group exists and if not, createidOrIdentifier- true for Id (uuid), false for Identifier of group (name)- Returns:
- the subjectId or Identifier
-
convertDnToSubPath
Deprecated.use GrouperUtil.ldapConvertDnToSubPath(String, String, String) -
convertAdMemberDnToSpecificValue
@Deprecated public static String convertAdMemberDnToSpecificValue(String ldapConfigId, String dn, String baseDn, String grouperBaseStem, boolean idOrIdentifier) Deprecated.use ldapConvertAdMemberDnToSpecificValue -
ldapConvertAdMemberDnToSpecificValue
public static String ldapConvertAdMemberDnToSpecificValue(String ldapConfigId, String dn, String baseDn, String grouperBaseStem, boolean idOrIdentifier) convert a user dn to a user CN, and a group dn to a group ID or Uuid- Parameters:
baseDn- e.g. OU=People,DC=devsim,DC=umontreal,DC=cadn- of group membergrouperBaseStem- is the base stem where the groups go. e.g. my:groups:idOrIdentifier- true for id (group id), false for identifier (group name)- Returns:
- CN for person, Uuid or Group name for a group
-
convertDnToGroupName
@Deprecated public static String convertDnToGroupName(String dn, String baseDn, String grouperBaseStem) Deprecated.use ldapConvertDnToGroupName -
ldapConvertDnToGroupName
convert a DN to a group name- Parameters:
dn-baseDn- e.g. OU=People,DC=devsim,DC=umontreal,DC=cagrouperBaseStem- is the base stem where the groups go. e.g. my:groups:- Returns:
- the subject identifier (group name)
-
convertLDAPMemberDnToSubjectIdOrGroup
@Deprecated public static String convertLDAPMemberDnToSubjectIdOrGroup(String dn, String baseOu, String grouperBaseStem, String serverId, String uniqueAttribute, boolean idOrIdentifier) Deprecated.use ldapConvertLDAPMemberDnToSubjectIdOrGroup -
ldapConvertLDAPMemberDnToSubjectIdOrGroup
public static String ldapConvertLDAPMemberDnToSubjectIdOrGroup(String dn, String baseOu, String grouperBaseStem, String serverId, String uniqueAttribute, boolean idOrIdentifier) convert a subject dn to a user RDN value, and a group dn to a group ID or Uuid- Parameters:
dn- of group member . Normally this will be as subjectIdbaseOu- This is the full DN of the OU to load from LDAP e.g. OU=Some Example,DC=test,DC=school,DC=edugrouperBaseStem- is the base stem where the groups are loaded into. e.g. my:groups:Loaded_from_LDAPserverId- is the connection or server ID specified in grouper-loader.properties file. e.g: personLdapuniqueAttribute- attribute value to return from LDAP query, preferably the one storing the subjectIdidOrIdentifier- true for id (group id), false for identifier (group name)- Returns:
- RDN value for subject (user object), Uuid or Group name for a group
-
promptUserAboutChanges
public static void promptUserAboutChanges(String reason, boolean checkResponse, String dbType, String url, String user) prompt the user about db changes- Parameters:
reason- e.g. delete all tablescheckResponse- true if the response from the user should be checked, or just display the promptdbType- should be db or ldapurl- to check foruser- user for db
-
uniqueId
get a unique string identifier based on the current time, this is not globally unique, just unique for as long as this server is running...- Returns:
- String
-
fileFromResourceName
get a file name from a resource name- Parameters:
resourceName- is the classpath location- Returns:
- the file path on the system
-
getLocationFromResourceName
get a full path from a resource name- Parameters:
resourceName- is the classpath location- Returns:
- Full path to the resource. For files, the file path on the system; otherwise, the resource URL
-
computeUrl
compute a url of a resource- Parameters:
resourceName-canBeNull- if cant be null, throw runtime- Returns:
- the URL
-
classLoader
fast class loader- Returns:
- the class loader
-
nonNull
make sure a array is non null. If null, then return an empty array.- Type Parameters:
T-- Parameters:
array-theClass- to make array from- Returns:
- the list or empty list if null
-
stripSuffix
strip the suffix off- Parameters:
string-suffix-- Returns:
- the string without the suffix
-
stripPrefix
strip the prefix off- Parameters:
string-prefix-- Returns:
- the string without the suffix
-
prefixOrSuffix
get the prefix or suffix of a string based on a separator- Parameters:
startString- is the string to start withseparator- is the separator to split onisPrefix- if thre prefix or suffix should be returned- Returns:
- the prefix or suffix, if the separator isnt there, return the original string
-
indent
this method will indent xml or json. this is for logging or documentations purposes only and should not be used for a production use (since it is not 100% tested or compliant with all constructs like xml CDATA For xml, assumes elements either have text or sub elements, not both. No cdata, nothing fancy. If the input is <a><b><c>hey</c><d><e>there</e></d></b></a> It would output: <a> <b> <c>hey</c> <d> <e>there</e> </d> </b> </a> For , if the input is: {"a":{"b\"b":{"c\\":"d"},"e":"f","g":["h":"i"]}} It would output: { "a":{ "b\"b":{ "c\\":"d" }, "e":"f", "g":[ "h":"i" ] } }- Parameters:
string-failIfTypeNotFound-- Returns:
- the indented string, 2 spaces per line
-
jsonConvertTo
convert an object to json.- Parameters:
object-- Returns:
- the string of json
-
jsonConvertTo
convert an object to json.- Parameters:
object-- Returns:
- the string of json
-
jsonJacksonFieldNames
get field names from json node, assume field names are unique- Parameters:
jsonNode-- Returns:
-
jsonJacksonGetString
public static String jsonJacksonGetString(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as string and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonAssignJsonPointerString
public static void jsonJacksonAssignJsonPointerString(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Object value) assign a jackson field- Parameters:
objectNode-jsonPointer- e.g. /a/b/c/dvalue-
-
jsonJacksonAssignString
public static void jsonJacksonAssignString(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, String value) assign a jackson field- Parameters:
jsonNode-fieldName-
-
jsonJacksonAssignBoolean
public static void jsonJacksonAssignBoolean(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Boolean value) assign a jackson field- Parameters:
jsonNode-fieldName-
-
jsonJacksonAssignLong
public static void jsonJacksonAssignLong(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Long value) assign a jackson field- Parameters:
jsonNode-fieldName-
-
jsonJacksonAssignStringArray
public static void jsonJacksonAssignStringArray(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Collection<String> values) assign a jackson field- Parameters:
jsonNode-fieldName-
-
jsonJacksonAssignObjectNodeArray
public static void jsonJacksonAssignObjectNodeArray(com.fasterxml.jackson.databind.node.ObjectNode objectNode, String fieldName, Collection<com.fasterxml.jackson.databind.node.ObjectNode> values) assign a jackson array- Parameters:
objectNode-fieldName-values-
-
jsonJacksonGetString
public static String jsonJacksonGetString(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, String defaultString) get a field as string and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonGetString
public static String jsonJacksonGetString(com.fasterxml.jackson.databind.node.ArrayNode arrayNode, int index) get a field as string and handle null- Parameters:
arrayNode-index-- Returns:
- the string
-
jsonJacksonGetArrayNode
public static com.fasterxml.jackson.databind.node.ArrayNode jsonJacksonGetArrayNode(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as node or array. could return null if not there- Parameters:
jsonNode-fieldName-- Returns:
- the node or array
-
jsonJacksonGetNode
public static com.fasterxml.jackson.databind.JsonNode jsonJacksonGetNode(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as node or array. could return null if not there- Parameters:
jsonNode-fieldName-- Returns:
- the node or array
-
jsonJacksonGetStringSet
public static Set<String> jsonJacksonGetStringSet(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as string set. could return null if not there- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonGetBoolean
public static Boolean jsonJacksonGetBoolean(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as boolean and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonGetBoolean
public static Boolean jsonJacksonGetBoolean(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, Boolean defaultBoolean) get a field as boolean and handle null- Parameters:
jsonNode-fieldName-defaultBoolean- if null use this value- Returns:
- the string
-
jsonJacksonGetBooleanFromJsonPointer
public static Boolean jsonJacksonGetBooleanFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Boolean defaultBoolean) get a field as boolean and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/bdefaultBoolean- if null use this value- Returns:
- the string
-
jsonJacksonGetLong
public static Long jsonJacksonGetLong(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as long and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonGetLong
public static Long jsonJacksonGetLong(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, Long defaultLong) get a field as long and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonGetInteger
public static Integer jsonJacksonGetInteger(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName) get a field as integer and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonGetInteger
public static Integer jsonJacksonGetInteger(com.fasterxml.jackson.databind.JsonNode jsonNode, String fieldName, Integer defaultInteger) get a field as integer and handle null- Parameters:
jsonNode-fieldName-- Returns:
- the string
-
jsonJacksonNode
public static com.fasterxml.jackson.databind.node.ObjectNode jsonJacksonNode() -
jsonJacksonArrayNode
public static com.fasterxml.jackson.databind.node.ArrayNode jsonJacksonArrayNode() -
jsonJacksonNode
-
jsonJacksonToString
convert a json node to actual json- Parameters:
jsonNode-- Returns:
-
jsonConvertToNoWrap
convert an object to json without wrapping it with the simple class name.- Parameters:
object-- Returns:
- the string of json
-
jsonConvertTo
convert an object to json. note this wraps the gson with the object simple name so it can be revived- Parameters:
object-writer-
-
jsonConvertFrom
convert an object from json. note this works well if there are no collections, just real types, arrays, etc.- Parameters:
conversionMap- is the class simple name to class of objects which are allowed to be brought back. Note: only the top level object needs to be registeredjson-- Returns:
- the object
-
jsonConvertFromMap
convert an object from Map.- Parameters:
jsonMap- is the json maptheClass- is the class that the object should be coverted into. Note: only the top level object needs to be registered- Returns:
- the object
-
jsonConvertFrom
convert an object from json. note this works well if there are no collections, just real types, arrays, etc.- Parameters:
json- is the json string, not wrapped with a simple class nametheClass- is the class that the object should be coverted into. Note: only the top level object needs to be registered- Returns:
- the object
-
jsonConvertFrom
public static <T> T jsonConvertFrom(com.fasterxml.jackson.databind.JsonNode jsonNode, Class<T> theClass) convert a jsonNode into POJO.- Parameters:
jsonNode-theClass- is the class that the object should be coverted into. Note: only the top level object needs to be registered- Returns:
- the object
-
jsonConvertFromObjectToObjectNode
public static com.fasterxml.jackson.databind.node.ObjectNode jsonConvertFromObjectToObjectNode(Object object) convert a POJO into ObjectNode- Parameters:
object- Note: only the top level object needs to be registered- Returns:
- ObjectNode
-
extensionFromName
get the extension from name. if name is a:b:c, name is c- Parameters:
name-- Returns:
- the name
-
nameInFolderDirect
see if a name is in a folder (not subfolder). if name is a:b:c, and folder is a:b, then yes if a:b:c and a:c, then no if a:b:c and a, then no
- Parameters:
name-folder-- Returns:
- the name
-
forName
Returns the class object.
- Parameters:
origClassName- is fully qualified- Returns:
- the class
-
newInstance
Construct a class- Type Parameters:
T- template type- Parameters:
theClass-- Returns:
- the instance
-
parentStemNameFromName
Deprecated.dont use this! call the overload and specify if you want root stem or notget the parent stem name from name. if already a root stem then just return null. e.g. if the name is a:b:c then the return value is a:b- Parameters:
name-- Returns:
- the parent stem name or null if none
-
parentStemNameFromName
get the parent stem name from name. if already a root stem then just return null. e.g. if the name is a:b:c then the return value is a:b- Parameters:
name-nullForRoot- null for root, otherwise colon- Returns:
- the parent stem name or null if none
-
defaultIfBlank
return the string or the other if the first is blank- Parameters:
string-defaultStringIfBlank-- Returns:
- the string or the default one
-
defaultIfNull
public static <T> T defaultIfNull(T theValue, T defaultIfTheValueIsNull) genericized method to see if first is null, if so then return second, else first.- Type Parameters:
T-- Parameters:
theValue- first inputdefaultIfTheValueIsNull- second input- Returns:
- the first if not null, second if no
-
addIfNotThere
add each element of listToAdd if it is not already in list- Type Parameters:
T-- Parameters:
list- to add tolistToAdd- each element will be added to list, or null if none
-
toStringFields
print out an object by fields- Parameters:
object-fieldNames-- Returns:
- the string representation or null if null
-
collectionContains
- Parameters:
collection-object-- Returns:
- true if the collection contains this object
-
collectionToString
convert a set to a string (comma separate)- Parameters:
collection-- Returns:
- the String
-
setToString
convert a set to a string (comma separate)- Parameters:
set-- Returns:
- the String
-
MapToString
Deprecated.use mapToString(map)convert a set to a string (comma separate)- Parameters:
map-- Returns:
- the String
-
mapToString
convert a set to a string (comma separate)- Parameters:
map-- Returns:
- the String
-
toStringForLog
print out various types of objects- Parameters:
object-- Returns:
- the string value
-
toStringForLogHtml
print out various types of objects- Parameters:
object-- Returns:
- the string value
-
toStringForLog
print out various types of objects- Parameters:
object-- Returns:
- the string value
-
toStringForLog
print out various types of objects- Parameters:
object-maxChars- is the max chars that should be returned (abbreviate if longer), or -1 for any amount- Returns:
- the string value
-
batchNumberOfBatches
public static int batchNumberOfBatches(int count, int batchSize, boolean haveAtLeastOne) If batching this is the number of batches- Parameters:
count- is size of setbatchSize-haveAtLeastOne- is true if there should be at least one run even if the collection is empty (e.g. for queries based on other things)- Returns:
- the number of batches
-
batchNumberOfBatches
Deprecated.use batchNumberOfBatches(Collection<?> collection, int batchSize, boolean haveAtLeastOne)If batching this is the number of batches. Will return at least 1- Parameters:
count- is size of setbatchSize-- Returns:
- the number of batches
-
batchNumberOfBatches
Deprecated.use batchNumberOfBatches(Collection<?> collection, int batchSize, boolean haveAtLeastOne)If batching this is the number of batches, will return at least 1- Parameters:
collection-batchSize-- Returns:
- the number of batches
-
batchNumberOfBatches
public static int batchNumberOfBatches(Collection<?> collection, int batchSize, boolean haveAtLeastOne) If batching this is the number of batches, will return at least 1- Parameters:
collection-batchSize-haveAtLeastOne- is true if there should be at least one run even if the collection is empty (e.g. for queries based on other things)- Returns:
- the number of batches
-
findParentStemNames
if the groups are: a:b:c:d and a:d:r, then return the strings: :, a, a:b, a:b:c, a:d- Parameters:
groups-- Returns:
- the set of stem names
-
findParentStemNames
if the groups are: a:b:c:d, then return the strings: :, a, a:b, a:b:c- Parameters:
objectName-- Returns:
- the set of stem names
-
batchList
retrieve a batch by 0 index. Will return an array of size batchSize or the remainder. the array will be full of elements. Note, this requires an ordered input (so use linkedhashset not hashset if doing sets)- Type Parameters:
T- template type- Parameters:
collection-batchSize-batchIndex-- Returns:
- the list This never returns null, only empty list
-
splitTrim
split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)- Parameters:
input- is the delimited input to split and trimseparator- is what to split on- Returns:
- the array of items after split and trimmed, or null if input is null. will be trimmed to empty
-
splitTrimToList
split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)- Parameters:
input- is the delimited input to split and trimseparator- is what to split on- Returns:
- the list of items after split and trimmed, or null if input is null. will be trimmed to empty
-
splitTrimToSet
split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)- Parameters:
input- is the delimited input to split and trimseparator- is what to split on- Returns:
- the set of items after split and trimmed, or null if input is null. will be trimmed to empty
-
splitTrim
public static String[] splitTrim(String input, String separator, boolean treatAdjacentSeparatorsAsOne) split a string based on a separator into an array, and trim each entry (see the Commons Util trim() for more details)- Parameters:
input- is the delimited input to split and trimseparator- is what to split ontreatAdjacentSeparatorsAsOne-- Returns:
- the array of items after split and trimmed, or null if input is null. will be trimmed to empty
-
escapeUrlEncode
escape url chars (e.g. a # is %23)- Parameters:
string- input- Returns:
- the encoded string
-
escapeUrlDecode
unescape url chars (e.g. a space is %20)- Parameters:
string- input- Returns:
- the encoded string
-
nonNull
make sure a list is non null. If null, then return an empty list- Type Parameters:
T-- Parameters:
list-- Returns:
- the list or empty list if null
-
nonNull
make sure a collection is non null. If null, then return an empty list- Type Parameters:
T-- Parameters:
list-- Returns:
- the list or empty list if null
-
nonNull
make sure a list is non null. If null, then return an empty set- Type Parameters:
T-- Parameters:
set-- Returns:
- the set or empty set if null
-
nonNull
make sure it is non null, if null, then give new map- Type Parameters:
K- key of mapV- value of map- Parameters:
map- is map- Returns:
- set non null
-
toList
return a list of objects from varargs. Though if there is one object, and it is a list, return it.- Type Parameters:
T- template type of the objects- Parameters:
objects-- Returns:
- the list or null if objects is null
-
toArrayObject
return an array of objects from varargs for JEXL- Parameters:
objects-- Returns:
- the array or null if objects is null
-
toListObject
return a list of objects from varargs. Though if there is one object, and it is a list, return it. template type of the objects- Parameters:
objects-- Returns:
- the list or null if objects is null
-
toListClasses
convert classes to a list- Parameters:
classes-- Returns:
- list of classes
-
toSet
return a set of objects from varargs.- Type Parameters:
T- template type of the objects- Parameters:
objects-- Returns:
- the set
-
toSetObjectType
return a set of objects from varargs.- Type Parameters:
T- template type of the objects- Parameters:
objects-- Returns:
- the set
-
toSetObject
return a set of string- Type Parameters:
T- template type of the objects- Parameters:
object-- Returns:
- the set
-
getFriendlyTimezoneStringForInputDescription
Return a string that combines the standard and daylight timezones of the server into one string separated by a slash that can be used in an input description to inform the user of the server timezone. For the main US timezones, the following is returned instead: ET, CT, MT, PT.- Returns:
- string
-
timestampIsoUtcSecondsConvertToString
- Parameters:
timestamp-- Returns:
- timestamp string
-
timestampIsoUtcMicrosConvertToString
2024-06-24T08:00:53.123456Z- Parameters:
timestamp-- Returns:
- timestamp string
-
timestampIsoUtcMicrosConvertFromString
2023-06-29T18:27:01.227972Z- Parameters:
utcStringWithMicros-- Returns:
- timestamp which is only specific to millis
-
timestampIsoUtcSecondsConvertFromString
allow: 2023-06-29T18:27:01Z allow: 2023-06-29T18:27:01.227972Z- Parameters:
timestamp-- Returns:
- timestamp string
-
assertion
If false, throw an assertException, and give a reason- Parameters:
isTrue-reason-
-
assignField
public static void assignField(Class theClass, Object invokeOn, String fieldName, Object dataToAssign, boolean callOnSupers, boolean overrideSecurity, boolean typeCast, Class<? extends Annotation> annotationWithValueOverride) assign data to a field- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticfieldName- method name to calldataToAssign- datacallOnSupers- if static and method not exists, try on supersoverrideSecurity- true to call on protected or private etc methodstypeCast- true if we should typecastannotationWithValueOverride- annotation with value of override
-
assignField
public static void assignField(Class theClass, Object invokeOn, String fieldName, Object dataToAssign, Class<? extends Annotation> annotationWithValueOverride) assign data to a field. Will find the field in superclasses, will typecast, and will override security (private, protected, etc)- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticfieldName- method name to calldataToAssign- dataannotationWithValueOverride- annotation with value of override
-
assignField
public static void assignField(Field field, Object invokeOn, Object dataToAssign, boolean overrideSecurity, boolean typeCast) assign data to a field- Parameters:
field- is the field to assign toinvokeOn- to call on or null for staticdataToAssign- dataoverrideSecurity- true to call on protected or private etc methodstypeCast- true if we should typecast
-
iterator
null safe iterator getter if the type if collection- Parameters:
collection-- Returns:
- the iterator
-
length
Null safe array length or map- Parameters:
arrayOrCollection-- Returns:
- the length of the array (0 for null)
-
isArrayOrCollection
is array or collection- Parameters:
arrayOrCollection-- Returns:
- true or false
-
next
If array, get the element based on index, if Collection, get it based on iterator.- Parameters:
arrayOrCollection-iterator-index-- Returns:
- the object
-
remove
Remove the iterator or index- Parameters:
arrayOrCollection-index-- Returns:
- the object list or new array
-
remove
Remove the iterator or index- Parameters:
arrayOrCollection-iterator-index-- Returns:
- the object list or new array
-
classesString
print the simple names of a list of classes- Parameters:
object-- Returns:
- the simple names
-
classNameCollection
null safe classname method, max out at 20- Parameters:
object-- Returns:
- the classname
-
className
null safe classname method, gets the unenhanced name- Parameters:
object-- Returns:
- the classname
-
unenhanceClass
if a class is enhanced, get the unenhanced version- Parameters:
theClass-- Returns:
- the unenhanced version
-
assignField
public static void assignField(Field field, Object invokeOn, Object dataToAssign, boolean overrideSecurity, boolean typeCast, Class<? extends Annotation> annotationWithValueOverride) assign data to a field- Parameters:
field- is the field to assign toinvokeOn- to call on or null for staticdataToAssign- dataoverrideSecurity- true to call on protected or private etc methodstypeCast- true if we should typecastannotationWithValueOverride- annotation with value of override, or null if none
-
assignField
assign data to a field. Will find the field in superclasses, will typecast, and will override security (private, protected, etc)- Parameters:
invokeOn- to call on or null for staticfieldName- method name to calldataToAssign- data
-
field
public static Field field(Class theClass, String fieldName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a field object for a class, potentially in superclasses- Parameters:
theClass-fieldName-callOnSupers- true if superclasses should be looked in for the fieldthrowExceptionIfNotFound- will throw runtime exception if not found- Returns:
- the field object or null if not found (or exception if param is set)
-
fieldNames
return a set of Strings for a class and type. This is not for any supertypes, only for the type at hand. includes final fields- Parameters:
theClass-fieldType- or null for allincludeStaticFields-- Returns:
- the set of strings, or the empty Set if none
-
dbVersionDescribeDifferences
public static String dbVersionDescribeDifferences(Object theOld, Object theNew, Set<String> differentFieldNames) put in english how an object changed- Parameters:
theOld-theNew-differentFieldNames-- Returns:
- the differences
-
fieldNames
public static Set<String> fieldNames(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields) get all field names from a class, including superclasses (if specified)- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectfieldType- is the type of the field to getincludeSuperclassToStopAt- if we should include the superclassincludeStaticFields- if include static fieldsincludeFinalFields- if final fields should be included- Returns:
- the set of field names or empty set if none
-
fieldNames
public static Set<String> fieldNames(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields, Class<? extends Annotation> markerAnnotationToIngore) get all field names from a class, including superclasses (if specified). ignore a certain marker annotation- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectfieldType- is the type of the field to getincludeSuperclassToStopAt- if we should include the superclassincludeStaticFields- if include static fieldsincludeFinalFields- if final fields should be includedmarkerAnnotationToIngore- if this is not null, then if the field has this annotation, then do not include in list- Returns:
- the set of field names
-
fieldNames
public static Set<String> fieldNames(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotationToIngore) get all field names from a class, including superclasses (if specified) (up to and including the specified superclass). ignore a certain marker annotation. Dont get static or final field, and get fields of all types- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectmarkerAnnotationToIngore- if this is not null, then if the field has this annotation, then do not include in list- Returns:
- the set of field names or empty set if none
-
fields
public static Set<Field> fields(Class theClass, Class superclassToStopAt, Class fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get all fields from a class, including superclasses (if specified)- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectfieldType- is the type of the field to getincludeSuperclassToStopAt- if we should include the superclassincludeStaticFields- if include static fieldsincludeFinalFields- if final fields should be includedmarkerAnnotation- if this is not null, then if the field has this annotation, then do not include in list (if includeAnnotation is false)includeAnnotation- true if the attribute should be included if annotation is present, false if exclude- Returns:
- the set of fields (wont return null)
-
fields
public static Set<Field> fields(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get all fields from a class, including superclasses (if specified) (up to and including the specified superclass). ignore a certain marker annotation, or only include it. Dont get static or final field, and get fields of all types- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectmarkerAnnotation- if this is not null, then if the field has this annotation, then do not include in list (if includeAnnotation is false)includeAnnotation- true if the attribute should be included if annotation is present, false if exclude- Returns:
- the set of field names or empty set if none
-
compareObjectFields
public static Set<String> compareObjectFields(Object first, Object second, Set<String> fieldsToCompare, String mapPrefix) compare two objects, compare primitives, Strings, maps of string attributes. if both objects equal each others references, then return empty set. then, if not, then if either is null, return all fields- Parameters:
first-second-fieldsToCompare-mapPrefix- is the prefix for maps which are compared (e.g. attribute__)- Returns:
- the set of fields which are different. never returns null
-
clone
clone an object, assign primitives, Strings, maps of string attributes. Clone GrouperCloneable fields.- Type Parameters:
T- template- Parameters:
object-fieldsToClone-- Returns:
- the cloned object or null if input is null
-
cloneFields
clone an object, assign primitives, Strings, maps of string attributes. Clone GrouperCloneable fields.- Type Parameters:
T- template- Parameters:
object-result-fieldsToClone-
-
cloneValue
public static <T> T cloneValue(T value) helper method to clone the value of a field. just returns the same reference for primitives and immutables. Will subclone GrouperCloneables, and will throw exception if not expecting the type. Will clone sets, lists, maps.- Type Parameters:
T- template- Parameters:
value-- Returns:
- the cloned value
-
methodNames
public static Set<String> methodNames(Class<?> theClass, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods) simple method to get method names- Parameters:
theClass-superclassToStopAt-includeSuperclassToStopAt-includeStaticMethods-- Returns:
- the set of method names
-
methodByName
public static Method methodByName(Class<?> theClass, String methodName, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, boolean exceptionIfNotFound) simple method to get method names- Parameters:
theClass-methodName-superclassToStopAt-includeSuperclassToStopAt-includeStaticMethods-exceptionIfNotFound-- Returns:
- the set of method names
-
methodsHelper
public static void methodsHelper(Class<?> theClass, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation, Set<Method> methodSet) get the set of methods- Parameters:
theClass-superclassToStopAt-includeSuperclassToStopAt-includeStaticMethods-markerAnnotation-includeAnnotation-methodSet-
-
method
public static Method method(Class<?> theClass, String methodName, Object paramTypesOrArrayOrList, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean isStaticOrInstance, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get the set of methods- Parameters:
theClass-methodName-paramTypesOrArrayOrList- types of the paramssuperclassToStopAt-includeSuperclassToStopAt-isStaticOrInstance- true if staticmarkerAnnotation-includeAnnotation-- Returns:
- the method or null if not found
-
fieldValue
public static Object fieldValue(Class theClass, Object invokeOn, String fieldName, boolean callOnSupers, boolean overrideSecurity, boolean considerFieldValuable) find out a field value- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticfieldName- method name to callcallOnSupers- if static and method not exists, try on supersoverrideSecurity- true to call on protected or private etc methodsconsiderFieldValuable- if the FieldValueable interface should be considered- Returns:
- the current value
-
fieldValue
get the value of a field, override security if needbe- Parameters:
field-invokeOn-- Returns:
- the value of the field
-
fieldValue
get the value of a field- Parameters:
field-invokeOn-overrideSecurity-- Returns:
- the value of the field
-
fieldValue
find out a field value (invoke on supers, override security)- Parameters:
invokeOn- to call on or null for staticfieldName- method name to call- Returns:
- the current value
-
callMethod
helper method for calling a method with no params (could be in superclass)- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticmethodName- method name to call- Returns:
- the data
-
callMethod
public static Object callMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray) helper method for calling a method (could be in superclass)- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticmethodName- method name to callparamTypesOrArrayOrList- types of the paramsparamsOrListOrArray- data- Returns:
- the data
-
callMethod
public static Object callMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray, boolean callOnSupers) helper method for calling a method- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticmethodName- method name to callparamTypesOrArrayOrList- types of the paramsparamsOrListOrArray- datacallOnSupers- if static and method not exists, try on supers- Returns:
- the data
-
construct
construct an instance by reflection- Type Parameters:
T-- Parameters:
theClass-args-types-- Returns:
- the instance
-
listToMap
public static <K,V> Map<K,V> listToMap(List<V> list, Class<K> keyClass, Class<V> valueClass, String keyPropertyName) turn a list into map
- Type Parameters:
K- is the template of the key of the mapV- is the template of the value of the map- Parameters:
list- is the list to convertvalueClass- type of the result (can typecast)keyClass- is the type of the key of the mapkeyPropertyName- name of the javabeans property for the key in the map- Returns:
- the ordered set or the empty set if not found (never null)
-
callMethod
public static Object callMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray, boolean callOnSupers, boolean overrideSecurity) helper method for calling a method- Parameters:
theClass- the class which has the methodinvokeOn- to call on or null for staticmethodName- method name to callparamTypesOrArrayOrList- types of the paramsparamsOrListOrArray- datacallOnSupers- if static and method not exists, try on supersoverrideSecurity- true to call on protected or private etc methods- Returns:
- the data
-
invokeMethod
Safely invoke a reflection method that takes no args- Parameters:
method- to invokeinvokeOn- if NO_PARAMS then will not pass in params.- Returns:
- the result
-
invokeMethod
Safely invoke a reflection method- Parameters:
method- to invokeinvokeOn-paramsOrListOrArray- must be an arg. If null, will pass null. if NO_PARAMS then will not pass in params.- Returns:
- the result
-
toArray
Convert a list to an array with the type of the first element e.g. if it is a list of Person objects, then the array is Person[]- Parameters:
objectOrArrayOrCollection- is a list- Returns:
- the array of objects with type of the first element in the list
-
toArray
convert a list into an array of type of theClass- Type Parameters:
T- is the type of the array- Parameters:
collection- list to converttheClass- type of array to return- Returns:
- array of type theClass[] filled with the objects from list
-
callMethod
helper method for calling a static method up the stack. method takes no args (could be in superclass)- Parameters:
theClass- the class which has the methodmethodName- method name to call- Returns:
- the data
-
callMethod
helper method for calling a static method with no params- Parameters:
theClass- the class which has the methodmethodName- method name to callcallOnSupers- if we should try the super classes if not exists in this class- Returns:
- the data
-
callMethod
public static Object callMethod(Class theClass, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray) helper method for calling a static method up the stack- Parameters:
theClass- the class which has the methodmethodName- method name to callparamTypesOrArrayOrList- types of the paramsparamsOrListOrArray- data- Returns:
- the data
-
callMethod
helper method for calling a method with no params (could be in superclass), will override security- Parameters:
invokeOn- instance to invoke onmethodName- method name to call not exists in this class- Returns:
- the data
-
replace
replace a string or strings from a string, and put the output in a string buffer. This does not recurse- Parameters:
text- string to look insearchFor- string array to search forreplaceWith- string array to replace with- Returns:
- the string
-
replace
replace a string or strings from a string, and put the output in a string buffer- Parameters:
text- string to look insearchFor- string array to search forreplaceWith- string array to replace withrecurse- if true then do multiple replaces (on the replacements)- Returns:
- the string
-
replace
public static String replace(String text, Object searchFor, Object replaceWith, boolean recurse, boolean removeIfFound) replace a string or strings from a string, and put the output in a string buffer- Parameters:
text- string to look insearchFor- string array to search forreplaceWith- string array to replace withrecurse- if true then do multiple replaces (on the replacements)removeIfFound- true if removing from searchFor and replaceWith if found- Returns:
- the string
-
replace
Replaces all occurrences of a String within another String.
A
nullreference passed to this method is a no-op.replace(null, *, *) = null replace("", *, *) = "" replace("any", null, *) = "any" replace("any", *, null) = "any" replace("any", "", *) = "any" replace("aba", "a", null) = "aba" replace("aba", "a", "") = "b" replace("aba", "a", "z") = "zbz"- Parameters:
text- text to search and replace in, may be nullrepl- the String to search for, may be nullwith- the String to replace with, may be null- Returns:
- the text with any replacements processed,
nullif null String input - See Also:
-
replace
Replaces a String with another String inside a larger String, for the first
maxvalues of the search String.A
nullreference passed to this method is a no-op.replace(null, *, *, *) = null replace("", *, *, *) = "" replace("any", null, *, *) = "any" replace("any", *, null, *) = "any" replace("any", "", *, *) = "any" replace("any", *, *, 0) = "any" replace("abaa", "a", null, -1) = "abaa" replace("abaa", "a", "", -1) = "b" replace("abaa", "a", "z", 0) = "abaa" replace("abaa", "a", "z", 1) = "zbaa" replace("abaa", "a", "z", 2) = "zbza" replace("abaa", "a", "z", -1) = "zbzz"- Parameters:
text- text to search and replace in, may be nullrepl- the String to search for, may be nullwith- the String to replace with, may be nullmax- maximum number of values to replace, or-1if no maximum- Returns:
- the text with any replacements processed,
nullif null String input
-
isEmpty
Checks if a String is empty ("") or null.
isEmpty(null) = true isEmpty("") = true isEmpty(" ") = false isEmpty("bob") = false isEmpty(" bob ") = falseNOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank().
- Parameters:
str- the String to check, may be null- Returns:
trueif the String is empty or null
-
replace
public static void replace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith) replace a string or strings from a string, and put the output in a string buffer. This does not recurse- Parameters:
outBuffer- stringbuffer to write totext- string to look insearchFor- string array to search forreplaceWith- string array to replace with
-
replace
public static void replace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith, boolean recurse) replace a string or strings from a string, and put the output in a string buffer- Parameters:
outBuffer- stringbuffer to write totext- string to look insearchFor- string array to search forreplaceWith- string array to replace withrecurse- if true then do multiple replaces (on the replacements)
-
replace
replace a string or strings from a string, and put the output in a string buffer. This does not recurse- Parameters:
outWriter- writer to write totext- string to look insearchFor- string array to search forreplaceWith- string array to replace with
-
replace
public static void replace(Writer outWriter, String text, Object searchFor, Object replaceWith, boolean recurse) replace a string or strings from a string, and put the output in a string buffer- Parameters:
outWriter- writer to write totext- string to look insearchFor- string array to search forreplaceWith- string array to replace withrecurse- if true then do multiple replaces (on the replacements)
-
packInts
public static long packInts(int first, int second) pack two ints into a long. Note: the first is held in the left bits, the second is held in the right bits- Parameters:
first- is first intsecond- is second int- Returns:
- the long which has two ints in there
-
unpackInt
public static int unpackInt(long theLong, boolean isFirst) take a long- Parameters:
theLong- to unpackisFirst- true for first, false for second- Returns:
- one of the packed ints, first or second
-
get
Get a specific index of an array or collection (note for collections and iterating, it is more efficient to get an iterator and iterate- Parameters:
arrayOrCollection-index-- Returns:
- the object at that index
-
toString
convert a collection of sources to a string- Parameters:
sources-- Returns:
- the string
-
toStringSafe
fail safe toString for Exception blocks, and include the stack if there is a problem with toString()- Parameters:
object-- Returns:
- the toStringSafe string
-
booleanValue
get the boolean value for an object, cant be null or blank- Parameters:
object-- Returns:
- the boolean
-
booleanValue
get the boolean value for an object- Parameters:
object-defaultBoolean- if object is null or empty- Returns:
- the boolean
-
booleanObjectValue
get the Boolean value for an object- Parameters:
object-- Returns:
- the Boolean or null if null or empty
-
nullOrBlank
is an object null or blank- Parameters:
object-- Returns:
- true if null or blank
-
getter
public static Method getter(Class theClass, String fieldName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a getter method object for a class, potentially in superclasses- Parameters:
theClass-fieldName-callOnSupers- true if superclasses should be looked in for the getterthrowExceptionIfNotFound- will throw runtime exception if not found- Returns:
- the getter object or null if not found (or exception if param is set)
-
getterHelper
public static Method getterHelper(Class theClass, String fieldName, String getterName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a setter method object for a class, potentially in superclasses- Parameters:
theClass-fieldName-getterName- name of settercallOnSupers- true if superclasses should be looked in for the setterthrowExceptionIfNotFound- will throw runtime exception if not found- Returns:
- the setter object or null if not found (or exception if param is set)
-
getterNameFromPropertyName
generate getBb from bb- Parameters:
propertyName-- Returns:
- the getter
-
getters
public static Set<Method> getters(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotation, Boolean includeAnnotation) get all getters from a class, including superclasses (if specified) (up to and including the specified superclass). ignore a certain marker annotation, or only include it. Dont get static or final getters, and get getters of all types- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectmarkerAnnotation- if this is not null, then if the field has this annotation, then do not include in list (if includeAnnotation is false)includeAnnotation- true if the attribute should be included if annotation is present, false if exclude- Returns:
- the set of field names or empty set if none
-
isGetter
if the method name starts with get, and takes no args, and returns something, then getter- Parameters:
method-- Returns:
- true if getter
-
assignSetter
public static void assignSetter(Object invokeOn, String fieldName, Object dataToAssign, boolean typeCast) assign data to a setter. Will find the field in superclasses, will typecast, and will override security (private, protected, etc)- Parameters:
invokeOn- to call on or null for staticfieldName- method name to calldataToAssign- datatypeCast- will typecast if true- Throws:
PropertyDoesNotExistUnchecked- if not there
-
isSetter
if the method name starts with get, and takes no args, and returns something, then getter- Parameters:
method-- Returns:
- true if getter
-
setter
public static Method setter(Class theClass, String fieldName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a setter method object for a class, potentially in superclasses- Parameters:
theClass-fieldName-callOnSupers- true if superclasses should be looked in for the setterthrowExceptionIfNotFound- will throw runtime exception if not found- Returns:
- the setter object or null if not found (or exception if param is set)
-
setterHelper
public static Method setterHelper(Class theClass, String fieldName, String setterName, boolean callOnSupers, boolean throwExceptionIfNotFound) get a setter method object for a class, potentially in superclasses- Parameters:
theClass-fieldName-setterName- name of settercallOnSupers- true if superclasses should be looked in for the setterthrowExceptionIfNotFound- will throw runtime exception if not found- Returns:
- the setter object or null if not found (or exception if param is set)
-
setterNameFromPropertyName
generate setBb from bb- Parameters:
propertyName-- Returns:
- the setter
-
setters
public static Set<Method> setters(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) get all setters from a class, including superclasses (if specified)- Parameters:
theClass- to look for fields insuperclassToStopAt- to go up to or null to go up to ObjectfieldType- is the type of the field to getincludeSuperclassToStopAt- if we should include the superclassmarkerAnnotation- if this is not null, then if the field has this annotation, then do not include in list (if includeAnnotation is false)includeAnnotation- true if the attribute should be included if annotation is present, false if exclude- Returns:
- the set of fields (wont return null)
-
propertyName
If this is a getter or setter, then get the property name- Parameters:
method-- Returns:
- the property name
-
propertyList
public static <T> List<T> propertyList(Collection<?> collection, String propertyName, Class<T> fieldType) take a collection of beans, and go through and get all the values of one of the javabean properties, and make a list of those values.- Type Parameters:
T-- Parameters:
collection-propertyName-fieldType-- Returns:
- the list
-
propertyType
use reflection to get a property type based on getter or setter or field- Parameters:
theClass-propertyName-- Returns:
- the property type
-
typeCast
If necessary, convert an object to another type. if type is Object.class, just return the input. Do not convert null to an empty primitive- Type Parameters:
T- is template type- Parameters:
value-theClass-- Returns:
- the object of that instance converted into something else
-
newFileUniqueName
public static File newFileUniqueName(String parentDirName, String namePrefix, String nameSuffix, boolean createFile) make a new file in the name prefix dir. If parent dir name is c:\temp and namePrefix is grouperDdl and nameSuffix is sql, then the file will be: c:\temp\grouperDdl_20080721_13_45_43_123.sql If the file exists, it will make a new filename, and create the empty file, and return it
- Parameters:
parentDirName- can be blank for current dirnamePrefix- the part before the date partnameSuffix- the last part of file name (can contain dot or will be the extensioncreateFile- true to create the file- Returns:
- the created file
-
dateLongValue
convert a string date into a long date (e.g. for xml export)- Parameters:
date-- Returns:
- the long or null if the date was null or blank
-
dateStringValue
date object to a string:- Parameters:
date-- Returns:
- the long or null if the date was null or blank
-
dateStringValue
date object to a string:- Parameters:
theDate-- Returns:
- the long or null if the date was null or blank
-
dateValue
Convert an object to a java.util.Date. allows, dates, null, blank, yyyymmdd or yyyymmdd hh24:mm:ss or yyyy/MM/dd HH:mm:ss.SSS
- Parameters:
inputObject- is the String or Date to convert- Returns:
- the Date
-
stringToDate2
take as input: yyyy/mm/dd yyyy-mm-dd dd-mon-yyyy yyyy/mm/dd hh:mm:ss dd-mon-yyyy hh:mm:ss yyyy/mm/dd hh:mm:ss.SSS dd-mon-yyyy hh:mm:ss.SSS- Parameters:
input-- Returns:
- the date
-
stringToDate3
public static Date stringToDate3(String dateString, String configuredDateFormat) throws ParseException Parse a date string from the UI.Accepts either:
- The configured UI format (e.g. MM/dd/yyyy)
- ISO local date from native browser date inputs (yyyy-MM-dd)
- Parameters:
dateString- date string from requestconfiguredDateFormat- configured format from properties / i18n- Returns:
- parsed date, or null if input is blank
- Throws:
ParseException- if it can't be parsed as either supported format
-
monthInt
convert a month string to an int (1 indexed). e.g. if input is feb or Feb or february or February return 2- Parameters:
mon-- Returns:
- the month
-
isBlank
See if the input is null or if string, if it is empty or blank (whitespace)- Parameters:
input-- Returns:
- true if blank
-
isEmpty
See if the input is null or if string, if it is empty (whitespace)- Parameters:
input-- Returns:
- true if empty
-
typeCast
public static <T> T typeCast(Object value, Class<T> theClass, boolean convertNullToDefaultPrimitive, boolean useNewInstanceHooks) If necessary, convert an object to another type. if type is Object.class, just return the input- Type Parameters:
T- is the type to return- Parameters:
value-theClass-convertNullToDefaultPrimitive- if the value is null, and theClass is primitive, should we convert the null to a primitive default valueuseNewInstanceHooks- if theClass is not recognized, then honor the string "null", "newInstance", or get a constructor with one param, and call it- Returns:
- the object of that instance converted into something else
-
isScalar
see if a class is a scalar (not bean, not array or list, etc)- Parameters:
type-- Returns:
- true if scalar
-
toTimestamp
Convert a string or object to a timestamp (could be string, date, timestamp, etc) yyyymmdd or yyyy/MM/dd or yyyy-MM-dd or yyyy/MM/dd HH:mm:ss or yyyy/MM/dd HH:mm:ss.SSS or yyyy/MM/dd HH:mm:ss.SSSSSS
- Parameters:
input-- Returns:
- the timestamp
- Throws:
RuntimeException- if invalid format
-
stringValue
convert an object to a string- Parameters:
input- is the object to convert- Returns:
- the String conversion of the object
-
timestampToString
Convert a timestamp into a string: yyyy/MM/dd HH:mm:ss.SSS- Parameters:
timestamp-- Returns:
- the string representation
-
timestampToFileString
Convert a timestamp into a string: yyyy_MM_dd__HH_mm_ss_SSS- Parameters:
timestamp-- Returns:
- the string representation
-
stringValue
convert a date to the standard string yyyymmdd- Parameters:
date-- Returns:
- the string value
-
stringToTimestamp
convert a string to timestamp based on the following formats: yyyyMMdd yyyy/MM/dd yyyy/MM/dd HH:mm:ss yyyy/MM/dd HH:mm:ss.SSS yyyy/MM/dd HH:mm:ss.SSSSSS
- Parameters:
input-- Returns:
- the timestamp object
-
stringToTimestampTimeRequiredWithoutSeconds
convert a string to timestamp based on the following formats: 2011-07-18T15:24+02:00 2011/07/18 15:24 2011/07/18 3:24 PM
- Parameters:
input-- Returns:
- the timestamp object
-
stringToTimestampTimeRequiredLocalDateTime
convert a string to timestamp based on the following formats: 2022-02-15T15:27:42 2022-02-15T15:27
- Parameters:
input-- Returns:
- the timestamp object
-
bigDecimalObjectValue
Convert an object to a byte, allow nulls- Parameters:
input-- Returns:
- the boolean object value
-
byteObjectValue
Convert an object to a byte, allow nulls- Parameters:
input-- Returns:
- the boolean object value
-
byteValue
convert an object to a byte- Parameters:
input-- Returns:
- the byte
-
doubleObjectValue
get the Double value of an object- Parameters:
input- is a number or StringallowNullBlank- used to default to false, if true, return null if nul inputted- Returns:
- the Double equivalent
-
doubleValue
get the double value of an object- Parameters:
input- is a number or String- Returns:
- the double equivalent
-
doubleValueNoError
get the double value of an object, do not throw an exception if there is an error- Parameters:
input- is a number or String- Returns:
- the double equivalent
-
floatObjectValue
get the Float value of an object- Parameters:
input- is a number or StringallowNullBlank- true if allow null or blank- Returns:
- the Float equivalent
-
floatValue
get the float value of an object- Parameters:
input- is a number or String- Returns:
- the float equivalent
-
floatValue
get the float value of an object- Parameters:
input- is a number or String- Returns:
- the float equivalent
-
floatValueNoError
get the float value of an object, do not throw an exception if there is an error- Parameters:
input- is a number or String- Returns:
- the float equivalent
-
intObjectValue
get the Integer value of an object- Parameters:
input- is a number or StringallowNullBlank- true if convert null or blank to null- Returns:
- the Integer equivalent
-
intValue
convert an object to a int- Parameters:
input-- Returns:
- the number
-
intValue
convert an object to a int- Parameters:
input-valueIfNull- is if the input is null or empty, return this value- Returns:
- the number
-
stemCalculateTopLevelStems
if these are the stems to sync: a:b:c, a:b, a:d, a:b:d, then the top level are: a:b, a:d- Returns:
-
stemRemoveChildStemsOfTopStem
remove stems that are children of the top level stem- Parameters:
stems-
-
stemRemoveAncestorStemsOfChildStem
remove stems that are ancestor of the child stem- Parameters:
stems-
-
stemRemoveChildStemsOfTopStemName
remove stems that are children of the top level stem- Parameters:
stems-
-
intValueNoError
get the int value of an object, do not throw an exception if there is an error- Parameters:
input- is a number or String- Returns:
- the int equivalent
-
longObjectValue
get the Long value of an object- Parameters:
input- is a number or StringallowNullBlank- true if null or blank converts to null- Returns:
- the Long equivalent
-
timestampObjectValue
get the Timestamp value of an object- Parameters:
input- is a timestamp or longallowNullBlank- true if null or blank converts to null- Returns:
- the Long equivalent
-
longValue
convert an object to a long- Parameters:
input-- Returns:
- the number
-
logFirstMax
log first few items, separate with semicolons and spaces- Parameters:
collection-numberToLog-- Returns:
- the string to log
-
multiKeySet
take a collection of Objectp[- Parameters:
collection-- Returns:
- the set of multikeys
-
longValue
convert an object to a long- Parameters:
input-valueIfNull- is if the input is null or empty, return this value- Returns:
- the number
-
longValueNoError
get the long value of an object, do not throw an exception if there is an error- Parameters:
input- is a number or String- Returns:
- the long equivalent
-
shortObjectValue
get the Short value of an object. converts null or blank to null- Parameters:
input- is a number or String- Returns:
- the Long equivalent
-
shortValue
convert an object to a short- Parameters:
input-- Returns:
- the number
-
charObjectValue
get the Character wrapper value for the input- Parameters:
input- allow null, return null- Returns:
- the Character object wrapper
-
characterMatchesRegex
- Parameters:
character-regex-- Returns:
- if regex
-
charValue
convert an object to a char- Parameters:
input-- Returns:
- the number
-
createParentDirectories
Create the parent directories for a file if they do not already exist- Parameters:
file-
-
saveStringIntoFile
save a string into a file, file does not have to exist- Parameters:
file- is the file to save tocontents- is the contents of the file
-
whitespaceRemove
remove whitespace from string- Returns:
- new string
-
whitespaceNormalizeNewLines
normalize new lines to unix- Parameters:
input-- Returns:
- new string
-
whitespaceCountNewLines
normalize newlines then count newlines- Parameters:
input-- Returns:
- new string
-
saveStringIntoFile
public static boolean saveStringIntoFile(File file, String contents, boolean onlyIfDifferentContents, boolean ignoreWhitespace) save a string into a file, file does not have to exist- Parameters:
file- is the file to save tocontents- is the contents of the fileonlyIfDifferentContents- true if only saving due to different contentsignoreWhitespace- true to ignore whitespace- Returns:
- true if contents were saved (thus different if param set)
-
writeStringToFile
Writes data to a file. The file will be created if it does not exist.
There is no readFileToString method without encoding parameter because the default encoding can differ between platforms and therefore results in inconsistent results.
- Parameters:
file- the file to write.data- The content to write to the file.encoding- encoding to use- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM
-
readFileIntoString
- Parameters:
file- is the file to read into a string- Returns:
- String
-
readResourceIntoString
- Parameters:
resourceName- is the string resource from classpath to read (e.g. grouper.properties)allowNull- is true if its ok if the resource is null or if it is not found or blank or whatever.- Returns:
- String or null if allowed or RuntimeException if not allowed
-
readFileToString
Reads the contents of a file into a String.
There is no readFileToString method without encoding parameter because the default encoding can differ between platforms and therefore results in inconsistent results.
- Parameters:
file- the file to read.encoding- the encoding to use- Returns:
- The file contents or null if read failed.
- Throws:
IOException- in case of an I/O error
-
replaceWhitespaceWithSpace
replace all whitespace with space- Parameters:
input-- Returns:
- the string
-
closeQuietly
Unconditionally close anInputStream. Equivalent toInputStream.close(), except any exceptions will be ignored.- Parameters:
input- A (possibly null) InputStream
-
closeQuietly
Unconditionally close anOutputStream. Equivalent toOutputStream.close(), except any exceptions will be ignored.- Parameters:
output- A (possibly null) OutputStream
-
closeQuietly
Unconditionally close anReader. Equivalent toReader.close(), except any exceptions will be ignored.- Parameters:
input- A (possibly null) Reader
-
closeQuietly
close a writer quietly- Parameters:
writer-
-
closeQuietly
close a writer quietly- Parameters:
writer-
-
toString
Get the contents of anInputStreamas a String.- Parameters:
input- theInputStreamto read fromencoding- The name of a supported character encoding. See the IANA Charset Registry for a list of valid encoding types.- Returns:
- the requested
String - Throws:
IOException- In case of an I/O problem
-
copy
Copy and convert bytes from anInputStreamto chars on aWriter, using the specified encoding.- Parameters:
input- theInputStreamto read fromoutput- theWriterto write toencoding- The name of a supported character encoding. See the IANA Charset Registry for a list of valid encoding types.- Throws:
IOException- In case of an I/O problem
-
copy
Copy chars from aReaderto aWriter.- Parameters:
input- theReaderto read fromoutput- theWriterto write to- Returns:
- the number of characters copied
- Throws:
IOException- In case of an I/O problem
-
threadJoin
join a thread- Parameters:
thread-
-
threadJoin
join a thread- Parameters:
thread-millis-
-
convertLongToChar
this method takes a long (less than 62) and converts it to a 1 character string (a-z, A-Z, 0-9)- Parameters:
theLong- is the long (less than 62) to convert to a 1 character string- Returns:
- a one character string
-
convertLongToCharSmall
this method takes a long (less than 36) and converts it to a 1 character string (A-Z, 0-9)- Parameters:
theLong- is the long (less than 36) to convert to a 1 character string- Returns:
- a one character string
-
convertLongToString
convert a long to a string by converting it to base 62 (26 lower, 26 upper, 10 digits)- Parameters:
theLong- is the long to convert- Returns:
- the String conversion of this
-
convertLongToStringSmall
convert a long to a string by converting it to base 36 (26 upper, 10 digits)- Parameters:
theLong- is the long to convert- Returns:
- the String conversion of this
-
incrementChar
public static char incrementChar(char theChar) increment a character (A-Z then 0-9)- Parameters:
theChar-- Returns:
- the value
-
incrementStringInt
public static char[] incrementStringInt(char[] string) Increment a string with A-Z and 0-9 (no lower case so case insensitive apps like windows IE will still work)- Parameters:
string-- Returns:
- the value
-
propertiesFromResourceName
read properties from a resource, dont modify the properties returned since they are cached- Parameters:
resourceName-- Returns:
- the properties
-
propertiesFromUrl
public static Properties propertiesFromUrl(String urlString, boolean useCache, boolean useFailSafeCache, GrouperHtmlFilter grouperHtmlFilter) this will get the properties from an external url. It will cache these (failsafe), and will escape them based on grouper's properties escaper (configurable)- Parameters:
urlString- e.g. http://localhost:8090/grouper/test.propertiesuseCache- if should cache for 2 minutesuseFailSafeCache- if should use this cache for 1 day if the url cant connectgrouperHtmlFilter-- Returns:
- the properties
-
propertiesFromFile
properties from file- Parameters:
file-useCache-- Returns:
- properties
-
propertiesFromResourceName
public static Properties propertiesFromResourceName(String resourceName, boolean useCache, boolean exceptionIfNotExist) read properties from a resource, dont modify the properties returned since they are cached- Parameters:
resourceName-useCache-exceptionIfNotExist-- Returns:
- the properties or null if not exist
-
enumValueOfIgnoreCase
public static <E extends Enum<?>> E enumValueOfIgnoreCase(Class<E> theEnumClass, String string, boolean exceptionOnBlank) throws RuntimeException do a case-insensitive matching- Type Parameters:
E- generic type- Parameters:
theEnumClass- class of the enumstring-exceptionOnBlank- true if exception should be thrown on not found- Returns:
- the enum or null or exception if not found
- Throws:
RuntimeException- if there is a problem
-
enumValueOfIgnoreCase
public static <E extends Enum<?>> E enumValueOfIgnoreCase(Class<E> theEnumClass, String string, boolean exceptionOnBlank, boolean exceptionIfInvalid) throws RuntimeException do a case-insensitive matching- Type Parameters:
E- generic type- Parameters:
theEnumClass- class of the enumstring-exceptionOnBlank- true if exception should be thrown on not foundexceptionIfInvalid- if there is a string, but it is invalid, if should throw exception- Returns:
- the enum or null or exception if not found
- Throws:
RuntimeException- if there is a problem
-
retrievePropertyDescriptor
if there is a valid accessible property descriptor, get it- Parameters:
object-property-- Returns:
- the property descriptor
-
propertyValue
this assumes the property exists, and is a simple property- Parameters:
object-property-- Returns:
- the value
-
propertiesValue
get a value (trimmed to e) from a property file- Parameters:
properties-key-- Returns:
- the property value
-
propertiesValue
public static String propertiesValue(Properties properties, Map<String, String> overrideMap, String key) get a value (trimmed to e) from a property file- Parameters:
properties-overrideMap- for testing, to override some properties valueskey-- Returns:
- the property value
-
propertiesToString
convert properties to a string (comma separate)- Parameters:
properties-- Returns:
- the String
-
propertiesValue
public static String propertiesValue(Properties properties, Map<String, String> overrideMap, Map<String, String> overrideMap2, String key) get a value (trimmed to e) from a property file- Parameters:
properties-overrideMap- for testing or threadlocal, to override some properties valuesoverrideMap2- for testing, to provide some properties valueskey-- Returns:
- the property value
-
propertiesValueBoolean
public static boolean propertiesValueBoolean(Properties properties, String propertyName, boolean defaultValue) get a boolean property, or the default if cant find- Parameters:
properties-propertyName-defaultValue-- Returns:
- the boolean
-
propertiesValueBoolean
public static boolean propertiesValueBoolean(Properties properties, Map<String, String> overrideMap, String propertyName, boolean defaultValue) get a boolean property, or the default if cant find- Parameters:
properties-overrideMap- for testing to override propertiespropertyName-defaultValue-- Returns:
- the boolean
-
propertiesValueBoolean
public static boolean propertiesValueBoolean(Properties properties, Map<String, String> overrideMap, Map<String, String> overrideMap2, String propertyName, boolean defaultValue) get a boolean property, or the default if cant find- Parameters:
properties-overrideMap- for testing or threadlocal to override propertiesoverrideMap2- for testing or threadlocal to override propertiespropertyName-defaultValue-- Returns:
- the boolean
-
closeQuietly
close a connection null safe and dont throw exception- Parameters:
connection-
-
closeQuietly
public static void closeQuietly(org.hibernate.Session session) close a session null safe and dont throw exception- Parameters:
session-
-
closeQuietly
close a statement null safe and dont throw exception- Parameters:
statement-
-
closeQuietly
close a resultSet null safe and dont throw exception- Parameters:
resultSet-
-
hostname
get the hostname of this machine- Returns:
- the hostname
-
isAscii
public static boolean isAscii(char input) is ascii char- Parameters:
input-- Returns:
- true if ascii
-
lengthAscii
find the length of ascii chars (non ascii are counted as two)- Parameters:
input-- Returns:
- the length of ascii chars
-
rollbackQuietly
public static void rollbackQuietly(org.hibernate.Transaction transaction) rollback a transaction quietly- Parameters:
transaction-
-
rollbackQuietly
rollback a connection quietly- Parameters:
connection-
-
stringLength
string length- Parameters:
string-- Returns:
- string length
-
closeQuietly
close a writer quietly- Parameters:
closeable-
-
fileCreateNewFile
create a new file- Parameters:
file-- Returns:
- if created
-
truncateAscii
find the length of ascii chars (non ascii are counted as three)- Parameters:
input- is the string to operate onrequiredLength- length we need the string to be- Returns:
- the length of ascii chars
-
subjectToString
convert a subject to string safely- Parameters:
subject-- Returns:
- the string value of subject (might be null)
-
readFromFileIfFile
if the input is a file, read string from file. if not, or if disabled from grouper.properties, return the input- Parameters:
in-disableExternalFileLookup-- Returns:
- the result
-
mkdirs
Create directories, throw exception if not possible. This is will be ok if the directory already exists (will not delete it)- Parameters:
dir-
-
fixRelativePath
- Parameters:
inPath-- Returns:
- string
-
equals
null safe string compare- Parameters:
first-second-- Returns:
- true if equal
-
isBlank
Checks if a String is whitespace, empty ("") or null.
isBlank(null) = true isBlank("") = true isBlank(" ") = true isBlank("bob") = false isBlank(" bob ") = false- Parameters:
str- the String to check, may be null- Returns:
trueif the String is null, empty or whitespace- Since:
- 2.0
-
isNotBlank
- Parameters:
str-- Returns:
- true if not blank
-
trim
trim whitespace from string- Parameters:
str-- Returns:
- trimmed string
-
equalsIgnoreCase
equalsignorecase- Parameters:
str1-str2-- Returns:
- true if the strings are equal ignore case
-
trimToEmpty
trim to empty, convert null to empty- Parameters:
str-- Returns:
- trimmed
-
abbreviate
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..."
Specifically:
- If
stris less thanmaxWidthcharacters long, return it. - Else abbreviate it to
(substring(str, 0, max-3) + "..."). - If
maxWidthis less than4, throw anIllegalArgumentException. - In no case will it return a String of length greater than
maxWidth.
StringUtils.abbreviate(null, *) = null StringUtils.abbreviate("", 4) = "" StringUtils.abbreviate("abcdefg", 6) = "abc..." StringUtils.abbreviate("abcdefg", 7) = "abcdefg" StringUtils.abbreviate("abcdefg", 8) = "abcdefg" StringUtils.abbreviate("abcdefg", 4) = "a..." StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException- Parameters:
str- the String to check, may be nullmaxWidth- maximum length of result String, must be at least 4- Returns:
- abbreviated String,
nullif null String input - Throws:
IllegalArgumentException- if the width is too small- Since:
- 2.0
- If
-
exceptionConvertToRuntime
-
exceptionConvertToRuntime
-
abbreviate
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "...is the time for..."
Works like
abbreviate(String, int), but allows you to specify a "left edge" offset. Note that this left edge is not necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear somewhere in the result.In no case will it return a String of length greater than
maxWidth.StringUtils.abbreviate(null, *, *) = null StringUtils.abbreviate("", 0, 4) = "" StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..." StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..." StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException- Parameters:
str- the String to check, may be nulloffset- left edge of source StringmaxWidth- maximum length of result String, must be at least 4- Returns:
- abbreviated String,
nullif null String input - Throws:
IllegalArgumentException- if the width is too small- Since:
- 2.0
-
split
Splits the provided text into an array, using whitespace as the separator. Whitespace is defined by
Character.isWhitespace(char).The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull.StringUtils.split(null) = null StringUtils.split("") = [] StringUtils.split("abc def") = ["abc", "def"] StringUtils.split("abc def") = ["abc", "def"] StringUtils.split(" abc ") = ["abc"]- Parameters:
str- the String to parse, may be null- Returns:
- an array of parsed Strings,
nullif null String input
-
split
Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull.StringUtils.split(null, *) = null StringUtils.split("", *) = [] StringUtils.split("a.b.c", '.') = ["a", "b", "c"] StringUtils.split("a..b.c", '.') = ["a", "b", "c"] StringUtils.split("a:b:c", '.') = ["a:b:c"] StringUtils.split("a\tb\nc", null) = ["a", "b", "c"] StringUtils.split("a b c", ' ') = ["a", "b", "c"]- Parameters:
str- the String to parse, may be nullseparatorChar- the character used as the delimiter,nullsplits on whitespace- Returns:
- an array of parsed Strings,
nullif null String input - Since:
- 2.0
-
split
Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull. AnullseparatorChars splits on whitespace.StringUtils.split(null, *) = null StringUtils.split("", *) = [] StringUtils.split("abc def", null) = ["abc", "def"] StringUtils.split("abc def", " ") = ["abc", "def"] StringUtils.split("abc def", " ") = ["abc", "def"] StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]- Parameters:
str- the String to parse, may be nullseparatorChars- the characters used as the delimiters,nullsplits on whitespace- Returns:
- an array of parsed Strings,
nullif null String input
-
split
Splits the provided text into an array with a maximum length, separators specified.
The separator is not included in the returned String array. Adjacent separators are treated as one separator.
A
nullinput String returnsnull. AnullseparatorChars splits on whitespace.If more than
maxdelimited substrings are found, the last returned string includes all characters after the firstmax - 1returned strings (including separator characters).StringUtils.split(null, *, *) = null StringUtils.split("", *, *) = [] StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]- Parameters:
str- the String to parse, may be nullseparatorChars- the characters used as the delimiters,nullsplits on whitespacemax- the maximum number of elements to include in the array. A zero or negative value implies no limit- Returns:
- an array of parsed Strings,
nullif null String input
-
splitByWholeSeparator
Splits the provided text into an array, separator string specified.
The separator(s) will not be included in the returned String array. Adjacent separators are treated as one separator.
A
nullinput String returnsnull. Anullseparator splits on whitespace.StringUtils.split(null, *) = null StringUtils.split("", *) = [] StringUtils.split("ab de fg", null) = ["ab", "de", "fg"] StringUtils.split("ab de fg", null) = ["ab", "de", "fg"] StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"] StringUtils.split("abstemiouslyaeiouyabstemiously", "aeiouy") = ["bst", "m", "sl", "bst", "m", "sl"] StringUtils.split("abstemiouslyaeiouyabstemiously", "aeiouy") = ["abstemiously", "abstemiously"]- Parameters:
str- the String to parse, may be nullseparator- String containing the String to be used as a delimiter,nullsplits on whitespace- Returns:
- an array of parsed Strings,
nullif null String was input
-
splitByWholeSeparator
Splits the provided text into an array, separator string specified. Returns a maximum of
maxsubstrings.The separator(s) will not be included in the returned String array. Adjacent separators are treated as one separator.
A
nullinput String returnsnull. Anullseparator splits on whitespace.StringUtils.splitByWholeSeparator(null, *, *) = null StringUtils.splitByWholeSeparator("", *, *) = [] StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"] StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"] StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd"] StringUtils.splitByWholeSeparator("abstemiouslyaeiouyabstemiously", "aeiouy", 2) = ["bst", "m"] StringUtils.splitByWholeSeparator("abstemiouslyaeiouyabstemiously", "aeiouy", 2) = ["abstemiously", "abstemiously"]- Parameters:
str- the String to parse, may be nullseparator- String containing the String to be used as a delimiter,nullsplits on whitespacemax- the maximum number of elements to include in the returned array. A zero or negative value implies no limit.- Returns:
- an array of parsed Strings,
nullif null String was input
-
splitPreserveAllTokens
Splits the provided text into an array, using whitespace as the separator, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer. Whitespace is defined by
Character.isWhitespace(char).The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull.StringUtils.splitPreserveAllTokens(null) = null StringUtils.splitPreserveAllTokens("") = [] StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"] StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]- Parameters:
str- the String to parse, may benull- Returns:
- an array of parsed Strings,
nullif null String input - Since:
- 2.1
-
splitPreserveAllTokens
Splits the provided text into an array, separator specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull.StringUtils.splitPreserveAllTokens(null, *) = null StringUtils.splitPreserveAllTokens("", *) = [] StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"] StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""] StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""] StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"] StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"] StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]- Parameters:
str- the String to parse, may benullseparatorChar- the character used as the delimiter,nullsplits on whitespace- Returns:
- an array of parsed Strings,
nullif null String input - Since:
- 2.1
-
splitPreserveAllTokens
Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull. AnullseparatorChars splits on whitespace.StringUtils.splitPreserveAllTokens(null, *) = null StringUtils.splitPreserveAllTokens("", *) = [] StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""] StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""] StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"] StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"] StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"] StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]- Parameters:
str- the String to parse, may benullseparatorChars- the characters used as the delimiters,nullsplits on whitespace- Returns:
- an array of parsed Strings,
nullif null String input - Since:
- 2.1
-
splitPreserveAllTokens
Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. Adjacent separators are treated as one separator.
A
nullinput String returnsnull. AnullseparatorChars splits on whitespace.If more than
maxdelimited substrings are found, the last returned string includes all characters after the firstmax - 1returned strings (including separator characters).StringUtils.splitPreserveAllTokens(null, *, *) = null StringUtils.splitPreserveAllTokens("", *, *) = [] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]- Parameters:
str- the String to parse, may benullseparatorChars- the characters used as the delimiters,nullsplits on whitespacemax- the maximum number of elements to include in the array. A zero or negative value implies no limit- Returns:
- an array of parsed Strings,
nullif null String input - Since:
- 2.1
-
join
Joins the elements of the provided array into a single String containing the provided list of elements.
No separator is added to the joined String. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null) = null StringUtils.join([]) = "" StringUtils.join([null]) = "" StringUtils.join(["a", "b", "c"]) = "abc" StringUtils.join([null, "", "a"]) = "a"
- Parameters:
array- the array of values to join together, may be null- Returns:
- the joined String,
nullif null array input - Since:
- 2.0
-
join
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null, *) = null StringUtils.join([], *) = "" StringUtils.join([null], *) = "" StringUtils.join(["a", "b", "c"], ';') = "a;b;c" StringUtils.join(["a", "b", "c"], null) = "abc" StringUtils.join([null, "", "a"], ';') = ";;a"
- Parameters:
array- the array of values to join together, may be nullseparator- the separator character to use- Returns:
- the joined String,
nullif null array input - Since:
- 2.0
-
join
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list. A
nullseparator is the same as an empty String (""). Null objects or empty strings within the array are represented by empty strings.StringUtils.join(null, *) = null StringUtils.join([], *) = "" StringUtils.join([null], *) = "" StringUtils.join(["a", "b", "c"], "--") = "a--b--c" StringUtils.join(["a", "b", "c"], null) = "abc" StringUtils.join(["a", "b", "c"], "") = "abc" StringUtils.join([null, "", "a"], ',') = ",,a"
- Parameters:
array- the array of values to join together, may be nullseparator- the separator character to use, null treated as ""- Returns:
- the joined String,
nullif null array input
-
join
Joins the elements of the provided
Iteratorinto a single String containing the provided elements.No delimiter is added before or after the list. Null objects or empty strings within the iteration are represented by empty strings.
See the examples here:
join(Object[],char).- Parameters:
iterator- theIteratorof values to join together, may be nullseparator- the separator character to use- Returns:
- the joined String,
nullif null iterator input - Since:
- 2.0
-
join
Joins the elements of the provided
Iteratorinto a single String containing the provided elements.No delimiter is added before or after the list. A
nullseparator is the same as an empty String ("").See the examples here:
join(Object[],String).- Parameters:
iterator- theIteratorof values to join together, may be nullseparator- the separator character to use, null treated as ""- Returns:
- the joined String,
nullif null iterator input
-
defaultString
Returns either the passed in String, or if the String is
null, an empty String ("").StringUtils.defaultString(null) = "" StringUtils.defaultString("") = "" StringUtils.defaultString("bat") = "bat"- Parameters:
str- the String to check, may be null- Returns:
- the passed in String, or the empty String if it
was
null - See Also:
-
defaultString
Returns either the passed in String, or if the String is
null, the value ofdefaultStr.StringUtils.defaultString(null, "NULL") = "NULL" StringUtils.defaultString("", "NULL") = "" StringUtils.defaultString("bat", "NULL") = "bat"- Parameters:
str- the String to check, may be nulldefaultStr- the default String to return if the input isnull, may be null- Returns:
- the passed in String, or the default if it was
null - See Also:
-
defaultIfEmpty
Returns either the passed in String, or if the String is empty or
null, the value ofdefaultStr.StringUtils.defaultIfEmpty(null, "NULL") = "NULL" StringUtils.defaultIfEmpty("", "NULL") = "NULL" StringUtils.defaultIfEmpty("bat", "NULL") = "bat"- Parameters:
str- the String to check, may be nulldefaultStr- the default String to return if the input is empty ("") ornull, may be null- Returns:
- the passed in String, or the default
-
capitalize
Capitalizes a String changing the first letter to title case as per
ACharacter.toTitleCase(char). No other letters are changed.nullinput String returnsnull.StringUtils.capitalize(null) = null StringUtils.capitalize("") = "" StringUtils.capitalize("cat") = "Cat" StringUtils.capitalize("cAt") = "CAt"- Parameters:
str- the String to capitalize, may be null- Returns:
- the capitalized String,
nullif null String input - Since:
- 2.0
-
capitalizeFully
Converts all the whitespace separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.
Whitespace is defined by
Character.isWhitespace(char). Anullinput String returnsnull. Capitalization uses the Unicode title case, normally equivalent to upper case.WordUtils.capitalizeFully(null) = null WordUtils.capitalizeFully("") = "" WordUtils.capitalizeFully("i am FINE") = "I Am Fine"- Parameters:
str- the String to capitalize, may be null- Returns:
- capitalized String,
nullif null String input
-
capitalizeFully
Converts all the delimiter separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.
The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized.
A
nullinput String returnsnull. Capitalization uses the Unicode title case, normally equivalent to upper case.WordUtils.capitalizeFully(null, *) = null WordUtils.capitalizeFully("", *) = "" WordUtils.capitalizeFully(*, null) = * WordUtils.capitalizeFully(*, new char[0]) = * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"- Parameters:
str- the String to capitalize, may be nulldelimiters- set of characters to determine capitalization, null means whitespace- Returns:
- capitalized String,
nullif null String input - Since:
- 2.1
-
capitalize
Capitalizes all the delimiter separated words in a String. Only the first letter of each word is changed. To convert the rest of each word to lowercase at the same time, use
capitalizeFully(String, char[]).The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized.
A
nullinput String returnsnull. Capitalization uses the Unicode title case, normally equivalent to upper case.WordUtils.capitalize(null, *) = null WordUtils.capitalize("", *) = "" WordUtils.capitalize(*, new char[0]) = * WordUtils.capitalize("i am fine", null) = "I Am Fine" WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"- Parameters:
str- the String to capitalize, may be nulldelimiters- set of characters to determine capitalization, null means whitespace- Returns:
- capitalized String,
nullif null String input - Since:
- 2.1
- See Also:
-
containsNewline
contains newline since JSP cant have a quoted newlines- Parameters:
string-- Returns:
- newline
-
contains
Checks if String contains a search character, handling
null. This method usesString.indexOf(int).A
nullor empty ("") String will returnfalse.StringUtils.contains(null, *) = false StringUtils.contains("", *) = false StringUtils.contains("abc", 'a') = true StringUtils.contains("abc", 'z') = false- Parameters:
str- the String to check, may be nullsearchChar- the character to find- Returns:
- true if the String contains the search character,
false if not or
nullstring input - Since:
- 2.0
-
contains
Checks if String contains a search String, handling
null. This method usesString.indexOf(int).A
nullString will returnfalse.StringUtils.contains(null, *) = false StringUtils.contains(*, null) = false StringUtils.contains("", "") = true StringUtils.contains("abc", "") = true StringUtils.contains("abc", "a") = true StringUtils.contains("abc", "z") = false- Parameters:
str- the String to check, may be nullsearchStr- the String to find, may be null- Returns:
- true if the String contains the search String,
false if not or
nullstring input - Since:
- 2.0
-
equalsIgnoreCaseObject
Compares two objects for equality, where either one or both objects may be
null.ObjectUtils.equals(null, null) = true ObjectUtils.equals(null, "") = false ObjectUtils.equals("", null) = false ObjectUtils.equals("", "") = true ObjectUtils.equals(Boolean.TRUE, null) = false ObjectUtils.equals(Boolean.TRUE, "true") = false ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false- Parameters:
object1- the first object, may benullobject2- the second object, may benull- Returns:
trueif the values of both objects are the same
-
equals
Compares two objects for equality, where either one or both objects may be
null.ObjectUtils.equals(null, null) = true ObjectUtils.equals(null, "") = false ObjectUtils.equals("", null) = false ObjectUtils.equals("", "") = true ObjectUtils.equals(Boolean.TRUE, null) = false ObjectUtils.equals(Boolean.TRUE, "true") = false ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false- Parameters:
object1- the first object, may benullobject2- the second object, may benull- Returns:
trueif the values of both objects are the same
-
equalsSet
see if two sets are deep equals using the equals() method on each item- Parameters:
set1-set2-- Returns:
- if lists are equal or empty
-
equalsCollectionStringLong
public static boolean equalsCollectionStringLong(Collection<?> collection1, Collection<?> collection2) see if two collections are deep equals based on strings or longs (or conversions)- Parameters:
collection1-collection2-- Returns:
- if lists are equal or empty
-
equalsLong
see if two objects long value is the same- Parameters:
thisValue-thatValue-- Returns:
- if equal
-
equalsString
see if two strings are equal (or the strings they convert into)- Parameters:
thisValue-thatValue-- Returns:
- true if equal
-
equalsList
see if two lists are deep equals using the equals() method on each item- Parameters:
list1-list2-- Returns:
- if lists are equal
-
getFullStackTraceHtml
A way to get the entire nested stack-trace of an throwable.
- Parameters:
throwable- theThrowableto be examined- Returns:
- the nested stack trace, with the root cause first
- Since:
- 2.0
-
getFullStackTrace
A way to get the entire nested stack-trace of an throwable.
- Parameters:
throwable- theThrowableto be examined- Returns:
- the nested stack trace, with the root cause first
- Since:
- 2.0
-
substituteVariableMapPrint
print out a variable map as java to try to debug whats going on- Parameters:
variableMap-
-
substituteExpressionLanguage
public static String substituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap) substitute an EL for objects- Parameters:
stringToParse-variableMap-- Returns:
- the string
-
substituteExpressionLanguage
@Deprecated public static String substituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses) Deprecated.substitute an EL for objects- Parameters:
stringToParse-variableMap-allowStaticClasses- if true allow static classes not registered with context- Returns:
- the string
-
substituteExpressionLanguage
public static String substituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent) substitute an EL for objects- Parameters:
stringToParse-variableMap-allowStaticClasses- if true allow static classes not registered with contextsilent- if silent mode, swallow exceptions (warn), and dont warn when variable not found- Returns:
- the string
-
substituteExpressionLanguage
public static String substituteExpressionLanguage(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) substitute an EL for objects- Parameters:
stringToParse-variableMap-allowStaticClasses- if true allow static classes not registered with contextsilent- if silent mode, swallow exceptions (warn), and dont warn when variable not foundlenient- false if undefined variables should throw an exception. if lenient is true (default) then undefined variables are null- Returns:
- the string
-
substituteExpressionLanguageScriptsNotExpressions
public static String substituteExpressionLanguageScriptsNotExpressions(String stringToParse, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) Template-mode substitution where each ${...} block is evaluated as a JEXL script (multi-statement, supports `var` declarations, can return a non-string value) rather than a single expression. Literal text outside ${...} passes through verbatim, same assubstituteExpressionLanguage(java.lang.String, java.util.Map<java.lang.String, java.lang.Object>). Use this when a ${...} block needs more than a single expression — e.g.${ var n = grouperUtil.escapeHtml(groupDisplayExtension, true); 'Job loss from ' + n }- Parameters:
stringToParse- template containing zero or more ${...} script blocksvariableMap- variables available to each scriptallowStaticClasses- if true allow static classes not registered with contextsilent- if silent mode, swallow exceptions (warn), and dont warn when variable not foundlenient- false if undefined variables should throw an exception- Returns:
- the substituted string
-
tryMultipleTimes
- Parameters:
times-runnable-
-
substituteExpressionLanguageScript
public static Object substituteExpressionLanguageScript(String script, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) substitute an EL for objects- Parameters:
script-variableMap-allowStaticClasses- if true allow static classes not registered with contextsilent- if silent mode, swallow exceptions (warn), and dont warn when variable not foundlenient- false if undefined variables should throw an exception. if lenient is true (default) then undefined variables are null- Returns:
- the object
-
copy
Copy bytes from anInputStreamto chars on aWriterusing the default character encoding of the platform.This method buffers the input internally, so there is no need to use a
BufferedInputStream.This method uses
InputStreamReader.- Parameters:
input- theInputStreamto read fromoutput- theWriterto write to- Throws:
NullPointerException- if the input or output is nullIOException- if an I/O error occurs- Since:
- Commons IO 1.1
-
jarFile
get a jar file from a sample class- Parameters:
sampleClass-printError- if error should be printed when there is a problem- Returns:
- the jar file
-
stripLastSlashIfExists
strip the last slash (/ or \) from a string if it exists- Parameters:
input-- Returns:
- input - the last / or \
-
stripLastCommaOrSemiIfExists
strip the last comma or semi from a string if it exists- Parameters:
input-- Returns:
- input - the last , or ;
-
stripFirstSlashIfExists
strip the first slash (/ or \) from a string if it exists- Parameters:
input-- Returns:
- input - the last / or \
-
retrievePasswordFromStdin
retrieve a password from stdin- Parameters:
dontMask-prompt- to print to user- Returns:
- the password
-
retrievePasswordFromStdin
public static final char[] retrievePasswordFromStdin(InputStream in, String prompt) throws IOException - Parameters:
in- stream to be used (e.g. System.in)prompt- The prompt to display to the user.- Returns:
- The password as entered by the user.
- Throws:
IOException
-
stripStart
Strips any of a set of characters from the start of a String.
A
nullinput String returnsnull. An empty string ("") input returns the empty string.If the stripChars String is
null, whitespace is stripped as defined byCharacter.isWhitespace(char).StringUtils.stripStart(null, *) = null StringUtils.stripStart("", *) = "" StringUtils.stripStart("abc", "") = "abc" StringUtils.stripStart("abc", null) = "abc" StringUtils.stripStart(" abc", null) = "abc" StringUtils.stripStart("abc ", null) = "abc " StringUtils.stripStart(" abc ", null) = "abc " StringUtils.stripStart("yxabc ", "xyz") = "abc "- Parameters:
str- the String to remove characters from, may be nullstripChars- the characters to remove, null treated as whitespace- Returns:
- the stripped String,
nullif null String input
-
stripEnd
Deprecated.use stripSuffix insteadStrips any of a set of characters from the end of a String.
A
nullinput String returnsnull. An empty string ("") input returns the empty string.If the stripChars String is
null, whitespace is stripped as defined byCharacter.isWhitespace(char).StringUtils.stripEnd(null, *) = null StringUtils.stripEnd("", *) = "" StringUtils.stripEnd("abc", "") = "abc" StringUtils.stripEnd("abc", null) = "abc" StringUtils.stripEnd(" abc", null) = " abc" StringUtils.stripEnd("abc ", null) = "abc" StringUtils.stripEnd(" abc ", null) = " abc" StringUtils.stripEnd(" abcyx", "xyz") = " abc"- Parameters:
str- the String to remove characters from, may be nullstripChars- the characters to remove, null treated as whitespace- Returns:
- the stripped String,
nullif null String input
-
repeat
Repeat a String
repeattimes to form a new String.StringUtils.repeat(null, 2) = null StringUtils.repeat("", 0) = "" StringUtils.repeat("", 2) = "" StringUtils.repeat("a", 3) = "aaa" StringUtils.repeat("ab", 2) = "abab" StringUtils.repeat("a", -2) = ""- Parameters:
str- the String to repeat, may be nullrepeat- number of times to repeat str, negative treated as zero- Returns:
- a new String consisting of the original String repeated,
nullif null String input
-
rightPad
Right pad a String with spaces (' ').
The String is padded to the size of
size.StringUtils.rightPad(null, *) = null StringUtils.rightPad("", 3) = " " StringUtils.rightPad("bat", 3) = "bat" StringUtils.rightPad("bat", 5) = "bat " StringUtils.rightPad("bat", 1) = "bat" StringUtils.rightPad("bat", -1) = "bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad to- Returns:
- right padded String or original String if no padding is necessary,
nullif null String input
-
rightPad
Right pad a String with a specified character.
The String is padded to the size of
size.StringUtils.rightPad(null, *, *) = null StringUtils.rightPad("", 3, 'z') = "zzz" StringUtils.rightPad("bat", 3, 'z') = "bat" StringUtils.rightPad("bat", 5, 'z') = "batzz" StringUtils.rightPad("bat", 1, 'z') = "bat" StringUtils.rightPad("bat", -1, 'z') = "bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad topadChar- the character to pad with- Returns:
- right padded String or original String if no padding is necessary,
nullif null String input - Since:
- 2.0
-
rightPad
Right pad a String with a specified String.
The String is padded to the size of
size.StringUtils.rightPad(null, *, *) = null StringUtils.rightPad("", 3, "z") = "zzz" StringUtils.rightPad("bat", 3, "yz") = "bat" StringUtils.rightPad("bat", 5, "yz") = "batyz" StringUtils.rightPad("bat", 8, "yz") = "batyzyzy" StringUtils.rightPad("bat", 1, "yz") = "bat" StringUtils.rightPad("bat", -1, "yz") = "bat" StringUtils.rightPad("bat", 5, null) = "bat " StringUtils.rightPad("bat", 5, "") = "bat "- Parameters:
str- the String to pad out, may be nullsize- the size to pad topadStr- the String to pad with, null or empty treated as single space- Returns:
- right padded String or original String if no padding is necessary,
nullif null String input
-
leftPad
Left pad a String with spaces (' ').
The String is padded to the size of
size.StringUtils.leftPad(null, *) = null StringUtils.leftPad("", 3) = " " StringUtils.leftPad("bat", 3) = "bat" StringUtils.leftPad("bat", 5) = " bat" StringUtils.leftPad("bat", 1) = "bat" StringUtils.leftPad("bat", -1) = "bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad to- Returns:
- left padded String or original String if no padding is necessary,
nullif null String input
-
leftPad
Left pad a String with a specified character.
Pad to a size of
size.StringUtils.leftPad(null, *, *) = null StringUtils.leftPad("", 3, 'z') = "zzz" StringUtils.leftPad("bat", 3, 'z') = "bat" StringUtils.leftPad("bat", 5, 'z') = "zzbat" StringUtils.leftPad("bat", 1, 'z') = "bat" StringUtils.leftPad("bat", -1, 'z') = "bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad topadChar- the character to pad with- Returns:
- left padded String or original String if no padding is necessary,
nullif null String input - Since:
- 2.0
-
leftPad
Left pad a String with a specified String.
Pad to a size of
size.StringUtils.leftPad(null, *, *) = null StringUtils.leftPad("", 3, "z") = "zzz" StringUtils.leftPad("bat", 3, "yz") = "bat" StringUtils.leftPad("bat", 5, "yz") = "yzbat" StringUtils.leftPad("bat", 8, "yz") = "yzyzybat" StringUtils.leftPad("bat", 1, "yz") = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null) = " bat" StringUtils.leftPad("bat", 5, "") = " bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad topadStr- the String to pad with, null or empty treated as single space- Returns:
- left padded String or original String if no padding is necessary,
nullif null String input
-
substringBefore
Gets the substring before the first occurrence of a separator. The separator is not returned.
A
nullstring input will returnnull. An empty ("") string input will return the empty string. Anullseparator will return the input string.StringUtils.substringBefore(null, *) = null StringUtils.substringBefore("", *) = "" StringUtils.substringBefore("abc", "a") = "" StringUtils.substringBefore("abcba", "b") = "a" StringUtils.substringBefore("abc", "c") = "ab" StringUtils.substringBefore("abc", "d") = "abc" StringUtils.substringBefore("abc", "") = "" StringUtils.substringBefore("abc", null) = "abc"- Parameters:
str- the String to get a substring from, may be nullseparator- the String to search for, may be null- Returns:
- the substring before the first occurrence of the separator,
nullif null String input - Since:
- 2.0
-
substringAfter
Gets the substring after the first occurrence of a separator. The separator is not returned.
A
nullstring input will returnnull. An empty ("") string input will return the empty string. Anullseparator will return the empty string if the input string is notnull.StringUtils.substringAfter(null, *) = null StringUtils.substringAfter("", *) = "" StringUtils.substringAfter(*, null) = "" StringUtils.substringAfter("abc", "a") = "bc" StringUtils.substringAfter("abcba", "b") = "cba" StringUtils.substringAfter("abc", "c") = "" StringUtils.substringAfter("abc", "d") = "" StringUtils.substringAfter("abc", "") = "abc"- Parameters:
str- the String to get a substring from, may be nullseparator- the String to search for, may be null- Returns:
- the substring after the first occurrence of the separator,
nullif null String input - Since:
- 2.0
-
substringBeforeLast
Gets the substring before the last occurrence of a separator. The separator is not returned.
A
nullstring input will returnnull. An empty ("") string input will return the empty string. An empty ornullseparator will return the input string.StringUtils.substringBeforeLast(null, *) = null StringUtils.substringBeforeLast("", *) = "" StringUtils.substringBeforeLast("abcba", "b") = "abc" StringUtils.substringBeforeLast("abc", "c") = "ab" StringUtils.substringBeforeLast("a", "a") = "" StringUtils.substringBeforeLast("a", "z") = "a" StringUtils.substringBeforeLast("a", null) = "a" StringUtils.substringBeforeLast("a", "") = "a"- Parameters:
str- the String to get a substring from, may be nullseparator- the String to search for, may be null- Returns:
- the substring before the last occurrence of the separator,
nullif null String input - Since:
- 2.0
-
substringAfterLast
Gets the substring after the last occurrence of a separator. The separator is not returned.
A
nullstring input will returnnull. An empty ("") string input will return the empty string. An empty ornullseparator will return the empty string if the input string is notnull.StringUtils.substringAfterLast(null, *) = null StringUtils.substringAfterLast("", *) = "" StringUtils.substringAfterLast(*, "") = "" StringUtils.substringAfterLast(*, null) = "" StringUtils.substringAfterLast("abc", "a") = "bc" StringUtils.substringAfterLast("abcba", "b") = "a" StringUtils.substringAfterLast("abc", "c") = "" StringUtils.substringAfterLast("a", "a") = "" StringUtils.substringAfterLast("a", "z") = ""- Parameters:
str- the String to get a substring from, may be nullseparator- the String to search for, may be null- Returns:
- the substring after the last occurrence of the separator,
nullif null String input - Since:
- 2.0
-
waitForInput
public static void waitForInput()wait for input -
retrieveByProperties
public static <T> T retrieveByProperties(Collection<T> collection, List<String> propertyNames, List<Object> propertyValues) find an object (or objects) in a collection based on fields- Type Parameters:
T-- Parameters:
collection-propertyNames-propertyValues-- Returns:
- the object(s) or empty list if cant find
-
retrieveByProperty
public static <T> T retrieveByProperty(Collection<T> collection, String propertyName, Object propertyValue) find an object (or objects) in a collection based on fields- Type Parameters:
T-- Parameters:
collection-propertyName-propertyValue-- Returns:
- the object(s) or empty list if cant find
-
getFirstParentStemOfName
Returns the first existing parent stem of a given name. So if the following stems exist: i2 i2:test And you run getFirstParentStemOfName("i2:test:mystem:mygroup"), you will get back the stem for i2:test. If you run getFirstParentStemOfName("test1:test2"), you will get back the root stem.- Parameters:
name-- Returns:
- Stem
-
retrieveListByProperties
public static <T> List<T> retrieveListByProperties(Collection<T> collection, List<String> propertyNames, List<Object> propertyValues) find an object (or objects) in a collection based on fields- Type Parameters:
T-- Parameters:
collection-propertyNames-propertyValues-- Returns:
- the object(s) or empty list if cant find
-
retrieveListByProperty
public static <T> List<T> retrieveListByProperty(Collection<T> collection, String propertyName, Object propertyValue) find an object (or objects) in a collection based on fields- Type Parameters:
T-- Parameters:
collection-propertyName-propertyValue-- Returns:
- the object(s) or empty list if cant find
-
listPopOne
Return the zero element of the list, if it exists, null if the list is empty. If there is more than one element in the list, an exception is thrown.- Type Parameters:
T-- Parameters:
list- is the container of objects to get the first of.- Returns:
- the first object, null, or exception.
-
setPopOne
Return the zero element of the set, if it exists, null if the list is empty. If there is more than one element in the list, an exception is thrown.- Type Parameters:
T-- Parameters:
set- is the container of objects to get the first of.- Returns:
- the first object, null, or exception.
-
collectionPopOne
Return the zero element of the list, if it exists, null if the list is empty. If there is more than one element in the list, an exception is thrown.- Type Parameters:
T-- Parameters:
collection- is the container of objects to get the first of.exceptionIfMoreThanOne- will throw exception if there is more than one item in list- Returns:
- the first object, null, or exception.
-
xmlEscape
Convert an XML string to HTML to display on the screen- Parameters:
input- is the XML to convertisEscape- true to escape chars, false to unescape- Returns:
- the HTML converted string
-
xmlEscape
Convert an XML string to HTML to display on the screen- Parameters:
input- is the XML to convertisEscape- true to escape chars, false to unescape- Returns:
- the HTML converted string
-
xmlAttribute
- Parameters:
writer-attributeName-attributeValue-
-
substituteStrings
see if the object has string fields with members in them (by memberUuid), and if so, export that member- Parameters:
object-stringSubstituteMap-- Returns:
- if altered or not
-
stringFieldNames
get the list of string field names based on class, and cache this- Parameters:
theClass-- Returns:
- the set of field names
-
appendIfNotBlank
if theString is not blank, apppend it to the result, and if appending,- Parameters:
result- to append to add a prefix and suffix (if not null)theStringOrArrayOrList- is a string, array, list, or set of strings- Returns:
- true if something appended, false if not
-
appendIfNotBlankString
append a string to another string if both not blank, with separator. trim to empty everything
- Parameters:
string-separator-suffix-- Returns:
- the resulting string or blank if nothing
-
appendPrefixIfStringNotBlank
append a prefix to another string if both not blank. trim to empty everything i.e. appendPrefixIfStringNotBlank("[]", " - ", "a") returns [] - a i.e. appendPrefixIfStringNotBlank("", " - ", "a") returns a i.e. appendPrefixIfStringNotBlank("[]", " - ", "") returns "" i.e. appendPrefixIfStringNotBlank("", " - ", "") returns ""- Parameters:
prefix-separator-string-- Returns:
- the resulting string or blank if nothing
-
appendIfNotBlank
public static boolean appendIfNotBlank(StringBuilder result, String prefix, Object theStringOrArrayOrList) if theString is not Blank, apppend it to the result, and if appending, add a prefix (if not null)- Parameters:
result- to append toprefix-theStringOrArrayOrList- is a string, array, list, or set of strings- Returns:
- true if something appended, false if not
-
appendIfNotBlank
public static boolean appendIfNotBlank(StringBuilder result, String prefix, Object theStringOrArrayOrList, String suffix) if theString is not Blank, apppend it to the result, and if appending, add a prefix and suffix (if not null)- Parameters:
result- to append to, assumed to be not nullprefix-theStringOrArrayOrList- is a string, array, list, or set of stringssuffix-- Returns:
- true if anything appended, false if not
-
appendIfNotBlank
public static boolean appendIfNotBlank(StringBuilder result, String prefix, String prefixIfNotBlank, Object theStringOrArrayOrList, String suffix) if theString is not Blank, apppend it to the result, and if appending, add a prefix and suffix (if not null)- Parameters:
result- to append to, assumed to be not nullprefix- prepend this prefix always (when a result not empty). Will be after the other prefixprefixIfNotBlank- prepend this prefix if the result is not emptytheStringOrArrayOrList- is a string, array, list, or set of stringssuffix-- Returns:
- true if anything appended, false if not
-
appendIfNotEmpty
if theString is not empty, apppend it to the result, and if appending,- Parameters:
result- to append to add a prefix and suffix (if not null)theStringOrArrayOrList- is a string, array, list, or set of strings- Returns:
- true if something appended, false if not
-
appendIfNotEmpty
public static boolean appendIfNotEmpty(StringBuilder result, String prefix, Object theStringOrArrayOrList) if theString is not empty, apppend it to the result, and if appending, add a prefix (if not null)- Parameters:
result- to append toprefix-theStringOrArrayOrList- is a string, array, list, or set of strings- Returns:
- true if something appended, false if not
-
appendIfNotEmpty
public static boolean appendIfNotEmpty(StringBuilder result, String prefix, Object theStringOrArrayOrList, String suffix) if theString is not empty, apppend it to the result, and if appending, add a prefix and suffix (if not null)- Parameters:
result- to append to, assumed to be not nullprefix-theStringOrArrayOrList- is a string, array, list, or set of stringssuffix-- Returns:
- true if anything appended, false if not
-
appendIfNotEmpty
public static boolean appendIfNotEmpty(StringBuilder result, String prefix, String prefixIfNotEmpty, Object theStringOrArrayOrList, String suffix) if theString is not empty, apppend it to the result, and if appending, add a prefix and suffix (if not null)- Parameters:
result- to append to, assumed to be not nullprefix- prepend this prefix always (when a result not empty). Will be after the other prefixprefixIfNotEmpty- prepend this prefix if the result is not emptytheStringOrArrayOrList- is a string, array, list, or set of stringssuffix-- Returns:
- true if anything appended, false if not
-
indexOf
Find the index of the given object in the array.
This method returns
-1ifnullarray input.- Parameters:
array- the array to search through for the object, may benullobjectToFind- the object to find, may benull- Returns:
- the index of the object within the array,
-1if not found ornullarray input
-
contains
Checks if the object is in the given array.
The method returns
falseif anullarray is passed in.- Parameters:
array- the array to search throughobjectToFind- the object to find- Returns:
trueif the array contains the object
-
indexOf
Find the index of the given object in the array starting at the given index.
This method returns
-1ifnullarray input.A negative startIndex is treated as zero. A startIndex larger than the array length will return
-1.- Parameters:
array- the array to search through for the object, may benullobjectToFind- the object to find, may benullstartIndex- the index to start searching at- Returns:
- the index of the object within the array starting at the index,
-1if not found ornullarray input
-
arrayPopOne
public static <T> T arrayPopOne(T[] array) Return the zero element of the array, if it exists, null if the array is empty. If there is more than one element in the list, an exception is thrown.- Type Parameters:
T-- Parameters:
array- is the container of objects to get the first of.- Returns:
- the first object, null, or exception.
-
dateToString
convert a date to a string using the standard web service pattern yyyy/MM/dd HH:mm:ss.SSS Note that HH is 0-23- Parameters:
date-- Returns:
- the string, or null if the date is null
-
stringToDate
convert a string to a date using the standard web service pattern Note that HH is 0-23- Parameters:
dateString-- Returns:
- the string, or null if the date was null
-
getMaxLongValue
- Parameters:
values-- Returns:
- the max long in the list of args
-
getMinLongValue
- Parameters:
values-- Returns:
- the min long in the list of args
-
propertiesThreadLocalOverrideMap
override map for properties in thread local to be used in a web server or the like, based on property file name- Parameters:
propertiesFileName-- Returns:
- the override map
-
typeCastStringStringMap
process a string / string map and convert the values to a string/object map.- Parameters:
limitEnvVars- if processing limits, pass in a map of limits. The name is the name of the variable, and the value is the value. Note, you can typecast the values by putting a valid type in parens in front of the param name. e.g. name: (integer)amount, value: 50 (will convert to long) name: (decimal)amount, value: 50.3 (will convert to double) name: (timestamp)amount, value: 2011/01/26 19:02:04 (will convert to date/timestamp)- Returns:
- the map of string to object
-
ipOnNetwork
see if an ip address is on a network- Parameters:
ipString- is the ip address to checknetworkIpString- is the ip address of the networkmask- is the length of the mask (0-32)- Returns:
- boolean
-
ipOnNetworks
see if an ip address is on a network- Parameters:
ipString- is the ip address to checknetworkIpStrings- are the ip addresses of the networks, e.g. 1.2.3.4/12, 2.3.4.5/24, 1.2.3.4- Returns:
- boolean
-
ipReadyForAnd
public static int ipReadyForAnd(int ip, int maskLength) get the ip address after putting 1's where the subnet mask is not- Parameters:
ip- intmaskLength- int- Returns:
- int
-
ipInt
get the ip addres integer from a string ip address- Parameters:
ip- String- Returns:
- int
-
methodsByNameHelper
public static void methodsByNameHelper(Class<?> theClass, String methodName, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation, Set<Method> methodSet) get the set of methods- Parameters:
theClass-methodName-superclassToStopAt-includeSuperclassToStopAt-includeStaticMethods-markerAnnotation-includeAnnotation-methodSet-
-
callMethodWithMoreParams
public static Object callMethodWithMoreParams(Object instance, Class<?> theType, String methodName, Object[] params) call method with more params. e.g. if you are only passing in the first 3 params, of a 6 param method...- Parameters:
instance-theType- of object to call method onmethodName-params-- Returns:
- the result of the method
-
changeToVersion
convert an object from one version to another- Parameters:
input- input objectnewPackage- is the package where the other version of things are- Returns:
- the object in the new version or null if input null or new version not found
-
changeToVersionHelper
convert an object from one version to another- Parameters:
input- input objectnewPackage- is the package where the other version of things aretimeToLive- avoid circular references- Returns:
- the object in the new version or null if input null or new version not found
-
tmpDir
return the temp dir, either what is in the java env var, or something in the grouper conf- Returns:
- the temp dir
-
tmpDir
return the temp dir, either what is in the java env var, or something in the grouper conf- Parameters:
appendSlashIfNotThere- add a slash to end if not there already- Returns:
- the temp dir
-
listFromCollection
null safe convert collection to list- Type Parameters:
T-- Parameters:
collection-- Returns:
- the list
-
retrieveExecutorService
might want to use GrouperCallable with this. Lazy-initialized so that config properties are available. Bounded thread pool with bounded queue and CallerRunsPolicy for backpressure. Up to maxThreads run concurrently, up to queueSize tasks are queued, and if the queue is full the calling thread runs the task itself. Idle threads are terminated after keepAliveSeconds. Configurable via grouper.properties: grouper.executorService.maxThreads (default 100) grouper.executorService.keepAliveSeconds (default 60) grouper.executorService.queueSize (default 10000)- Returns:
- executor service
-
executorServiceSubmit
public static <T> GrouperFuture<T> executorServiceSubmit(ExecutorService executorService, Callable<T> callable) you should probably use the GrouperCallable method, not this one- Parameters:
executorService-callable-- Returns:
- the future
-
executorServiceSubmit
public static GrouperFuture executorServiceSubmit(ExecutorService executorService, GrouperCallable callable, boolean willRetry) - Parameters:
executorService-callable-willRetry-- Returns:
- the future
-
executorServiceSubmit
public static void executorServiceSubmit(ExecutorService executorService, List<GrouperCallable<Void>> callables) - Parameters:
executorService- if null just run it in this threadcallable-willRetry-
-
concat
concat two strings- Parameters:
a-b-- Returns:
- the concatted string
-
concat
concat strings- Parameters:
a-b-c-- Returns:
- the concatted string
-
concat
concat strings- Parameters:
a-b-c-d-- Returns:
- the concatted string
-
concat
concat strings- Parameters:
a-b-c-d-- Returns:
- the concatted string
-
stack
get a couple of lines of stack- Returns:
- the couple of lines of stack
-
stack
get a short stack trace from a throwable, only edu.internet2 lines- Parameters:
throwable-- Returns:
- the couple of lines of stack
-
sortByIds
public static <T extends GrouperId> Set<T> sortByIds(Collection<String> ids, Collection<T> grouperObjects) based on some ids, sort a set of grouper objects by that- Type Parameters:
T-- Parameters:
ids-grouperObjects-- Returns:
- the set of grouper objects
-
getGrouperHome
- Returns:
- grouper home
-
splitFileLines
split a file on whitespace- Parameters:
fileContents-- Returns:
- the list of file lines
-
escapeHtml
Convert an XML string to HTML to display on the screen- Parameters:
input- is the XML to convertisEscape- true to escape chars, false to unescape- Returns:
- the HTML converted string
-
escapeHtml
Convert an XML string to HTML to display on the screen- Parameters:
input- is the XML to convertisEscape- true to escape chars, false to unescapeescapeSingleQuotes- true to escape single quotes too- Returns:
- the HTML converted string
-
fileListRecursive
list files recursively from parent, dont include- Parameters:
parent-- Returns:
- set of files wont return null
-
fileListRecursiveDirs
list dirs recursively from parent, dont include- Parameters:
parent-- Returns:
- set of files wont return null
-
fileDescendantDirsRelativePaths
get the relative paths of descendant files- Parameters:
parentDir-- Returns:
- the relative paths of files underneath, dont start with slash
-
fileDescendantRelativePaths
get the relative paths of descendant files- Parameters:
parentDir-- Returns:
- the relative paths of files underneath, dont start with slash
-
mapAddValue
in a map get a value if there and increment or set a value- Parameters:
map-key-numberToAdd- long
-
mapAddValueObjectKey
in a map get a value if there and increment or set a value- Parameters:
map-key-numberToAdd- long
-
mapAddValue
in a map get a value if there and increment or set a value- Parameters:
map-key-numberToAdd- int
-
mapAddValueObjectKey
in a map get a value if there and increment or set a value- Parameters:
map-key-numberToAdd- int- Returns:
- new count
-
substituteExpressionLanguageTemplate
public static String substituteExpressionLanguageTemplate(String script, Map<String, Object> variableMap, boolean allowStaticClasses, boolean silent, boolean lenient) substitute an EL for objects- Parameters:
stringToParse-variableMap-allowStaticClasses- if true allow static classes not registered with contextsilent- if silent mode, swallow exceptions (warn), and dont warn when variable not foundlenient- false if undefined variables should throw an exception. if lenient is true (default) then undefined variables are null- Returns:
- the object
-
gshReturn
public static void gshReturn(int returnCode) get out of GSH with return code- Parameters:
returnCode-
-
gshReturn
public static void gshReturn()get out of gsh with normal return code -
portAvailable
Checks to see if a specific port is available.- Parameters:
port- the port to check for availabilityipAddress-- Returns:
- true if available
-
portAvailableWait
public static boolean portAvailableWait(int port, String ipAddress, int seconds, boolean expectingListening) - Parameters:
port-ipAddress-seconds-expectingListening-- Returns:
- success
-
regexGroup
run a regex on a string and return first group or null if not matches. regex must have group in it regexGroup("^fr(u)it$", "fruit") will return "u"- Parameters:
regex-input-- Returns:
- the group
-
isWindows
public static boolean isWindows()see if we are running on windows- Returns:
- true if windows
-
exceptionTruncate
truncate an exception stack to be less than 3.5k- Parameters:
exception- the stack- Returns:
- the stack
-
exceptionWithoutPackages
take out packages and whitespace from stack- Parameters:
exception-- Returns:
- the new stack
-
exceptionWithoutDupes
take out packages and whitespace from stack- Parameters:
exception-- Returns:
- the new stack
-
exceptionWithoutClasses
take out packages and whitespace from stack- Parameters:
exception-- Returns:
- the new stack
-
exception4kZipBase64
take out packages and whitespace from stack- Parameters:
exception-- Returns:
- the new stack
-
zipUnBase64UnGzip
if a string has zips and base 64s (e.g. for stack), then remove- Parameters:
zippedBase64Exception-- Returns:
-
zipGzipCompress
-
zipGzipDecompress
-
zipGzipIsCompressed
public static boolean zipGzipIsCompressed(byte[] compressed) -
jsonJacksonGetBooleanFromJsonPointer
public static Boolean jsonJacksonGetBooleanFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as boolean and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetIntegerFromJsonPointer
public static Integer jsonJacksonGetIntegerFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as integer and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetIntegerFromJsonPointer
public static Integer jsonJacksonGetIntegerFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Integer defaultInteger) get a field as integer and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetLongFromJsonPointer
public static Long jsonJacksonGetLongFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as long and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetLongFromJsonPointer
public static Long jsonJacksonGetLongFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, Long defaultLong) get a field as long and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetNodeFromJsonPointer
public static com.fasterxml.jackson.databind.JsonNode jsonJacksonGetNodeFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as node or array. could return null if not there- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the node or array
-
jsonJacksonGetStringFromJsonPointer
public static String jsonJacksonGetStringFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as string and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetStringFromJsonPointer
public static String jsonJacksonGetStringFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer, String defaultString) get a field as string and handle null- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
jsonJacksonGetStringSetFromJsonPointer
public static Set<String> jsonJacksonGetStringSetFromJsonPointer(com.fasterxml.jackson.databind.JsonNode jsonNode, String jsonPointer) get a field as string set. could return null if not there- Parameters:
jsonNode-jsonPointer- e.g. /a/b- Returns:
- the string
-
stringFormatNameReverseReplaceTruncate
public static String stringFormatNameReverseReplaceTruncate(String name, String newSeparator, int maxLength) assertEquals("c.b.a", edu.internet2.middleware.grouper.util.GrouperUtil.stringFormatNameReverseReplaceTruncate("a:b:c", ".", -1)); assertEquals("c.b.", edu.internet2.middleware.grouper.util.GrouperUtil.stringFormatNameReverseReplaceTruncate("a:b:c", ".", 4));- Parameters:
string-string2-i-- Returns:
- the new string
-
collectionRemoveNulls
-
checkIfMembershipsMayPropagate
- Parameters:
groups-- Returns:
- true if membership adds/deletes in any of the given groups may propagate asynchronously to composites
-
setAppendStringToItems
-
containsConvertType
-
splitTrimCommas
public static List<String> splitTrimCommas(String input, String commaSeparatedAttributes, String regexAllowedChars, String replaceChar) split by commas. only keep specific attribute values. if a regexAllowedChars is specified, then whitelist chars by regex. character to replace (e.g. underscore), default is underscore. if there isnt a value, dont put it in the list- Parameters:
input-commaSeparatedAttributes-regexAllowedChars-replaceChar-- Returns:
- the list of attributes
-
splitTrimCurlyColons
public static List<String> splitTrimCurlyColons(String input, String commaSeparatedAttributes, String regexAllowedChars, String replaceChar) split by curly colons. only keep specific attribute values. if a regexAllowedChars is specified, then whitelist chars by regex. character to replace (e.g. underscore), default is underscore. if there isnt a value, dont put it in the list- Parameters:
input-commaSeparatedAttributes-regexAllowedChars-replaceChar-- Returns:
- the list of attributes
-
toLowerCase
null safe to lower method- Parameters:
input-- Returns:
- lower
-
toUpperCase
null safe to upper method- Parameters:
input-- Returns:
- upper
-