Class DataTools
DataTools is a utility class with the following facilities: getProperties()andsetProperties():getProperties()allow the properties of any Java object to be extracted as a Map, andsetPropertiesallows any Map to be applied to a Java object, calling setter methods named after the keys of the Map. These methods are very useful for going from Java beans to a JavaScript representation and back.- prettyPrint(), which uses a JSTranslater to output a text summary of arbitrary Java objects, very useful for logging
- many utilities for manipulating Java Collections
-
Method Summary
Modifier and TypeMethodDescriptionstatic ListAdds all the elements of anIteratorto aList.static ListAdds the contents of oneListto another.static ListAdd either a single object or List to another List.static voidaddDisjunctionToSet(List one, List two) Adds elements of the secondListthat are missing in the first.static voidaddToIntInMap(Map map, Object key, int addition) Add to the value of an Integer instance stored in the map "map" under key "key".static ListarrayToList(Object[] arr) Creates aListfrom an array.static ListarrayToList(Object[] arr, int from, int length) Creates aListcontaining a subset of an array.static <T> T[]arrayUnion(T[] one, T[] two) Creates a new array containing all the elements of two arrays.static StringReturns the hash of the passed-in string, encrypted using the bcrypt algorithmstatic <T> List<T>buildList(T... args) Creates aListcontaining the passed in objectsstatic com.isomorphic.collections.DataTypeMapCreates aMapof key/value pairs.static ObjectcastValue(Object value, Class targetType, DataSource ds) Converts specifiedvaluetotargetType.static intObtains the size of aMap,ListorString.static ObjectcombineAsLists(Object one, Object two) Combine two single objects or Lists into one new List, or return a single Object if one argument is single and the other argument is null.static booleanTests if the specified substring is present in the specified string.static ObjectMerges one collections data structure into another.static voidWalks a nested Collection-based datastructure and removes all Collections entities that are zero-sized.static voiddeepRemoveKey(Object keyToRemove, Object data) Walks a nested Collection-based datastructure and removes all instances of keyToRemove (and its associated value) from any Map objects found in the data structure.static voiddeepRemoveNullValues(Object data) Walks a nested Collection-based datastructure and removes all entities that have a null value.static MapAlters aMapso that it retains only the specified keys, returning aMapwith any keys not retained.static ListConverts anIteratorto aList.static StringfastDateFormat(Date date) Returns aStringrepresentation of aDateobject.static MapGiven a List of Maps, return the first Map that has a certain value for a keystatic ListGiven a List of Maps, return all Maps that have a certain value for a key.static ListGiven a List of Maps, return all Maps that have common key/value pairs with another Map.static StringformatDate(String format, Date date) Returns the parameter date formatted according to the parameter format string.static ClassgetCachedClass(String className) Returns loadedClassobject for specified name.static Field[]Returns array of all fields declared in specified class and it's supper classes.static Method[]Returns array of all methods declared in specified class and it's supper classes.static intgetIntInMap(Map map, Object key) Get value of an Integer instance stored in the map "map" under key "key", as the primitive typeint.static ObjectReturns log4j2LoggerContextinstance that was configured fromlog4j2.isc.config.xml.static ObjectDeprecated.static MapgetProperties(Object bean) Gets the properties for a JavaBean and returns them as aMap.static ListgetProperty(List rows, Object column) Given a result set, as aListof rows, and a column name, returns theListof values for that column.static Map<String,PropertyDescriptor> getPropertyDescriptors(Class beanClass) Gets the properties for a JavaBean class through introspection and returns them as aMap.static Map<String,PropertyDescriptor> getPropertyDescriptors(Object bean) Gets the property descriptors for a JavaBean and returns them as aMap.static ClassgetPropertyType(Class c, String propertyName) Returns type of specified property in provided class.static ClassgetRealClass(Object bean) Checks if provided bean is a proxy and extracts real class.static ObjectRetrieves the element of a single elementList, or the key of a single key/value pairMap.static StringReturns the stack trace of aThrowableobject as aString.static StringgetStackTrace(Throwable t, int lineCount) Returns the stack trace of aThrowableobject as aStringshortened to requested number of lines.static StringgetterName(Method method) Tests if method is getter and returns property name.static StringReturns the hash of the passed-in string, encrypted using the MD5 algorithmstatic StringReturns the hash of the passed-in string, encrypted using the specified algorithmstatic MapidentityMap(List list) Stores the elements of aListas the keys and values of aMap.static voidincrementIntInMap(Map map, Object key) Add to the value of an Integer instance stored in the map "map" under key "key".static booleanisNumberType(Class clazz) Returnstrueif provided class is either assignable toNumberor represents one of primitive number typesbyte, short, int, long, float, double.static booleanisTextType(Class clazz) Returnstrueif provided class is either assignable toCharacteror assignable toStringor represents primitivechartype.static org.apache.commons.jxpath.JXPathContextjxPathContext(Object obj) Returns JXPathContext in lenient modestatic ListkeysAsList(Map map) Creates aListof the keys from aMap.static ListkeysNotPresent(Map map, List keys) Given aMapand aListof keys, returns the list of keys in theListthat are not present in theMap.static Object[]listToArray(List list) Creates anObjectarray from aList.static String[]listToStringArray(Collection list) Creates aStringarray from aList.static ListCreates aListcontaining one element.static ListmakeListIfSingle(Object obj) Creates aListcontaining one element if the element is not aList.static MapmapDisjunction(Map one, Map two) Creates a newMapcontaining the key/value pairs whose keys are not present in bothMapssupplied.static MapmapIntersection(Map primary, Map secondary) Constructs aMapcontaining the key/value pairs of the primaryMapwhose keys are present in the secondaryMap.static ListmapIntersectionKeys(Map one, Map two) Returns the list of keys that are present in bothMaps.static MapCopies the key/value pairs of aMapinto anotherMap, replacing the key/value pair of the targetMap.static MapmapMergeNonNull(Map source, Map target) Copies the key/value pairs of aMapinto anotherMap, replacing the key/value pair of the targetMapif the source value is non-null.static PropertiesmapToProperties(Map map) Creates aPropertiesobject from aMap.static MapConstructs aMapcontaining all the key/value pairs of theMapssupplied as arguments, with the firstMaptaking precedence.static StringDeprecated.static ObjectRetrieves a object from a series of nestedListsorMap.static LinkedHashMaporderedMapUnion(Map primary, Map secondary) Does the same asmapUnion, but keeps order of key/value pairs.static StringprettyPrint(Object obj) Formats information about anObjectfor viewing or printing as aString.static MapputAllNotPresent(Map target, Map source) Copies the key/value pairs of aMapinto anotherMap, adding only key/value pairs for which the targetMapdoes not already have a mapping (as determined by thecontainsKeymethod).static MapputCombinedList(Map map, Object key, Object value) Put a value into a Map, combining with any existing value as though combineAsLists() had been called on the existing value and new value.static MapputMultiple(Map map, Object key, Object value) Puts a key/value pair into aMap, if there is already a value under that key, create aListto hold the values.static MapputMultipleAsList(Map map, Object key, Object value) Works like theputMultiplemethod, but in this case values are always encapsualted in aList.static booleanrecursiveFileDelete(File file) Recursively deletes a directory.static voidregisterTransformer(Class targetType, com.isomorphic.util.DataTools.Transformer transformer) Register a Transformer.static MapChange the keys used in aMapto a new set of keys.static MapChange the keys used in aMapto a new set of keys.static ListRemap the keys in aListofMaps.static ListRemap the keys in aListofMaps.static MapRemoves all keys from the passed-inmapwhere the values are empty strings.static MapremoveNullValuedKeys(Map map) Removes all keys from the passed-inmapwhere the values arenull.static MapreverseMap(Map origMap) Reverses aMapso that values point at keys.static ListsetDisjunction(Collection one, Collection two) Creates a newListcontaining all elements from the firstCollectionthat are not in the secondCollection.static <T> List<T>setIntersection(Collection<T> one, Collection<T> two) Creates a newListcontaining the common elements of twoCollections.static ObjectsetProperties(Map propertyMap, Object bean) As the three-argument version of this method, but passes a null dataSourcestatic ObjectsetProperties(Map propertyMap, Object bean, DataSource dataSource) Sets the properties for a JavaBean provided as key-value pairs in aMap.static ObjectsetProperties(Map propertyMap, Object bean, DataSource dataSource, DSRequest dsRequest) This version of setProperties accepts a DSRequest for use as context by the conversion process.static <T> List<T>Creates a newListcontaining all the elements of twoLists.static StringDeprecated.Please usesha256(java.lang.String)orsha512(java.lang.String)instead to generate a secure hash, as SHA-1 is vulnerable to attackers creating collisions with current technology.static StringReturns the hash of the passed-in string, encrypted using the SHA-256 algorithmstatic StringReturns the hash of the passed-in string, encrypted using the SHA-512 algorithmstatic ListsubsetByPrefix(List list, String prefix) Returns any strings withinlistwhich begin withprefix.static MapGiven aMapand aListof keys, returns a subset of theMapcontaining the key/value pairs as specified by theListof keys.static MapsubstringKeyMap(String prefix, Map source) Constructs aMapof key/value pairs from the sourceMapwhose keys start with a specific prefix.static ListtoLowerCaseList(List list) Given aListof strings, returns a newListof lower cased strings.
-
Method Details
-
keysNotPresent
Given aMapand aListof keys, returns the list of keys in theListthat are not present in theMap.- Parameters:
map- theMapkeys- theListof keys- Returns:
- the list of keys in the supplied
Listthat are not present in theMap
-
subsetMap
Given aMapand aListof keys, returns a subset of theMapcontaining the key/value pairs as specified by theListof keys.- Parameters:
origMap- the originalMapkeys- the keys denoting the key/value pairs that should be included in the resultMap- Returns:
- the subset of the original
Mapcontaining only the key/value pairs corresponding to the suppliedListof keys
-
subsetByPrefix
Returns any strings withinlistwhich begin withprefix. Non-string members oflistare ignored.- Parameters:
list- the list of stringsprefix- strings in the list with this prefix will be returned- Returns:
- a list of the strings in the supplied list that begin with the specified prefix
-
removeNullValuedKeys
Removes all keys from the passed-inmapwhere the values arenull.- Parameters:
map- theMapon which to operate
-
removeEmptyStringValuedKeys
Removes all keys from the passed-inmapwhere the values are empty strings.- Parameters:
map- theMapon which to operate
-
divideMap
Alters aMapso that it retains only the specified keys, returning aMapwith any keys not retained.- Parameters:
origMap- the originalMapretainKeys- theListof keys corresponding to the key/value pairs that should be retained- Returns:
- a
Mapcontaining the key/value pairs that were not retained
-
mapUnion
Constructs aMapcontaining all the key/value pairs of theMapssupplied as arguments, with the firstMaptaking precedence. If the same key is present in bothMaps, the returnedMapwill contain the key/value pair of the firstMap.- Parameters:
primary- the firstMapsecondary- the secondMap- Returns:
- the union of the two
Maps
-
orderedMapUnion
Does the same asmapUnion, but keeps order of key/value pairs. Key/value pairs of primaryMapwill go first, then key/value pairs from secondaryMapignoring dublicates. Consider usingLinkedHashMapfor primary and secondary maps to get full value from this method.- Parameters:
primary- the firstMapsecondary- the secondMap- Returns:
- the union of the two
Maps
-
deepMerge
Merges one collections data structure into another. Any nodes/items not present in the target get created. Those that are present are merged. Note that the initial source and target must be of the same type and their data must not contain conflicting types.- Parameters:
source- theObjectto be copied fromtarget- theObjectto be copied intooverwrite- controls how non-collection/non-map collisions are resolved. If true, target values are overwritten with source values. If false, target values are not overwritten.- Returns:
- the merged
Object - Throws:
Exception
-
deepRemoveKey
Walks a nested Collection-based datastructure and removes all instances of keyToRemove (and its associated value) from any Map objects found in the data structure.- Parameters:
keyToRemove- the key to removedata- the nested data structure to walk- Throws:
Exception
-
deepRemoveNullValues
Walks a nested Collection-based datastructure and removes all entities that have a null value. For Maps this means the removal of keys with a value of null, for Collections this means the removel of null elements.- Parameters:
data- the nested data structure to walk- Throws:
Exception
-
deepRemoveEmptyCollections
Walks a nested Collection-based datastructure and removes all Collections entities that are zero-sized.- Parameters:
data- the nested data structure to walk- Throws:
Exception
-
mapMerge
Copies the key/value pairs of aMapinto anotherMap, replacing the key/value pair of the targetMap.- Parameters:
source- theMapto be copied fromtarget- theMapto be copied into- Returns:
- the merged
Map
-
mapMergeNonNull
Copies the key/value pairs of aMapinto anotherMap, replacing the key/value pair of the targetMapif the source value is non-null.- Parameters:
source- theMapto be copied fromtarget- theMapto be copied into- Returns:
- the merged
Map
-
putAllNotPresent
Copies the key/value pairs of aMapinto anotherMap, adding only key/value pairs for which the targetMapdoes not already have a mapping (as determined by thecontainsKeymethod).- Parameters:
source- theMapto be copied fromtarget- theMapto be copied into- Returns:
- the merged
Map
-
mapIntersection
Constructs aMapcontaining the key/value pairs of the primaryMapwhose keys are present in the secondaryMap.- Parameters:
primary- the primaryMapsecondary- the secondaryMap- Returns:
- the intersection of the two
Map
-
mapIntersectionKeys
Returns the list of keys that are present in bothMaps.- Parameters:
one- the firstMaptwo- the secondMap- Returns:
- the list of keys that is the intersection of the
Maps
-
substringKeyMap
Constructs aMapof key/value pairs from the sourceMapwhose keys start with a specific prefix. The newMap's keys are the origin keys without the prefix.- Parameters:
prefix- the prefix to be matched with the keyssource- the sourceMap- Returns:
- the new
Map
-
identityMap
Stores the elements of aListas the keys and values of aMap. This can serve as aHashSetwhich disallows duplicates and can quickly determine whether a set has a given member.- Parameters:
list- theListto be stored- Returns:
- the
Mapcontaining the uniques elements of the list
-
reverseMap
Reverses aMapso that values point at keys. If more than one value in the originalMaphas the same key (where "same" is determined byhashcode), the multiple keys are placed into aListin the reversedMap.Note: If in the original
Map,Listsare mapped to values, and more than oneListmaps to the same value, this method will work incorrectly since it won't be able to tellListsit created for multiple values fromListsthat were keys in the originalMap.- Parameters:
origMap- the originalMap- Returns:
- the reversed
Map
-
putMultiple
Puts a key/value pair into aMap, if there is already a value under that key, create aListto hold the values.- Parameters:
map- theMapto which the key/value pair should be addedkey- the key in the key/value pairvalue- the value in the key/value pair- Returns:
- the
Map, with the key/value pair added to it
-
putMultipleAsList
Works like theputMultiplemethod, but in this case values are always encapsualted in aList.- Parameters:
map- theMapto which the key/value pair should be addedkey- the key in the key/value pairvalue- the value in the key/value pair- Returns:
- the
Map, with the key/value pair added to it
-
addAll
Adds the contents of oneListto another.- Parameters:
target- theListto which the contents of the sourceListshould be addedsource- theListto be added to the targetList- Returns:
- the combined
List
-
addAll
Adds all the elements of anIteratorto aList.- Parameters:
target- theListto which the contents of the sourceListshould be addedsource- theListto be added to the targetList- Returns:
- the combined
List
-
addAsList
Add either a single object or List to another List. IfsourceListis a List, adds its items, if it's an Object, just adds the Object itself. Returns the modifiedtargetList. -
combineAsLists
Combine two single objects or Lists into one new List, or return a single Object if one argument is single and the other argument is null. -
putCombinedList
Put a value into a Map, combining with any existing value as though combineAsLists() had been called on the existing value and new value. -
setUnion
Creates a newListcontaining all the elements of twoLists.- Parameters:
one- the firstListtwo- the secondList- Returns:
- the combined
List
-
addDisjunctionToSet
Adds elements of the secondListthat are missing in the first. If the first or secondListisnull, the first will be unchanged.- Parameters:
one- the firstListtwo- the secondList
-
arrayUnion
public static <T> T[] arrayUnion(T[] one, T[] two) Creates a new array containing all the elements of two arrays.- Parameters:
one- the first arraytwo- the second array- Returns:
- the combined array
-
setIntersection
Creates a newListcontaining the common elements of twoCollections.- Parameters:
one- the firstCollectiontwo- the secondCollection- Returns:
- the common elements
-
mapDisjunction
Creates a newMapcontaining the key/value pairs whose keys are not present in bothMapssupplied.- Parameters:
one- the firstMaptwo- the secondMap- Returns:
- the
Mapof the disjunction
-
setDisjunction
Creates a newListcontaining all elements from the firstCollectionthat are not in the secondCollection.- Parameters:
one- the firstCollectiontwo- the secondCollection- Returns:
- the
Listof elements present in the firstListthat are not in the secondList
-
enumToList
Converts anIteratorto aList.- Parameters:
i- theIterator- Returns:
- the
ListofIteratorelements
-
arrayToList
Creates aListcontaining a subset of an array.- Parameters:
arr- the source arrayfrom- the array index of the first element of the subsetlength- the number of elements in the subset- Returns:
- the
Listof elements from the subset of the source array
-
arrayToList
Creates aListfrom an array.- Parameters:
arr- the source array- Returns:
- the
Listof elements from the source array
-
listToArray
Creates anObjectarray from aList.- Parameters:
list- the sourceList- Returns:
- the
Objectarray containing the elements of the source list
-
listToStringArray
Creates aStringarray from aList.- Parameters:
list- the sourceList- Returns:
- the array of
Stringsfrom the sourceList
-
mapToProperties
Creates aPropertiesobject from aMap. The keys and values in the map must be strings.- Parameters:
map- the sourceMap- Returns:
- the
Propertiesobject containing the keys/values of the sourceMapas properties
-
keysAsList
Creates aListof the keys from aMap.- Parameters:
map- the sourceMap- Returns:
- the list of keys from the source
Map
-
makeList
Creates aListcontaining one element.- Parameters:
element- the element- Returns:
- the
Listcontaining the element
-
makeListIfSingle
Creates aListcontaining one element if the element is not aList.- Parameters:
obj- the element- Returns:
- the
List
-
contains
Tests if the specified substring is present in the specified string.- Parameters:
str- the enclosing stringsubstr- the substring- Returns:
trueif the substring is contained in the string,falseotherwise
-
jxPathContext
Returns JXPathContext in lenient mode- Parameters:
obj- the context bean- Returns:
- JXPathContext instance
-
nestedGet
Retrieves a object from a series of nestedListsorMap. The location of the structure is described by a string ofMapkeys orListindexes, separated by periods.For example, specifying the string
"dog.2"would retrieve the object with key"dog"from the suppliedMap; this object should be aList- the second element of thisListwould be retrieved and returned.- Parameters:
struct- the enclosingListorMapfetch- the string describing the location of the desired object- Returns:
- the desired object
- Throws:
ClassCastException- if any of the enclosing data structures is neither aMapnor aList
-
buildList
Creates aListcontaining the passed in objects- Parameters:
args- any number of arguments of Objects to add to the returned list- Returns:
- the
Listcontaining the passed in args
-
buildMap
Creates aMapof key/value pairs.- Parameters:
args- any (even) number of arguments - key then value then key then value etc.- Returns:
- the
Mapcontaining the five key/value pairs
-
getSingle
Retrieves the element of a single elementList, or the key of a single key/value pairMap. Returnsnullif thetoFetchFromargument is not aListorMap, or iftoFetchFromdoes not contain a single element.- Parameters:
toFetchFrom- the sourceListorMap- Returns:
- the single element or key
-
checkSize
Obtains the size of aMap,ListorString.- Parameters:
obj- theMap,ListorString- Returns:
- the size of the
Map,ListorString, as anintor0if the object is of another class
-
fastDateFormat
Returns aStringrepresentation of aDateobject. This method is faster than using theSimpleDateFormatmethods.- Parameters:
date- the date to be formatted- Returns:
- the formatted date as a
String
-
getStackTrace
Returns the stack trace of aThrowableobject as aStringshortened to requested number of lines.- Parameters:
t- theThrowableobjectlineCount- number of lines to keep in stack traceString- Returns:
- the stack trace for
tas aString
-
getStackTrace
Returns the stack trace of aThrowableobject as aString.- Parameters:
t- theThrowableobject- Returns:
- the stack trace for
tas aString
-
remapRow
Change the keys used in aMapto a new set of keys. Given an existingMapand a mapping from old keys to new keys, create a newMapthat uses the new keys.- Parameters:
row- the row, aMapremap- the map of original to new column nameskeepNonRemapped-booleanindicating whether to keep data under keys that are not remapped- Returns:
- the row with remapped keys, or the original row, if
remapisnull
-
remapRow
Change the keys used in aMapto a new set of keys. Given an existingMapand a mapping from old keys to new keys, create a newMapthat uses the new keys. Columns from the original row that were not remapped will be retained.- Parameters:
row- the row, aMapremap- theMapof original to new column names- Returns:
- the row with remapped keys, or the original row, if
remapisnull
-
remapRows
Remap the keys in aListofMaps.- Parameters:
rows- theListof rowsremap- theMapof original to new column nameskeepNonRemapped-booleanindicating whether to keep data under keys that are not remapped- Returns:
- the result set with remapped columns, or the original
List, ifremapisnull
-
remapRows
Remap the keys in aListofMaps. Columns from the original row that were not remapped will be retained.- Parameters:
rows- theListof rowsremap- theMapof original to new column names- Returns:
- the result set with remapped columns, or the original
List, ifremapisnull
-
getProperty
Given a result set, as aListof rows, and a column name, returns theListof values for that column.The result set is represented as a
ListofMapobjects, with eachMaprepresenting a row of data. The keys and values in each row correspond to the column names and data, respectively.For rows that do not have a value for the specified column, no value will be present in the return list, in other words, an empty object will not be added for that row.
- Parameters:
rows- theListof rowscolumn- the column name or key- Returns:
- the
Listof values forcolumn
-
find
Given a List of Maps, return the first Map that has a certain value for a key- Parameters:
rows- the List of MapspropertyName- the propertyName (key in the Map)value- expected value of the propertyName (may be null)- Returns:
- the first matching Map in the List, or null if no matches
-
findAll
Given a List of Maps, return all Maps that have a certain value for a key.- Parameters:
rows- the List of MapspropertyName- the propertyName (key in the Map)value- expected value of the propertyName (may be null)- Returns:
- a List of matching Maps, or an empty list if no matches
-
findAll
Given a List of Maps, return all Maps that have common key/value pairs with another Map.- Parameters:
rows- the List of Mapsproperties- Map of key/value pairs to match. May not have null values.- Returns:
- a List of matching Maps, or an empty list if no matches
-
toLowerCaseList
Given aListof strings, returns a newListof lower cased strings.- Parameters:
list- theListof strings- Returns:
- the
Listof lower cased strings
-
prettyPrint
Formats information about anObjectfor viewing or printing as aString.- Parameters:
obj- theObjectto be formatted for output- Returns:
- the information
Stringto be used for theObjectin viewing or printing
-
addToIntInMap
Add to the value of an Integer instance stored in the map "map" under key "key".If no Integer is currently stored under "key", creates a new Integer with value 0 before adding to it.
This method exists because of the horrific chain of typecasts otherwise necessary to achieve this effect.
-
incrementIntInMap
Add to the value of an Integer instance stored in the map "map" under key "key".If no Integer is currently stored under "key", creates a new Integer with value 0 before adding to it.
This method exists because of the horrific chain of typecasts otherwise necessary to achieve this effect.
-
getIntInMap
Get value of an Integer instance stored in the map "map" under key "key", as the primitive typeint.Returns 0 if no Integer is currently stored in the Map.
-
getterName
Tests if method is getter and returns property name. Returnsnullif provided method is not getter.- Parameters:
method-MethodGetter to extract property name.- Returns:
StringGetter property name ornullif provided method is not getter.
-
getClassFields
Returns array of all fields declared in specified class and it's supper classes. Array contains fields with all modifiers. Returns empty array if provided parameter isnull.- Parameters:
c-Classto be inspected.- Returns:
Field[]Array of class fields.
-
getClassMethods
Returns array of all methods declared in specified class and it's supper classes. Array contains methods with all modifiers as well as overriden methods from super classes. Returns empty array if provided parameter isnull.- Parameters:
c-Classto be inspected.- Returns:
Method[]Array of class methods.
-
getPropertyType
Returns type of specified property in provided class. Property name can be composed of sub-properties separated by dot for example:- property1 - type of property1 will be returned
- property1.subproperty - type of sub-property will be returned
- Among fields declared in specified class
- Among methods declared in specified class
- Among fields declared in all supper classes
- Among methods declared in all supper classes
ThrowsNullPointerExceptionif either of parameters is null.- Parameters:
c-Classto be inspected.propertyName-StringName of property.- Returns:
ClassType of property.- Throws:
IntrospectionException- when specified class has no such property.
-
getCachedClass
Returns loadedClassobject for specified name. Cached class is returned if exists otherwise class object is loaded and cached. Returnsnullif class can not be loaded (not in class path).- Parameters:
className-Stringqualified class name to load.- Returns:
Classobject ofnullif class can not be loaded (not in class path).
-
getRealClass
Checks if provided bean is a proxy and extracts real class. If bean is not a proxy class then its getClass() is returned. Current implementation checks only for Hibernate proxies. Real class is extracted viarealClass = (Class) ((HibernateProxy) bean).getHibernateLazyInitializer().getPersistentClass();- Parameters:
bean-Object- Returns:
Class
-
getProperties
Gets the properties for a JavaBean and returns them as aMap.- Parameters:
bean- the JavaBean object- Returns:
- the JavaBean properties as a
Map - Throws:
Exception
-
getPropertyDescriptors
Gets the property descriptors for a JavaBean and returns them as aMap.- Parameters:
bean- the JavaBean object- Returns:
- the JavaBean property descriptors as a
Map - Throws:
Exception
-
getPropertyDescriptors
public static Map<String,PropertyDescriptor> getPropertyDescriptors(Class beanClass) throws Exception Gets the properties for a JavaBean class through introspection and returns them as aMap.Removes properties added by byte-code instrumentation:
interceptFieldCallbackproperty is removed if class implementsnet.sf.cglib.transform.impl.InterceptFieldEnabledinterface;fieldHandlerproperty is removed if class implementsorg.hibernate.bytecode.javassist.FieldHandledinterface;
- Parameters:
beanClass- the JavaBean class- Returns:
- the JavaBean class's property descriptors as a
Map - Throws:
Exception
-
setProperties
As the three-argument version of this method, but passes a null dataSource- Parameters:
propertyMap- aMapproviding the key-value pairsbean- the JavaBean object- Returns:
- the JavaBean properties as a
Map - Throws:
IllegalArgumentException- if a value provided in theMapcannot be converted to an appropriate typeException
-
setProperties
public static Object setProperties(Map propertyMap, Object bean, DataSource dataSource) throws Exception Sets the properties for a JavaBean provided as key-value pairs in aMap. This method performs automatic type detection and conversion where possible. Conversion is done via standard bean semantics. Additionally, some standard conversions are performed automatically - for example inbound java.util.Date object will be auto-converted to java.sql.Date or java.sql.Timestamp.Keys for which conversion fails or for which there are no corresponding Bean properties are ignored.
For properties that have primitive value on the target bean (eg properties of
inttype), generally, the static "valueOf(String)" method for the primitive type (eg Boolean.valueOf(String)) will be invoked on the result of "toString()" for the Object being assigned to the primitive property.As special cases the null string ("") and the
nullvalue will become 0 when assigned to numeric primitive types (which cannot be null).If the null string is assigned to a non-primitive numeric type (eg Long), the property will be assigned
null.If the target bean property is an enum, this method attempts to set an appropriate value by use of the enum translate strategy set by calling setEnumTranslateStrategy() on the dataSource, if one is provided. See
DataSource.setEnumTranslateStrategy(String). If there is no DataSource, or it cannot set a value by cleanly using the enumTranslateStrategy, it will attempt to infer a value by considering the incoming value first as a String to match against the enumerated type's value names, and failing that as an integer to match against the enumerated type's values as an ordinal value. If that fails, it sets the target bean property to null.If the target bean property is of Joda-Time type (
org.joda.time.DateTime, DateMidnight, LocalDateTime, LocalDate, LocalTime), then value is passed to the target type constructor takingObjectparameter. See Joda documentation for supported inputs.If the target bean property is of Java 8 Date/Time API type (
java.time.LocalDate, LocalDateTime, LocalTime), it is created withZoneId.systemDefault()forDateinput or attempting<target-type>.parse(input.toString())for everything else.Otherwise, if the type accepted by a setter method on the target bean cannot accept the type of the value in the propertyMap, this method will attempt type conversion by looking for a constructor on the setter method type that accepts instances of the value's type.
Also, if a Map value is found in the values of the passed in propertyMap, and the recipient field on the bean is not a Map, this method will treat the target field as a bean, attempting to create the bean via newInstance() and populating it via a recursive call to this method. In other words, this method will auto-create and populate inner beans.
Similarly if a Collection is found in the propertyMap, it will be applied to a target field of Collection type. If the target field is of an abstract Collection type, the default types used are:
- Map -> LinkedHashMap
- List or Collection -> ArrayList
- Set -> HashSet
- Queue -> LinkedList
will be populated automatically with instances of SomeBean. A DataSource can be optionally passed as the third argument and can modify some of the above behaviors, including choice of concrete type when populating bean properties that declare only an abstract type or base type - See
DataSource.setProperties(Map, Object)for details.- Parameters:
propertyMap- aMapproviding the key-value pairsbean- the JavaBean objectdataSource- a context DataSource, if applicable. Can be null- Returns:
- the JavaBean object
- Throws:
IllegalArgumentException- if a value provided in theMapcannot be converted to an appropriate typeException
-
setProperties
public static Object setProperties(Map propertyMap, Object bean, DataSource dataSource, DSRequest dsRequest) throws Exception This version of setProperties accepts a DSRequest for use as context by the conversion process. In particular, the DSRequest is passed to the getDataSource() method of aDynamicDSGenerator.- Parameters:
propertyMap- aMapproviding the key-value pairsbean- the JavaBean objectdataSource- a context DataSource, if applicabledsRequest- a context DSRequest, if applicable- Returns:
- the JavaBean object
- Throws:
IllegalArgumentException- if a value provided in theMapcannot be converted to an appropriate typeException
-
registerTransformer
public static void registerTransformer(Class targetType, com.isomorphic.util.DataTools.Transformer transformer) Register a Transformer. The Transformer interface specifies a single transform() method. The transform() method must be capable of creating an object of type targetType from the input Object. In a simple case, this could typically be done by making use of Object.toString.- Parameters:
targetType- the Class that this Transformer is capable of transforming totransformer- the Transformer object itself
-
castValue
Converts specifiedvaluetotargetType.
Implemented conversion rules:- Returns
nullif passed value isnull - If passed value can be cast to
targetTypethen same value returned - For primitive types returns appropriate object for example:if
targetTypeisLong.TYPEmethod returnsLong - If
targetTypeisBooleanand passed value is instance ofNumberthen 0 converted tofalse; any other number converted totrue - If
targetTypeisBooleanand passed value is instance ofCharacterthen 'T', 't', 'Y' and 'y' converted totrue; any other character converted tofalse - If
targetTypeisBooleanand passed value is instance ofStringthen "true", "t", "yes" and "y" (ignoring case) converted totrue; any other string converted tofalse - If
targetTypeisByteand passed value is instance ofBooleanthenfalseconverted to 0;trueconverted to 1 - If
targetTypeisByteand passed value is instance ofNumberthen value may be rounded and/or truncated - If
targetTypeisByteand passed value is instance ofStringthen value is parsed withByte.valueOf() - If
targetTypeisShortand passed value is instance ofBooleanthenfalseconverted to 0;trueconverted to 1 - If
targetTypeisShortand passed value is instance ofNumberthen value may be rounded and/or truncated - If
targetTypeisShortand passed value is instance ofStringthen value is parsed withShort.valueOf() - If
targetTypeisIntegerand passed value is instance ofBooleanthenfalseconverted to 0;trueconverted to 1 - If
targetTypeisIntegerand passed value is instance ofNumberthen value may be rounded and/or truncated - If
targetTypeisIntegerand passed value is instance ofCharacterthen caracter value is returned - If
targetTypeisIntegerand passed value is instance ofStringthen value is parsed withInteger.valueOf() - If
targetTypeisLongand passed value is instance ofBooleanthenfalseconverted to 0;trueconverted to 1 - If
targetTypeisLongand passed value is instance ofNumberthen value may be rounded and/or truncated - If
targetTypeisLongand passed value is instance ofCharacterthen caracter value is returned - If
targetTypeisLongand passed value is instance ofStringthen value is parsed withLong.valueOf() - If
targetTypeisLongand passed value is instance ofDatethenDate.getTime()returned - If
targetTypeisFloatand passed value is instance ofBooleanthenfalseconverted to 0;trueconverted to 1 - If
targetTypeisFloatand passed value is instance ofNumberthen value may be rounded and/or truncated - If
targetTypeisFloatand passed value is instance ofCharacterthen caracter value is returned - If
targetTypeisFloatand passed value is instance ofStringthen value is parsed withFloat.valueOf() - If
targetTypeisFloatand passed value is instance ofDatethenDate.getTime()returned - If
targetTypeisDoubleand passed value is instance ofBooleanthenfalseconverted to 0;trueconverted to 1 - If
targetTypeisDoubleand passed value is instance ofNumberthen value may be rounded - If
targetTypeisDoubleand passed value is instance ofCharacterthen caracter value is returned - If
targetTypeisDoubleand passed value is instance ofStringthen value is parsed withDouble.valueOf() - If
targetTypeisDoubleand passed value is instance ofDatethenDate.getTime()returned - If
targetTypeisCharacterand passed value is instance ofBooleanthenfalseconverted to 'f';trueconverted to 't' - If
targetTypeisCharacterand passed value is instance ofNumberthen character for value code returned (value may be rounded and/or truncated) - If
targetTypeisCharacterand passed value is instance ofStringthen returns first string charater;(char) 0returned for empty string - If
targetTypeisStringthenvalue.toString()returned - If
targetTypeisBigIntegerand passed value is instance ofBooleanthenfalseconverted toBigInteger.ZERO;trueconverted toBigInteger.ONE - If
targetTypeisBigIntegerand passed value is instance ofNumberthen value may be rounded - If
targetTypeisBigIntegerand passed value is instance ofCharacterthen caracter value is returned - If
targetTypeisBigIntegerand passed value is instance ofStringthen value is parsed - If
targetTypeisBigIntegerand passed value is instance ofDatethenDate.getTime()returned - If
targetTypeisBigDecimaland passed value is instance ofBooleanthenfalseconverted toBigDecimal.ZERO;trueconverted toBigDecimal.ONE - If
targetTypeisBigDecimaland passed value is instance ofNumberthen value converted toBigDecimal - If
targetTypeisBigDecimaland passed value is instance ofCharacterthen caracter value is returned - If
targetTypeisBigDecimaland passed value is instance ofStringthen value is parsed - If
targetTypeisBigDecimaland passed value is instance ofDatethenDate.getTime()returned - If
targetTypeisjava.util.Dateand passed value is instance ofNumberthenjava.util.Datecreated with value as miliseconds (value may be rounded and/or truncated) - If
targetTypeisjava.util.Dateand passed value is instance ofStringthen value is parsed withDateFormat.getDateTimeInstance() - If
targetTypeisjava.sql.Dateand passed value is instance ofNumberthenjava.sql.Datecreated with value as miliseconds (value may be rounded and/or truncated) - If
targetTypeisjava.sql.Dateand passed value is instance ofStringthen value is parsed withDateFormat.getDateInstance() - If
targetTypeisjava.sql.Dateand passed value is instance ofjava.util.Datethen value is converted - If
targetTypeisjava.sql.Dateand passed value is instance ofjava.sql.Timethen value is converted - If
targetTypeisjava.sql.Dateand passed value is instance ofjava.sql.Timestampthen value is converted - If
targetTypeisjava.sql.Timeand passed value is instance ofNumberthenjava.sql.Timecreated with value as miliseconds (value may be rounded and/or truncated) - If
targetTypeisjava.sql.Timeand passed value is instance ofStringthen value is parsed withDateFormat.getTimeInstance() - If
targetTypeisjava.sql.Timeand passed value is instance ofjava.util.Datethen value is converted - If
targetTypeisjava.sql.Timeand passed value is instance ofjava.sql.Datethen value is converted - If
targetTypeisjava.sql.Timeand passed value is instance ofjava.sql.Timestampthen value is converted - If
targetTypeisjava.sql.Timestampand passed value is instance ofNumberthenjava.sql.Timestampcreated with value as miliseconds (value may be rounded and/or truncated) - If
targetTypeisjava.sql.Timestampand passed value is instance ofStringthen value is parsed withDateFormat.getDateTimeInstance() - If
targetTypeisjava.sql.Timestampand passed value is instance ofjava.util.Datethen value is converted - If
targetTypeisjava.sql.Timestampand passed value is instance ofjava.sql.Datethen value is converted - If
targetTypeisjava.sql.Timestampand passed value is instance ofjava.sql.Timethen value is converted
- Parameters:
value-Objectvalue to be converted.targetType-Classconversion target type.ds-DataSourceinitiating conversion.- Returns:
Objectconverted value.- Throws:
ClassCastException- if value can not be converted or parsing exception occurs.
- Returns
-
isTextType
Returnstrueif provided class is either assignable toCharacteror assignable toStringor represents primitivechartype.- Parameters:
clazz-Classfor testing.- Returns:
booleantrueif specified class represents class for text;false- for all other classes.
-
isNumberType
Returnstrueif provided class is either assignable toNumberor represents one of primitive number typesbyte, short, int, long, float, double.- Parameters:
clazz-Classfor testing.- Returns:
booleantrueif specified class represents class for numbers;false- for all other classes.
-
recursiveFileDelete
Recursively deletes a directory.- Parameters:
file- file or directory to delete- Returns:
- true if successful, false otherwise cannot be converted to an appropriate type
-
md5
Deprecated.Please usesha256(java.lang.String)orsha512(java.lang.String)instead to generate a secure hash, as MD5 is vulnerable to attackers creating collisions with current technology.Returns the hash of the passed-in string, encrypted using the MD5 algorithm- Parameters:
plaintext- the text to encrypt- Returns:
- the encrypted (MD5) hash of the supplied plaintext
- Throws:
Exception
-
sha
Deprecated.Please usesha256(java.lang.String)orsha512(java.lang.String)instead to generate a secure hash, as SHA-1 is vulnerable to attackers creating collisions with current technology.Returns the hash of the passed-in string, encrypted using the SHA-1 algorithm- Parameters:
plaintext- the text to encrypt- Returns:
- the encrypted (SHA) hash of the supplied plaintext
- Throws:
Exception
-
sha256
Returns the hash of the passed-in string, encrypted using the SHA-256 algorithm- Parameters:
plaintext- the text to encrypt- Returns:
- the encrypted (SHA-256) hash of the supplied plaintext
- Throws:
Exception
-
sha512
Returns the hash of the passed-in string, encrypted using the SHA-512 algorithm- Parameters:
plaintext- the text to encrypt- Returns:
- the encrypted (SHA-512) hash of the supplied plaintext
- Throws:
Exception
-
bcrypt
Returns the hash of the passed-in string, encrypted using the bcrypt algorithm- Parameters:
plaintext- the text to encrypt- Returns:
- the encrypted (bcrypt) hash of the supplied plaintext
- Throws:
Exception
-
hashValue
Returns the hash of the passed-in string, encrypted using the MD5 algorithm- Parameters:
plaintext- the text to encrypt- Returns:
- the encrypted (MD5) hash of the supplied plaintext
- Throws:
Exception
-
hashValue
Returns the hash of the passed-in string, encrypted using the specified algorithm- Parameters:
plaintext- the text to encryptalgorithm- the encryption algorithm to use. Search the client-side documentation for "HashAlgorithm" for details.- Returns:
- the encrypted hash of the supplied plaintext
- Throws:
Exception
-
formatDate
Returns the parameter date formatted according to the parameter format string. This method is trivial - it just creates a SimpleDateFormat object and calls its format() method - but it is useful for formatting dates in Velocity expressions- Parameters:
format- A valid SimpleDateFormat format stringdate- The date to format- Returns:
- The date formatted according to the format string
-
getLoggerRepository
Deprecated.Since Log4j 1.x is no longer directly supported, this returns the Log4j2LoggerContextby calling the newgetLoggerContext()API. -
getLoggerContext
Returns log4j2LoggerContextinstance that was configured fromlog4j2.isc.config.xml. Use this method to access log4j2 loggers for custom categories defined in this file.Note: use this method only if log4j2 logging is used.
- Returns:
- log4j2
LoggerContextinstance if configured, otherwisenull.Note:
Objectreturn type is used to avoid unnecessary log4j2 dependency if alternative logging system is used.
-
sha256(java.lang.String)orsha512(java.lang.String)instead to generate a secure hash, as MD5 is vulnerable to attackers creating collisions with current technology.