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