Class KRADUtils
- Author:
- Kuali Rice Team (rice.collab@kuali.org)
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidaddAttachmentToResponse(javax.servlet.http.HttpServletResponse response, InputStream inputStream, String contentType, String fileName, long fileSize) Adds the header and content of an attachment to the response.static booleanareDifferentDomains(String firstDomain, String secondDomain) Determines whether two URLs point at the same domain.static StringHelper method for building title text for an element and a map of key/value pairs,static StringBuilds a string from the given map by joining each entry with a comma and each key/value pair with a colonstatic StringbuildViewUrl(String baseUrl, String controllerMapping, String viewId) Helper method for building a URL that will invoke the given controller and render the given KRAD viewstatic StringRemoves all query characters from a string.coerceRequestParameterTypes(Class<?> dataObjectClass, Map<String, String> parameters) This method converts request parameters coming in as String to native types in case of Boolean, Number or java.sql.Date.static booleancontainsSensitiveDataPatternMatch(String fieldValue) Check if data might be sensitivestatic PropertiesconvertMapToProperties(Map<String, String> parameters) Utility method to convert a Map to a Properties objectstatic PropertiesconvertRequestMapToProperties(Map<String, String[]> requestParameters) Utility method to convert a Request Parameters Map to a Properties objectconvertStringParameterToList(String parameter) Parses a string that is in list format (commas separating list entries) to a new List instanceconvertStringParameterToMap(String parameter) Parses a string that is in map format (commas separating map entries, colon separates map key/value) to a new map instancestatic StringconvertToHTMLAttributeSafeString(String message) Helper method to change common characters into HTML attribute safe charactersstatic <T> TcreateNewObjectFromClass(Class<T> clazz) This method safely creates a object from a class Convenience method to create new object and throw a runtime exception if it cannot If the class is anExternalizableBusinessObject, this method will determine the interface for the EBO and query the appropriate module service to create a new instance.static ObjectcreateObject(Class<?> clazz, Class<?>[] argumentClasses, Object[] argumentValues) static Class<?> easyGetPropertyType(Object object, String propertyName) LegacyCase - This method simply uses PojoPropertyUtilsBean logic to get the Class of a Class property.static StringgenerateRowCssClassString(Map<String, String> conditionalRowCssClasses, int lineIndex, boolean isOdd, Map<String, Object> lineContext, ExpressionEvaluator expressionEvaluator) Get the rowCss for the line specified, by evaluating the conditionalRowCssClasses map for that rowstatic StringgenerateUniqueViewTitle(UifFormBase form, View view) Attempts to generate a unique view title by combining the View's headerText with the title attribute for the dataObjectClass found through the DataObjectMetaDataService.static StringgetFullURL(javax.servlet.http.HttpServletRequest request) Get the full url for a request (requestURL + queryString)getMapFromParameterString(String parameterString) Parses the given string into a Map by splitting on the comma to get the map entries and within each entry splitting by colon to get the key/value pairsstatic StringgetMessageText(ErrorMessage errorMessage, boolean processPrefixSuffix) Gets the message associated with ErrorMessage object passed in, using message service.getNamespaceAndActionClass(Class<?> clazz) getNamespaceAndComponentFullName(Class<?> clazz) getNamespaceAndComponentSimpleName(Class<?> clazz) static StringgetNamespaceCode(Class<?> clazz) TODO this method will probably need to be exposed in a public KRADUtils class as it is used by several different modules.static StringgetNestedAttributePrefix(String attributeName) Returns the prefix of a nested attribute name, or the empty string if the attribute name is not nested.static StringgetNestedAttributePrimitive(String attributeName) Returns the primitive part of an attribute name string.static ObjectgetNestedValue(Object bo, String fieldName) This method safely extracts either simple values OR nested values.getParametersFromRequest(List<String> parameterNames, Class<?> parentObjectClass, Map<String, String> requestParameters) Retrieves parameter values from the request that match the requested names.getPropertyKeyValuesFromDataObject(List<String> propertyNames, Object dataObject) Returns a map containing a key/value pair for each property given in the property names list, ignoring any values considered to be secure.getPropertyKeyValuesFromDataObject(List<String> propertyNames, List<String> securePropertyNames, Object dataObject) Returns a map containing a key/value pair for each property given in the property names list, ignoring any values considered to be secure, including those insecurePropertyNames.static StringgetRequestStringFromMap(Map<String, String> requestParameters) Generate the request parameter portion of the url based on the map of key value pairs passed instatic StringgetSimpleFieldValue(Object model, Field field) Attempts to extract a string value out of the field passed in, varies depending on field typestatic UserSessiongetUserSessionFromRequest(javax.servlet.http.HttpServletRequest request) Gets the UserSession object from the HttpServletRequest object's associated session.static ObjecthydrateAttributeValue(Class<?> propertyType, String attributeValue) Attempt to coerce a String attribute value to the given propertyType.static booleanThis method is a confirms if object is not null, and unproxies if necessary to determine thisstatic booleanThis method is a confirms if object is null, and unproxies if necessary to determine thisstatic booleanCheck if current deployment is the production environmentstatic booleanDetermines whether a property name should be secured, either based on installed sensitive data patterns, a list of secure property name patterns, or attributes in the Data Dictionary.static booleanDetermines whether a property name should be secured, either based on installed sensitive data patterns, a list of secure property name patterns, or attributes in the Data Dictionary.static StringjoinWithQuotes(List<String> list) Creates a comma separated String representation of the given list.static voidLogs the error messages if any in the message mapstatic Class<?> Attempts to find the Class for the given potentially proxied objectstatic voidmaterializeObjects(Collection<?> possiblyProxiedObjects) This method runs the KRADUtils.isNotNull() method for each item in a list of BOs.static <T> voidsetObjectProperty(Object bo, String propertyName, Class<T> propertyType, T propertyValue) Sets the property of an object with the given value.static voidsetObjectProperty(Object bo, String propertyName, Object propertyValue) Sets the property of an object with the given value.static StringstripXSSPatterns(String value) Strips out common patterns used in cross side scripting.static String[]stripXSSPatterns(String[] values) Strips out common patterns used in cross side scripting.static voidsyncClientSideStateForComponent(Component component, Map<String, Object> clientSideState) Updates the properties of the given component instance with the value found from the corresponding map of client state (if found)translateRequestParameterMap(Map<String, String[]> requestParameters) Translates the given Map of String keys and String array values to a Map of String key and values.static StringTranslates characters in the given string like brackets that will cause problems with binding to characters that do not affect the binding
-
Method Details
-
hydrateAttributeValue
Attempt to coerce a String attribute value to the given propertyType. If the transformation can't be made, either because the propertyType is null or because the transformation required exceeds this method's very small bag of tricks, then null is returned.- Parameters:
propertyType- the Class to coerce the attributeValue toattributeValue- the String value to coerce- Returns:
- an instance of the propertyType class, or null the transformation can't be made.
-
createObject
-
joinWithQuotes
Creates a comma separated String representation of the given list.For example 'a','b',c'.
- Returns:
- the joined String, empty if the list is null or has no elements
-
getNamespaceCode
TODO this method will probably need to be exposed in a public KRADUtils class as it is used by several different modules. That will have to wait until ModuleService and KualiModuleService are moved to core though.- Parameters:
clazz- class to get a namespace code for- Returns:
- namespace code
-
getNamespaceAndComponentSimpleName
-
getNamespaceAndComponentFullName
-
getNamespaceAndActionClass
-
convertStringParameterToMap
Parses a string that is in map format (commas separating map entries, colon separates map key/value) to a new map instance- Parameters:
parameter- - string parameter to parse- Returns:
- Mapinvalid input: '<'String, String> instance populated from string parameter
-
convertStringParameterToList
Parses a string that is in list format (commas separating list entries) to a new List instance- Parameters:
parameter- - string parameter to parse- Returns:
- List<String> instance populated from string parameter
-
translateToMapSafeKey
Translates characters in the given string like brackets that will cause problems with binding to characters that do not affect the binding- Parameters:
key- - string to translate- Returns:
- String translated string
-
buildMapParameterString
Builds a string from the given map by joining each entry with a comma and each key/value pair with a colon- Parameters:
map- - map instance to build string for- Returns:
- String of map entries
-
getMapFromParameterString
Parses the given string into a Map by splitting on the comma to get the map entries and within each entry splitting by colon to get the key/value pairs- Parameters:
parameterString- - string to parse into map- Returns:
- Mapinvalid input: '<'String, String> map from string
-
translateRequestParameterMap
public static Map<String,String> translateRequestParameterMap(Map<String, String[]> requestParameters) Translates the given Map of String keys and String array values to a Map of String key and values. If the String array contains more than one value, the single string is built by joining the values with the vertical bar character- Parameters:
requestParameters- - Map of request parameters to translate- Returns:
- Mapinvalid input: '<'String, String> translated Map
-
getParametersFromRequest
public static Map<String,String> getParametersFromRequest(List<String> parameterNames, Class<?> parentObjectClass, Map<String, String> requestParameters) Retrieves parameter values from the request that match the requested names. In addition, based on the object class an authorization check is performed to determine if the values are secure and should be decrypted. If true, the value is decrypted before returning- Parameters:
parameterNames- - names of the parameters whose values should be retrieved from the requestparentObjectClass- - object class that contains the parameter names as properties and should be consulted for security checksrequestParameters- - all request parameters to pull from- Returns:
- Mapinvalid input: '<'String, String> populated with parameter name/value pairs pulled from the request
-
getPropertyKeyValuesFromDataObject
public static Map<String,String> getPropertyKeyValuesFromDataObject(List<String> propertyNames, Object dataObject) Returns a map containing a key/value pair for each property given in the property names list, ignoring any values considered to be secure.- Parameters:
propertyNames- the list of property names for which to get key/value pairsdataObject- the object instance containing the properties for which the values will be pulled- Returns:
- a map containing an entry for each property name with the property name as the map key and the property value as the value
-
getPropertyKeyValuesFromDataObject
public static Map<String,String> getPropertyKeyValuesFromDataObject(List<String> propertyNames, List<String> securePropertyNames, Object dataObject) Returns a map containing a key/value pair for each property given in the property names list, ignoring any values considered to be secure, including those insecurePropertyNames.- Parameters:
propertyNames- the list of property names for which to get key/value pairssecurePropertyNames- list of additional secure property names to match for encryptiondataObject- the object instance containing the properties for which the values will be pulled- Returns:
- a map containing an entry for each property name with the property name as the map key and the property value as the value
-
isSecure
Determines whether a property name should be secured, either based on installed sensitive data patterns, a list of secure property name patterns, or attributes in the Data Dictionary.- Parameters:
propertyName- the property name to check for securitydataObjectClass- the class of the object containing this property- Returns:
- true if the property needs to be secure, false otherwise
-
isSecure
public static boolean isSecure(String propertyName, List<String> securePropertyNames, Class<?> dataObjectClass) Determines whether a property name should be secured, either based on installed sensitive data patterns, a list of secure property name patterns, or attributes in the Data Dictionary.- Parameters:
propertyName- the property name to check for securitysecurePropertyNames- the secure property name patterns to checkdataObjectClass- the class of the object containing this property- Returns:
- true if the property needs to be secure, false otherwise
-
convertMapToProperties
Utility method to convert a Map to a Properties object- Parameters:
parameters- - map to convert- Returns:
- Properties object containing all the map entries
-
convertRequestMapToProperties
Utility method to convert a Request Parameters Map to a Properties objectMultiple values for a parameter are joined together with comma delimiter
- Parameters:
requestParameters- - map to convert- Returns:
- Properties object containing all the map entries
-
coerceRequestParameterTypes
public static Map<String,Object> coerceRequestParameterTypes(Class<?> dataObjectClass, Map<String, String> parameters) This method converts request parameters coming in as String to native types in case of Boolean, Number or java.sql.Date. For boolean the conversion is performed only if an @Converter annotation is set on the JPA entity field.- Parameters:
dataObjectClass- - business object classparameters- - map of request parameters with field values as String for the fields in the dataObjectClass- Returns:
- Map invalid input: '<'String,Object> converted values
-
containsSensitiveDataPatternMatch
Check if data might be sensitiveThe sensitivity of the data is checked by matching it against the sensitive data patterns that are specified in the system parameter table.
- Parameters:
fieldValue- data to be checked for sensitivity- Returns:
- true if the data matches the sensitive data pattern, false otherwise
-
stripXSSPatterns
Strips out common patterns used in cross side scripting.- Parameters:
values- string array to strip patterns from- Returns:
- cleaned string array
-
stripXSSPatterns
Strips out common patterns used in cross side scripting.- Parameters:
value- string to strip patterns from- Returns:
- cleaned string
-
getUserSessionFromRequest
Gets the UserSession object from the HttpServletRequest object's associated session.In some cases (different threads) the UserSession cannot be retrieved from GlobalVariables but can still be accessed via the session object
- Parameters:
request- servlet request- Returns:
- user session found in the request's servlet session
-
isProductionEnvironment
public static boolean isProductionEnvironment()Check if current deployment is the production environment- Returns:
- true if the deploy environment is production, false otherwise
-
getMessageText
Gets the message associated with ErrorMessage object passed in, using message service. The prefix and suffix will be appended to the retrieved message if processPrefixSuffix is true and if those settings are set on the ErrorMessage passed in.- Parameters:
errorMessage- the ErrorMessage object containing the message key(s)processPrefixSuffix- if true appends the prefix and suffix to the message if they exist on ErrorMessage- Returns:
- the converted/retrieved message
-
logErrors
public static void logErrors()Logs the error messages if any in the message map -
getRequestStringFromMap
Generate the request parameter portion of the url based on the map of key value pairs passed in- Parameters:
requestParameters- the request parameters to use in the string- Returns:
- a request parameter string starting with "?" with "invalid input: '&'" separators, or blank if the mapped passed in is blank
-
addAttachmentToResponse
public static void addAttachmentToResponse(javax.servlet.http.HttpServletResponse response, InputStream inputStream, String contentType, String fileName, long fileSize) throws IOException Adds the header and content of an attachment to the response.- Parameters:
response- HttpServletResponse instanceinputStream- the content of the attachmentcontentType- the content type of the attachmentfileName- the file name of the attachmentfileSize- the size of the attachment- Throws:
IOException- if attachment to the results fails due to an IO error
-
buildViewUrl
Helper method for building a URL that will invoke the given controller and render the given KRAD view- Parameters:
baseUrl- base url (domain, port)controllerMapping- mapping for the controller that should be invokedviewId- id for the view that should be rendered- Returns:
- url for invoking the view
-
getFullURL
Get the full url for a request (requestURL + queryString)- Parameters:
request- the request- Returns:
- the fullUrl
-
areDifferentDomains
Determines whether two URLs point at the same domain.- Parameters:
firstDomain- first URL string to comparesecondDomain- second URL string to compare- Returns:
- true if the domains are different, false otherwise
-
generateUniqueViewTitle
Attempts to generate a unique view title by combining the View's headerText with the title attribute for the dataObjectClass found through the DataObjectMetaDataService. If the title attribute cannot be found, just the headerText is returned.- Parameters:
form- the formview- the view- Returns:
- the headerText with the title attribute in parenthesis or just the headerText if it title attribute cannot be determined
-
buildAttributeTitleString
public static String buildAttributeTitleString(String prependText, Class<?> element, Map<String, String> keyValueMap) Helper method for building title text for an element and a map of key/value pairs,Each key of the key value map is assumed to be an attribute for the given element class. The label is then retrieved for the attribute from the data dictionary and used in the title (instead of the key)
- Parameters:
prependText- text to prepend to the titleelement- element class the title is being generated for, used as the parent for getting the key labelskeyValueMap- map of key value pairs to add to the title text- Returns:
- title string
-
getSimpleFieldValue
Attempts to extract a string value out of the field passed in, varies depending on field typeIf the field is a dataField, it will use its propertyName to retrieve a value, otherwise it will try to retrieve textual content out of various component types. If the field is a FieldGroup, only the first component's determined value will be used. This function is used for sorting.
- Parameters:
model- the current modelfield- the field to get a value from- Returns:
- the field's String value, false if it cant be determined
-
convertToHTMLAttributeSafeString
Helper method to change common characters into HTML attribute safe characters- Parameters:
message- the string to convert- Returns:
- the converted string with quotes, sing quotes, and slash replaced
-
generateRowCssClassString
public static String generateRowCssClassString(Map<String, String> conditionalRowCssClasses, int lineIndex, boolean isOdd, Map<String, Object> lineContext, ExpressionEvaluator expressionEvaluator) Get the rowCss for the line specified, by evaluating the conditionalRowCssClasses map for that row- Parameters:
conditionalRowCssClasses- the conditionalRowCssClass map, where key is the condition and value is the class(es)lineIndex- the line/row indexisOdd- true if the row is considered oddlineContext- the lineContext for expressions, pass null if not applicableexpressionEvaluator- the expressionEvaluator, pass null if not applicable- Returns:
- row csss class String for the class attribute of this row
-
easyGetPropertyType
public static Class<?> easyGetPropertyType(Object object, String propertyName) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException LegacyCase - This method simply uses PojoPropertyUtilsBean logic to get the Class of a Class property. This method does not have any of the logic needed to obtain the Class of an element of a Collection specified in the DataDictionary.- Parameters:
object- An instance of the Class of which we're trying to get the property Class.propertyName- The name of the property.- Throws:
IllegalAccessExceptionNoSuchMethodExceptionInvocationTargetException
-
setObjectProperty
public static void setObjectProperty(Object bo, String propertyName, Object propertyValue) throws FormatException, IllegalAccessException, InvocationTargetException, NoSuchMethodException Sets the property of an object with the given value. Converts using the formatter of the type for the property. Note: propertyType does not need passed, is found by util method. -
setObjectProperty
public static <T> void setObjectProperty(Object bo, String propertyName, Class<T> propertyType, T propertyValue) throws FormatException, IllegalAccessException, InvocationTargetException, NoSuchMethodException Sets the property of an object with the given value. Converts using the formatter of the given type if one is found. -
clean
Removes all query characters from a string.- Returns:
- Cleaned string
-
isNull
This method is a confirms if object is null, and unproxies if necessary to determine this- Parameters:
object- - any object, proxied or not, materialized or not- Returns:
- true if the object (or underlying materialized object) is null, false otherwise
-
isNotNull
This method is a confirms if object is not null, and unproxies if necessary to determine this- Parameters:
object- - any object, proxied or not, materialized or not- Returns:
- true if the object (or underlying materialized object) is not null, true if its null
-
materializeClassForProxiedObject
Attempts to find the Class for the given potentially proxied object- Parameters:
object- the potentially proxied object to find the Class of- Returns:
- the best Class which could be found for the given object
-
materializeObjects
This method runs the KRADUtils.isNotNull() method for each item in a list of BOs. KRADUtils.isNotNull() will materialize the objects if they are currently OJB proxies.- Parameters:
possiblyProxiedObjects- - a Collection of objects that may be proxies
-
getNestedAttributePrefix
Returns the prefix of a nested attribute name, or the empty string if the attribute name is not nested.- Returns:
- everything BEFORE the last "." character in attributeName
-
getNestedAttributePrimitive
Returns the primitive part of an attribute name string.- Returns:
- everything AFTER the last "." character in attributeName
-
getNestedValue
This method safely extracts either simple values OR nested values. For example, if the bo is SubAccount, and the fieldName is a21SubAccount.subAccountTypeCode, this thing makes sure it gets the value off the very end attribute, no matter how deeply nested it is. The code would be slightly simpler if this was done recursively, but this is safer, and consumes a constant amount of memory, no matter how deeply nested it goes.- Returns:
- The field value if it exists. If it doesnt, and the name is invalid, and
-
createNewObjectFromClass
This method safely creates a object from a class Convenience method to create new object and throw a runtime exception if it cannot If the class is anExternalizableBusinessObject, this method will determine the interface for the EBO and query the appropriate module service to create a new instance.- Returns:
- a newInstance() of clazz
-
syncClientSideStateForComponent
public static void syncClientSideStateForComponent(Component component, Map<String, Object> clientSideState) Updates the properties of the given component instance with the value found from the corresponding map of client state (if found)- Parameters:
component- component instance to updateclientSideState- map of state to sync with
-