Coverage Report - org.kuali.rice.krad.util.KRADUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
KRADUtils
0%
0/156
0%
0/70
2.962
 
 1  
 /*
 2  
  * Copyright 2007-2009 The Kuali Foundation
 3  
  * 
 4  
  * Licensed under the Educational Community License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  * 
 8  
  * http://www.opensource.org/licenses/ecl2.php
 9  
  * 
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  */
 16  
 package org.kuali.rice.krad.util;
 17  
 
 18  
 import org.apache.commons.lang.StringUtils;
 19  
 import org.kuali.rice.core.api.CoreApiServiceLocator;
 20  
 import org.kuali.rice.core.api.encryption.EncryptionService;
 21  
 import org.kuali.rice.core.framework.parameter.ParameterConstants;
 22  
 import org.kuali.rice.core.framework.parameter.ParameterService;
 23  
 import org.kuali.rice.core.framework.services.CoreFrameworkServiceLocator;
 24  
 import org.kuali.rice.core.util.type.KualiDecimal;
 25  
 import org.kuali.rice.core.web.format.BooleanFormatter;
 26  
 import org.kuali.rice.krad.UserSession;
 27  
 import org.kuali.rice.krad.service.KRADServiceLocator;
 28  
 import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
 29  
 import org.kuali.rice.krad.service.KualiModuleService;
 30  
 import org.kuali.rice.krad.service.ModuleService;
 31  
 import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
 32  
 
 33  
 import javax.servlet.ServletRequest;
 34  
 import javax.servlet.http.HttpServletRequest;
 35  
 import java.lang.reflect.Constructor;
 36  
 import java.security.GeneralSecurityException;
 37  
 import java.text.NumberFormat;
 38  
 import java.util.ArrayList;
 39  
 import java.util.Arrays;
 40  
 import java.util.Collection;
 41  
 import java.util.HashMap;
 42  
 import java.util.Iterator;
 43  
 import java.util.List;
 44  
 import java.util.Map;
 45  
 import java.util.regex.Pattern;
 46  
 
 47  
 /**
 48  
  * Miscellaneous Utility Methods.
 49  
  *
 50  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 51  
  */
 52  
 public final class KRADUtils {
 53  
     private static KualiModuleService kualiModuleService;
 54  
 
 55  0
     private KRADUtils() {
 56  0
         throw new UnsupportedOperationException("do not call");
 57  
     }
 58  
 
 59  
     public final static String getBusinessTitleForClass(Class<? extends Object> clazz) {
 60  0
         if (clazz == null) {
 61  0
             throw new IllegalArgumentException(
 62  
                     "The getBusinessTitleForClass method of KRADUtils requires a non-null class");
 63  
         }
 64  0
         String className = clazz.getSimpleName();
 65  
 
 66  0
         StringBuffer label = new StringBuffer(className.substring(0, 1));
 67  0
         for (int i = 1; i < className.length(); i++) {
 68  0
             if (Character.isLowerCase(className.charAt(i))) {
 69  0
                 label.append(className.charAt(i));
 70  
             } else {
 71  0
                 label.append(" ").append(className.charAt(i));
 72  
             }
 73  
         }
 74  0
         return label.toString().trim();
 75  
     }
 76  
 
 77  
     /**
 78  
      * Picks off the filename from the full path. Takes care of different OS seperators.
 79  
      */
 80  
     public final static List<String> getFileNameFromPath(List<String> fullFileNames) {
 81  0
         List<String> fileNameList = new ArrayList<String>();
 82  
 
 83  0
         for (String fullFileName : fullFileNames) {
 84  0
             if (StringUtils.contains(fullFileName, "/")) {
 85  0
                 fileNameList.add(StringUtils.substringAfterLast(fullFileName, "/"));
 86  
             } else {
 87  0
                 fileNameList.add(StringUtils.substringAfterLast(fullFileName, "\\"));
 88  
             }
 89  
         }
 90  
 
 91  0
         return fileNameList;
 92  
     }
 93  
 
 94  0
     private static final KualiDecimal ONE_HUNDRED = new KualiDecimal("100.00");
 95  
 
 96  
     /**
 97  
      * Convert the given monney amount into an interger string. Since the return string cannot have decimal point,
 98  
      * multiplies the
 99  
      * amount by 100 so the decimal places are not lost, for example, 320.15 is converted into 32015.
 100  
      *
 101  
      * @return an integer string of the given money amount through multiplicating by 100 and removing the fraction
 102  
      *         portion.
 103  
      */
 104  
     public final static String convertDecimalIntoInteger(KualiDecimal decimalNumber) {
 105  0
         KualiDecimal decimalAmount = decimalNumber.multiply(ONE_HUNDRED);
 106  0
         NumberFormat formatter = NumberFormat.getIntegerInstance();
 107  0
         String formattedAmount = formatter.format(decimalAmount);
 108  
 
 109  0
         return StringUtils.replace(formattedAmount, ",", "");
 110  
     }
 111  
 
 112  
     public static Integer getIntegerValue(String numberStr) {
 113  0
         Integer numberInt = null;
 114  
         try {
 115  0
             numberInt = new Integer(numberStr);
 116  0
         } catch (NumberFormatException nfe) {
 117  0
             Double numberDbl = new Double(numberStr);
 118  0
             numberInt = new Integer(numberDbl.intValue());
 119  0
         }
 120  0
         return numberInt;
 121  
     }
 122  
 
 123  
     public static Object createObject(Class<?> clazz, Class<?>[] argumentClasses, Object[] argumentValues) {
 124  0
         if (clazz == null)
 125  0
             return null;
 126  
         try {
 127  0
             Constructor<?> constructor = clazz.getConstructor(argumentClasses);
 128  0
             return constructor.newInstance(argumentValues);
 129  0
         } catch (Exception e) {
 130  0
             return null;
 131  
         }
 132  
     }
 133  
 
 134  
     public static String joinWithQuotes(List<String> list) {
 135  0
         if (list == null || list.size() == 0)
 136  0
             return "";
 137  
 
 138  0
         return KRADConstants.SINGLE_QUOTE +
 139  
                 StringUtils.join(list.iterator(), KRADConstants.SINGLE_QUOTE + "," + KRADConstants.SINGLE_QUOTE) +
 140  
                 KRADConstants.SINGLE_QUOTE;
 141  
     }
 142  
 
 143  
     private static KualiModuleService getKualiModuleService() {
 144  0
         if (kualiModuleService == null) {
 145  0
             kualiModuleService = KRADServiceLocatorWeb.getKualiModuleService();
 146  
         }
 147  0
         return kualiModuleService;
 148  
     }
 149  
 
 150  
     /**
 151  
      * TODO this method will probably need to be exposed in a public KRADUtils class as it is used
 152  
      * by several different modules.  That will have to wait until ModuleService and KualiModuleService are moved
 153  
      * to core though.
 154  
      */
 155  
     public static String getNamespaceCode(Class<? extends Object> clazz) {
 156  0
         ModuleService moduleService = getKualiModuleService().getResponsibleModuleService(clazz);
 157  0
         if (moduleService == null) {
 158  0
             return KRADConstants.DEFAULT_NAMESPACE;
 159  
         }
 160  0
         return moduleService.getModuleConfiguration().getNamespaceCode();
 161  
     }
 162  
 
 163  
     public static Map<String, String> getNamespaceAndComponentSimpleName(Class<? extends Object> clazz) {
 164  0
         Map<String, String> map = new HashMap<String, String>();
 165  0
         map.put(KRADConstants.NAMESPACE_CODE, getNamespaceCode(clazz));
 166  0
         map.put(KRADConstants.COMPONENT_NAME, getComponentSimpleName(clazz));
 167  0
         return map;
 168  
     }
 169  
 
 170  
     public static Map<String, String> getNamespaceAndComponentFullName(Class<? extends Object> clazz) {
 171  0
         Map<String, String> map = new HashMap<String, String>();
 172  0
         map.put(KRADConstants.NAMESPACE_CODE, getNamespaceCode(clazz));
 173  0
         map.put(KRADConstants.COMPONENT_NAME, getComponentFullName(clazz));
 174  0
         return map;
 175  
     }
 176  
 
 177  
     public static Map<String, String> getNamespaceAndActionClass(Class<? extends Object> clazz) {
 178  0
         Map<String, String> map = new HashMap<String, String>();
 179  0
         map.put(KRADConstants.NAMESPACE_CODE, getNamespaceCode(clazz));
 180  0
         map.put(KRADConstants.ACTION_CLASS, clazz.getName());
 181  0
         return map;
 182  
     }
 183  
 
 184  
     private static String getComponentSimpleName(Class<? extends Object> clazz) {
 185  0
         return clazz.getSimpleName();
 186  
     }
 187  
 
 188  
     private static String getComponentFullName(Class<? extends Object> clazz) {
 189  0
         return clazz.getName();
 190  
     }
 191  
 
 192  
     /**
 193  
      * Parses a string that is in map format (commas separating map entries, colon separates
 194  
      * map key/value) to a new map instance
 195  
      *
 196  
      * @param parameter - string parameter to parse
 197  
      * @return Map<String, String> instance populated from string parameter
 198  
      */
 199  
     public static Map<String, String> convertStringParameterToMap(String parameter) {
 200  0
         Map<String, String> map = new HashMap<String, String>();
 201  
 
 202  0
         if (StringUtils.isNotBlank(parameter)) {
 203  0
             if (StringUtils.contains(parameter, ",")) {
 204  0
                 String[] fieldConversions = StringUtils.split(parameter, ",");
 205  
 
 206  0
                 for (int i = 0; i < fieldConversions.length; i++) {
 207  0
                     String fieldConversionStr = fieldConversions[i];
 208  0
                     if (StringUtils.isNotBlank(fieldConversionStr)) {
 209  0
                         if (StringUtils.contains(fieldConversionStr, ":")) {
 210  0
                             String[] fieldConversion = StringUtils.split(fieldConversionStr, ":");
 211  0
                             map.put(fieldConversion[0], fieldConversion[1]);
 212  0
                         } else {
 213  0
                             map.put(fieldConversionStr, fieldConversionStr);
 214  
                         }
 215  
                     }
 216  
                 }
 217  0
             } else if (StringUtils.contains(parameter, ":")) {
 218  0
                 String[] fieldConversion = StringUtils.split(parameter, ":");
 219  0
                 map.put(fieldConversion[0], fieldConversion[1]);
 220  0
             } else {
 221  0
                 map.put(parameter, parameter);
 222  
             }
 223  
         }
 224  
 
 225  0
         return map;
 226  
     }
 227  
 
 228  
     /**
 229  
      * Parses a string that is in list format (commas separating list entries) to a new List instance
 230  
      *
 231  
      * @param parameter - string parameter to parse
 232  
      * @return List<String> instance populated from string parameter
 233  
      */
 234  
     public static List<String> convertStringParameterToList(String parameter) {
 235  0
         List<String> list = new ArrayList<String>();
 236  
 
 237  0
         if (StringUtils.isNotBlank(parameter)) {
 238  0
             if (StringUtils.contains(parameter, ",")) {
 239  0
                 String[] parameters = StringUtils.split(parameter, ",");
 240  0
                 list = Arrays.asList(parameters);
 241  0
             } else {
 242  0
                 list.add(parameter);
 243  
             }
 244  
         }
 245  
 
 246  0
         return list;
 247  
     }
 248  
 
 249  
     /**
 250  
      * Translates characters in the given string like brackets that will cause
 251  
      * problems with binding to characters that do not affect the binding
 252  
      *
 253  
      * @param key - string to translate
 254  
      * @return String translated string
 255  
      */
 256  
     public static String translateToMapSafeKey(String key) {
 257  0
         String safeKey = key;
 258  
 
 259  0
         safeKey = StringUtils.replace(safeKey, "[", "_");
 260  0
         safeKey = StringUtils.replace(safeKey, "]", "_");
 261  
 
 262  0
         return safeKey;
 263  
     }
 264  
 
 265  
     /**
 266  
      * Builds a string from the given map by joining each entry with a comma and
 267  
      * each key/value pair with a colon
 268  
      *
 269  
      * @param map - map instance to build string for
 270  
      * @return String of map entries
 271  
      */
 272  
     public static String buildMapParameterString(Map<String, String> map) {
 273  0
         String parameterString = "";
 274  
 
 275  0
         for (Map.Entry<String, String> entry : map.entrySet()) {
 276  0
             if (StringUtils.isNotBlank(parameterString)) {
 277  0
                 parameterString += ",";
 278  
             }
 279  
 
 280  0
             parameterString += entry.getKey() + ":" + entry.getValue();
 281  
         }
 282  
 
 283  0
         return parameterString;
 284  
     }
 285  
 
 286  
     /**
 287  
      * Parses the given string into a Map by splitting on the comma to get the
 288  
      * map entries and within each entry splitting by colon to get the key/value
 289  
      * pairs
 290  
      *
 291  
      * @param parameterString - string to parse into map
 292  
      * @return Map<String, String> map from string
 293  
      */
 294  
     public static Map<String, String> getMapFromParameterString(String parameterString) {
 295  0
         Map<String, String> map = new HashMap<String, String>();
 296  
 
 297  0
         String[] entries = parameterString.split(",");
 298  0
         for (int i = 0; i < entries.length; i++) {
 299  0
             String[] keyValue = entries[i].split(":");
 300  0
             if (keyValue.length != 2) {
 301  0
                 throw new RuntimeException("malformed field conversion pair: " + Arrays.toString(keyValue));
 302  
             }
 303  
 
 304  0
             map.put(keyValue[0], keyValue[1]);
 305  
         }
 306  
 
 307  0
         return map;
 308  
     }
 309  
 
 310  
     /**
 311  
      * Retrieves value for the given parameter name in the request and attempts to convert to a Boolean using
 312  
      * the <code>BooleanFormatter</code>
 313  
      *
 314  
      * @param request - servlet request containing parameters
 315  
      * @param parameterName - name of parameter to retrieve value for
 316  
      * @return Boolean set to value of parameter, or null if parameter was not found in request
 317  
      */
 318  
     public static Boolean getRequestParameterAsBoolean(ServletRequest request, String parameterName) {
 319  0
         Boolean parameterValue = null;
 320  
 
 321  0
         String parameterValueStr = request.getParameter(parameterName);
 322  0
         if (StringUtils.isNotBlank(parameterValueStr)) {
 323  0
             parameterValue = (Boolean) new BooleanFormatter().convertFromPresentationFormat(parameterValueStr);
 324  
         }
 325  
 
 326  0
         return parameterValue;
 327  
     }
 328  
 
 329  
     /**
 330  
      * Translates the given Map of String keys and String array values to a Map
 331  
      * of String key and values. If the String array contains more than one
 332  
      * value, the single string is built by joining the values with the vertical
 333  
      * bar character
 334  
      *
 335  
      * @param requestParameters - Map of request parameters to translate
 336  
      * @return Map<String, String> translated Map
 337  
      */
 338  
     public static Map<String, String> translateRequestParameterMap(Map<String, String[]> requestParameters) {
 339  0
         Map<String, String> parameters = new HashMap<String, String>();
 340  
 
 341  0
         for (Map.Entry<String, String[]> parameter : requestParameters.entrySet()) {
 342  0
             String parameterValue = "";
 343  0
             if (parameter.getValue().length > 1) {
 344  0
                 parameterValue = StringUtils.join(parameter.getValue(), "|");
 345  
             } else {
 346  0
                 parameterValue = parameter.getValue()[0];
 347  
             }
 348  0
             parameters.put(parameter.getKey(), parameterValue);
 349  0
         }
 350  
 
 351  0
         return parameters;
 352  
     }
 353  
 
 354  
     /**
 355  
      * Retrieves parameter values from the request that match the requested
 356  
      * names. In addition, based on the object class an authorization check is
 357  
      * performed to determine if the values are secure and should be decrypted.
 358  
      * If true, the value is decrypted before returning
 359  
      *
 360  
      * @param parameterNames - names of the parameters whose values should be retrieved
 361  
      * from the request
 362  
      * @param parentObjectClass - object class that contains the parameter names as properties
 363  
      * and should be consulted for security checks
 364  
      * @param requestParameters - all request parameters to pull from
 365  
      * @return Map<String, String> populated with parameter name/value pairs
 366  
      *         pulled from the request
 367  
      */
 368  
     public static Map<String, String> getParametersFromRequest(List<String> parameterNames, Class<?> parentObjectClass,
 369  
             Map<String, String> requestParameters) {
 370  0
         Map<String, String> parameterValues = new HashMap<String, String>();
 371  
 
 372  0
         for (Iterator<String> iter = parameterNames.iterator(); iter.hasNext(); ) {
 373  0
             String keyPropertyName = iter.next();
 374  
 
 375  0
             if (requestParameters.get(keyPropertyName) != null) {
 376  0
                 String keyValue = requestParameters.get(keyPropertyName);
 377  
 
 378  
                 // Check if this element was encrypted, if it was decrypt it
 379  0
                 if (KRADServiceLocatorWeb.getDataObjectAuthorizationService()
 380  
                         .attributeValueNeedsToBeEncryptedOnFormsAndLinks(parentObjectClass, keyPropertyName)) {
 381  
                     try {
 382  0
                         keyValue = StringUtils.removeEnd(keyValue, EncryptionService.ENCRYPTION_POST_PREFIX);
 383  0
                         keyValue = CoreApiServiceLocator.getEncryptionService().decrypt(keyValue);
 384  0
                     } catch (GeneralSecurityException e) {
 385  0
                         throw new RuntimeException(e);
 386  0
                     }
 387  
                 }
 388  
 
 389  0
                 parameterValues.put(keyPropertyName, keyValue);
 390  
             }
 391  0
         }
 392  
 
 393  0
         return parameterValues;
 394  
     }
 395  
 
 396  
     /**
 397  
      * Builds a Map containing a key/value pair for each property given in the property names list, general
 398  
      * security is checked to determine if the value needs to be encrypted along with applying formatting to
 399  
      * the value
 400  
      *
 401  
      * @param propertyNames - list of property names to get key/value pairs for
 402  
      * @param dataObject - object instance containing the properties for which the values will be pulled
 403  
      * @return Map<String, String> containing entry for each property name with the property name as the map key
 404  
      *         and the property value as the value
 405  
      */
 406  
     public static Map<String, String> getPropertyKeyValuesFromDataObject(List<String> propertyNames,
 407  
             Object dataObject) {
 408  0
         Map<String, String> propertyKeyValues = new HashMap<String, String>();
 409  
 
 410  0
         if (dataObject == null) {
 411  0
             return propertyKeyValues;
 412  
         }
 413  
 
 414  
         // iterate through properties and add a map entry for each
 415  0
         for (String propertyName : propertyNames) {
 416  0
             Object propertyValue = ObjectPropertyUtils.getPropertyValue(dataObject, propertyName);
 417  0
             if (propertyValue == null) {
 418  0
                 propertyValue = StringUtils.EMPTY;
 419  
             }
 420  
 
 421  0
             if (KRADServiceLocatorWeb.getDataObjectAuthorizationService()
 422  
                     .attributeValueNeedsToBeEncryptedOnFormsAndLinks(dataObject.getClass(), propertyName)) {
 423  
                 try {
 424  0
                     propertyValue = CoreApiServiceLocator.getEncryptionService().encrypt(propertyValue) +
 425  
                             EncryptionService.ENCRYPTION_POST_PREFIX;
 426  0
                 } catch (GeneralSecurityException e) {
 427  0
                     throw new RuntimeException("Exception while trying to encrypt value for key/value map.", e);
 428  0
                 }
 429  
             }
 430  
 
 431  
             // TODO: need to apply formatting to return value once util class is ready
 432  0
             propertyKeyValues.put(propertyName, propertyValue.toString());
 433  0
         }
 434  
 
 435  0
         return propertyKeyValues;
 436  
     }
 437  
 
 438  
     public static boolean containsSensitiveDataPatternMatch(String fieldValue) {
 439  0
         if (StringUtils.isBlank(fieldValue)) {
 440  0
             return false;
 441  
         }
 442  0
         ParameterService parameterService = CoreFrameworkServiceLocator.getParameterService();
 443  0
         Collection<String> sensitiveDataPatterns = parameterService
 444  
                 .getParameterValuesAsString(KRADConstants.KRAD_NAMESPACE, ParameterConstants.ALL_COMPONENT,
 445  
                         KRADConstants.SystemGroupParameterNames.SENSITIVE_DATA_PATTERNS);
 446  0
         for (String pattern : sensitiveDataPatterns) {
 447  0
             if (Pattern.compile(pattern).matcher(fieldValue).find()) {
 448  0
                 return true;
 449  
             }
 450  
         }
 451  0
         return false;
 452  
     }
 453  
 
 454  
     /**
 455  
      * Gets the UserSession object from the HttpServletRequest object's
 456  
      * associated session.
 457  
      *
 458  
      * <p>
 459  
      * In some cases (different threads) the UserSession cannot be retrieved
 460  
      * from GlobalVariables but can still be accessed via the session object
 461  
      * </p>
 462  
      */
 463  
     public static final UserSession getUserSessionFromRequest(HttpServletRequest request) {
 464  0
         return (UserSession) request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY);
 465  
     }
 466  
 
 467  
     /**
 468  
      * @return whether the deploy environment is production
 469  
      */
 470  
     public static boolean isProductionEnvironment() {
 471  0
         return KRADServiceLocator.getKualiConfigurationService().isProductionEnvironment();
 472  
     }
 473  
 }