Coverage Report - org.kuali.rice.krad.uif.util.ClientValidationUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
ClientValidationUtils
0%
0/287
0%
0/236
7.05
ClientValidationUtils$ValidationMessageKeys
0%
0/14
0%
0/4
7.05
 
 1  
 /*
 2  
  * Copyright 2011 The Kuali Foundation
 3  
  *
 4  
  * Licensed under the Educational Community License, Version 1.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/ecl1.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.uif.util;
 17  
 
 18  
 import org.apache.commons.lang.StringUtils;
 19  
 import org.kuali.rice.core.api.config.property.ConfigurationService;
 20  
 import org.kuali.rice.krad.datadictionary.validation.constraint.BaseConstraint;
 21  
 import org.kuali.rice.krad.datadictionary.validation.constraint.CaseConstraint;
 22  
 import org.kuali.rice.krad.datadictionary.validation.constraint.Constraint;
 23  
 import org.kuali.rice.krad.datadictionary.validation.constraint.MustOccurConstraint;
 24  
 import org.kuali.rice.krad.datadictionary.validation.constraint.PrerequisiteConstraint;
 25  
 import org.kuali.rice.krad.datadictionary.validation.constraint.SimpleConstraint;
 26  
 import org.kuali.rice.krad.datadictionary.validation.constraint.ValidCharactersConstraint;
 27  
 import org.kuali.rice.krad.datadictionary.validation.constraint.WhenConstraint;
 28  
 import org.kuali.rice.krad.service.KRADServiceLocator;
 29  
 import org.kuali.rice.krad.uif.UifConstants;
 30  
 import org.kuali.rice.krad.uif.container.View;
 31  
 import org.kuali.rice.krad.uif.control.TextControl;
 32  
 import org.kuali.rice.krad.uif.field.AttributeField;
 33  
 
 34  
 import java.text.MessageFormat;
 35  
 import java.util.ArrayList;
 36  
 import java.util.EnumSet;
 37  
 import java.util.List;
 38  
 
 39  
 /**
 40  
  * This class contains all the methods necessary for generating the js required to perform validation client side.
 41  
  * The processAndApplyConstraints(AttributeField field, View view) is the key method of this class used by
 42  
  * AttributeField to setup its client side validation mechanisms.
 43  
  * 
 44  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 45  
  */
 46  0
 public class ClientValidationUtils {
 47  
         // used to give validation methods unique signatures
 48  0
         private static int methodKey = 0;
 49  
         
 50  
         // list used to temporarily store mustOccurs field names for the error
 51  
         // message
 52  
         private static List<List<String>> mustOccursPathNames;
 53  
         
 54  
         public static final String LABEL_KEY_SPLIT_PATTERN = ",";
 55  
         
 56  
         
 57  
         public static final String PREREQ_MSG_KEY = "prerequisite";
 58  
         public static final String POSTREQ_MSG_KEY = "postrequisite";
 59  
         public static final String MUSTOCCURS_MSG_KEY = "mustOccurs";
 60  
         public static final String GENERIC_FIELD_MSG_KEY = "general.genericFieldName";
 61  
         
 62  
         public static final String ALL_MSG_KEY = "general.all";
 63  
         public static final String ATMOST_MSG_KEY = "general.atMost";
 64  
         public static final String AND_MSG_KEY = "general.and";
 65  
         public static final String OR_MSG_KEY = "general.or";
 66  
         
 67  0
         private static ConfigurationService configService = KRADServiceLocator.getKualiConfigurationService();
 68  
         
 69  
         //Enum representing names of rules provided by the jQuery plugin
 70  0
         public static enum ValidationMessageKeys{
 71  0
                 REQUIRED("required"), 
 72  0
                 MIN_EXCLUSIVE("minExclusive"), 
 73  0
                 MAX_INCLUSIVE("maxInclusive"),
 74  0
                 MIN_LENGTH("minLengthConditional"),
 75  0
                 MAX_LENGTH("maxLengthConditional");
 76  
                 
 77  0
                 private ValidationMessageKeys(String name) {
 78  0
                         this.name = name;
 79  0
                 }
 80  
                 
 81  
                 private final String name;
 82  
                 
 83  
                 @Override
 84  
                 public String toString() {
 85  0
                         return name;
 86  
                 }
 87  
                 
 88  
                 public static boolean contains(String name){
 89  0
             for (ValidationMessageKeys element : EnumSet.allOf(ValidationMessageKeys.class)) {
 90  0
                 if (element.toString().equalsIgnoreCase(name)) {
 91  0
                     return true;
 92  
                 }
 93  
             }
 94  0
             return false;
 95  
                 }
 96  
         }
 97  
         
 98  
         public static String generateMessageFromLabelKey(List<String> params, String labelKey){
 99  0
                 String message = "NO MESSAGE";
 100  0
                 if(StringUtils.isNotEmpty(labelKey)){
 101  0
                         message = configService.getPropertyValueAsString(labelKey);
 102  0
                         if(params != null && !params.isEmpty() && StringUtils.isNotEmpty(message)){
 103  0
                             message = MessageFormat.format(message, params.toArray());
 104  
                         }
 105  
                 }
 106  0
                 if(StringUtils.isEmpty(message)){
 107  0
                     message = labelKey;
 108  
                 }
 109  0
                 else if(message.contains("\"")){
 110  0
                     message = message.replaceAll("\"", "&quot;");
 111  
                 }
 112  0
                 return message;
 113  
         }
 114  
 
 115  
         /**
 116  
          * Generates the js object used to override all default messages for validator jquery plugin with custom
 117  
          * messages derived from the configService.
 118  
          * 
 119  
          * @return
 120  
          */
 121  
         public static String generateValidatorMessagesOption(){
 122  0
                 String mOption = "";
 123  0
                 String keyValuePairs = "";
 124  0
                 for(ValidationMessageKeys element : EnumSet.allOf(ValidationMessageKeys.class)){
 125  0
                         String key = element.toString();
 126  0
                         String message = configService.getPropertyValueAsString(UifConstants.Messages.VALIDATION_MSG_KEY_PREFIX + key);
 127  0
                         if(StringUtils.isNotEmpty(message)){
 128  0
                                 keyValuePairs = keyValuePairs + "\n" + key + ": '"+ message + "',";
 129  
                                 
 130  
                         }
 131  
                         
 132  0
                 }
 133  0
                 keyValuePairs = StringUtils.removeEnd(keyValuePairs, ",");
 134  0
                 if(StringUtils.isNotEmpty(keyValuePairs)){
 135  0
                         mOption="{" + keyValuePairs + "}";
 136  
                 }
 137  
                 
 138  0
                 return mOption;
 139  
         }
 140  
         
 141  
         /**
 142  
          * Returns the add method jquery validator call for the regular expression
 143  
          * stored in validCharactersConstraint.
 144  
          * 
 145  
          * @param validCharactersConstraint
 146  
          * @return js validator.addMethod script
 147  
          */
 148  
         public static String getRegexMethod(AttributeField field, ValidCharactersConstraint validCharactersConstraint) {
 149  0
                 String message = generateMessageFromLabelKey(validCharactersConstraint.getValidationMessageParams(), validCharactersConstraint.getLabelKey());
 150  0
                 String key = "validChar-" + field.getBindingInfo().getBindingPath() + methodKey;
 151  
                 
 152  0
                 String regex = validCharactersConstraint.getValue();
 153  0
                 if(regex.contains("\\\\")){
 154  0
                     regex.replaceAll("\\\\", "\\\\\\\\");
 155  
                 }
 156  
                 
 157  0
         return "\njQuery.validator.addMethod(\"" + key
 158  
                 + "\", function(value, element) {\n "
 159  
                 + "return this.optional(element) || /" + regex + "/.test(value);"
 160  
                 + "}, \"" + message + "\");";
 161  
         }
 162  
         
 163  
         /**
 164  
      * Returns the add method jquery validator call for the regular expression
 165  
      * stored in validCharactersConstraint that explicitly checks a boolean.  Needed because one method
 166  
      * accepts params and the other doesn't.
 167  
      * 
 168  
      * @param validCharactersConstraint
 169  
      * @return js validator.addMethod script
 170  
      */
 171  
     public static String getRegexMethodWithBooleanCheck(AttributeField field, ValidCharactersConstraint validCharactersConstraint) {
 172  0
         String message = generateMessageFromLabelKey(validCharactersConstraint.getValidationMessageParams(), validCharactersConstraint.getLabelKey());
 173  0
         String key = "validChar-" + field.getBindingInfo().getBindingPath() + methodKey;
 174  
         
 175  0
         String regex = validCharactersConstraint.getValue();
 176  0
         if(regex.contains("\\\\")){
 177  0
             regex.replaceAll("\\\\", "\\\\\\\\");
 178  
         }
 179  
         
 180  0
         return "\njQuery.validator.addMethod(\"" + key
 181  
                 + "\", function(value, element, doCheck) {\n if(doCheck === false){return true;}else{"
 182  
                 + "return this.optional(element) || /" + regex + "/.test(value);}"
 183  
                 + "}, \"" + message + "\");";
 184  
     }
 185  
         
 186  
 
 187  
         /**
 188  
          * This method processes a single CaseConstraint. Internally it makes calls
 189  
          * to processWhenConstraint for each WhenConstraint that exists in this
 190  
          * constraint. It adds a "dependsOn" css class to this field for the field
 191  
          * which the CaseConstraint references.
 192  
          * 
 193  
          * @param view
 194  
          * @param andedCase
 195  
          *            the boolean logic to be anded when determining if this case is
 196  
          *            satisfied (used for nested CaseConstraints)
 197  
          */
 198  
         public static void processCaseConstraint(AttributeField field, View view, CaseConstraint constraint, String andedCase) {
 199  0
                 if (constraint.getOperator() == null) {
 200  0
                         constraint.setOperator("equals");
 201  
                 }
 202  
 
 203  0
                 String operator = "==";
 204  0
                 if (constraint.getOperator().equalsIgnoreCase("not_equals")) {
 205  0
                         operator = "!=";
 206  
                 }
 207  0
                 else if (constraint.getOperator().equalsIgnoreCase("greater_than_equal")) {
 208  0
                         operator = ">=";
 209  
                 }
 210  0
                 else if (constraint.getOperator().equalsIgnoreCase("less_than_equal")) {
 211  0
                         operator = "<=";
 212  
                 }
 213  0
                 else if (constraint.getOperator().equalsIgnoreCase("greater_than")) {
 214  0
                         operator = ">";
 215  
                 }
 216  0
                 else if (constraint.getOperator().equalsIgnoreCase("less_than")) {
 217  0
                         operator = "<";
 218  
                 }
 219  0
                 else if (constraint.getOperator().equalsIgnoreCase("has_value")) {
 220  0
                         operator = "";
 221  
                 }
 222  
                 // add more operator types here if more are supported later
 223  
 
 224  0
                 field.getControl().addStyleClass("dependsOn-" + constraint.getFieldPath());
 225  
 
 226  0
                 if (constraint.getWhenConstraint() != null && !constraint.getWhenConstraint().isEmpty()) {
 227  0
                         for (WhenConstraint wc : constraint.getWhenConstraint()) {
 228  0
                                 processWhenConstraint(field, view, constraint, wc, constraint.getFieldPath(), operator, andedCase);
 229  
                         }
 230  
                 }
 231  0
         }
 232  
         
 233  
 
 234  
 
 235  
         /**
 236  
          * This method processes the WhenConstraint passed in. The when constraint
 237  
          * is used to create a boolean statement to determine if the constraint will
 238  
          * be applied. The necessary rules/methods for applying this constraint are
 239  
          * created in the createRule call. Note the use of the use of coerceValue js
 240  
          * function call.
 241  
          * 
 242  
          * @param view
 243  
          * @param wc
 244  
          * @param fieldPath
 245  
          * @param operator
 246  
          * @param andedCase
 247  
          */
 248  
         private static void processWhenConstraint(AttributeField field, View view, CaseConstraint caseConstraint, WhenConstraint wc, String fieldPath,
 249  
                         String operator, String andedCase) {
 250  0
                 String ruleString = "";
 251  
                 // prerequisite constraint
 252  
 
 253  0
                 String booleanStatement = "";
 254  0
                 if (wc.getValues() != null) {
 255  
 
 256  0
                         String caseStr = "";
 257  0
                         if (!caseConstraint.isCaseSensitive()) {
 258  0
                                 caseStr = ".toUpperCase()";
 259  
                         }
 260  0
                         for (int i = 0; i < wc.getValues().size(); i++) {
 261  0
                                 if (operator.isEmpty()) {
 262  
                                         // has_value case
 263  0
                                         if (wc.getValues().get(i) instanceof String
 264  
                                                         && ((String) wc.getValues().get(i)).equalsIgnoreCase("false")) {
 265  0
                                                 booleanStatement = booleanStatement + "(coerceValue('" + fieldPath + "') == '')";
 266  
                                         }
 267  
                                         else {
 268  0
                                                 booleanStatement = booleanStatement + "(coerceValue('" + fieldPath + "') != '')";
 269  
                                         }
 270  
                                 }
 271  
                                 else {
 272  
                                         // everything else
 273  0
                                         booleanStatement = booleanStatement + "(coerceValue('" + fieldPath + "')" + caseStr + " "
 274  
                                                         + operator + " \"" + wc.getValues().get(i) + "\"" + caseStr + ")";
 275  
                                 }
 276  0
                                 if ((i + 1) != wc.getValues().size()) {
 277  0
                                         booleanStatement = booleanStatement + " || ";
 278  
                                 }
 279  
                         }
 280  
 
 281  
                 }
 282  
 
 283  0
                 if (andedCase != null) {
 284  0
                         booleanStatement = "(" + booleanStatement + ") && (" + andedCase + ")";
 285  
                 }
 286  
 
 287  0
                 if (wc.getConstraint() != null && StringUtils.isNotEmpty(booleanStatement)) {
 288  0
                         ruleString = createRule(field, wc.getConstraint(), booleanStatement, view);
 289  
                 }
 290  
 
 291  0
                 if (StringUtils.isNotEmpty(ruleString)) {
 292  0
                         addScriptToPage(view, field, ruleString);
 293  
                 }
 294  0
         }
 295  
         
 296  
 
 297  
 
 298  
         /**
 299  
          * Adds the script to the view to execute on a jQuery document ready event.
 300  
          * 
 301  
          * @param view
 302  
          * @param script
 303  
          */
 304  
         public static void addScriptToPage(View view, AttributeField field, String script) {
 305  0
         String prefixScript = "";
 306  
         
 307  0
         if (field.getOnDocumentReadyScript() != null) {
 308  0
             prefixScript = field.getOnDocumentReadyScript();
 309  
         }
 310  0
         field.setOnDocumentReadyScript(prefixScript + "\n" + "runValidationScript(function(){" + script + "});");
 311  0
         }
 312  
         
 313  
         /**
 314  
          * Determines which fields are being evaluated in a boolean statement, so handlers can be
 315  
          * attached to them if needed, returns these names in a list.
 316  
          * 
 317  
          * @param statement
 318  
          * @return
 319  
          */
 320  
         private static List<String> parseOutFields(String statement){
 321  0
             List<String> fieldNames = new ArrayList<String>();
 322  0
             String[] splits = StringUtils.splitByWholeSeparator(statement, "coerceValue('");
 323  0
             for(String s: splits){
 324  0
                 String fieldName = StringUtils.substringBefore(s, "'");
 325  0
                 fieldNames.add(fieldName);
 326  
             }
 327  0
             return fieldNames;
 328  
         }
 329  
 
 330  
         /**
 331  
          * This method takes in a constraint to apply only when the passed in
 332  
          * booleanStatement is valid. The method will create the necessary addMethod
 333  
          * and addRule jquery validator calls for the rule to be applied to the
 334  
          * field when the statement passed in evaluates to true during runtime and
 335  
          * this field is being validated. Note the use of custom methods for min/max
 336  
          * length/value.
 337  
          * 
 338  
          * @param applyToField
 339  
          *            the field to apply the generated methods and rules to
 340  
          * @param constraint
 341  
          *            the constraint to be applied when the booleanStatement
 342  
          *            evaluates to true during validation
 343  
          * @param booleanStatement
 344  
          *            the booleanstatement in js - should return true when the
 345  
          *            validation rule should be applied
 346  
          * @param view
 347  
          * @return
 348  
          */
 349  
         @SuppressWarnings("boxing")
 350  
         private static String createRule(AttributeField field, Constraint constraint, String booleanStatement, View view) {
 351  0
                 String rule = "";
 352  0
                 int constraintCount = 0;
 353  0
                 if (constraint instanceof BaseConstraint && ((BaseConstraint) constraint).getApplyClientSide()) {
 354  0
                         if (constraint instanceof SimpleConstraint) {
 355  0
                                 if (((SimpleConstraint) constraint).getRequired() != null && ((SimpleConstraint) constraint).getRequired()) {
 356  0
                                         rule = rule + "required: function(element){\nreturn (" + booleanStatement + ");}";
 357  
                                         //special requiredness indicator handling
 358  0
                                         String showIndicatorScript = "";
 359  0
                                         for(String checkedField: parseOutFields(booleanStatement)){
 360  0
                                             showIndicatorScript = showIndicatorScript + 
 361  
                                                 "setupShowReqIndicatorCheck('"+ checkedField +"', '" + field.getBindingInfo().getBindingPath() + "', " + "function(){\nreturn (" + booleanStatement + ");});\n";
 362  
                                         }
 363  0
                                         addScriptToPage(view, field, showIndicatorScript);
 364  
                                         
 365  0
                                         constraintCount++;
 366  
                                 }
 367  0
                                 if (((SimpleConstraint) constraint).getMinLength() != null) {
 368  0
                                         if (constraintCount > 0) {
 369  0
                                                 rule = rule + ",\n";
 370  
                                         }
 371  0
                                         rule = rule + "minLengthConditional: [" + ((SimpleConstraint) constraint).getMinLength()
 372  
                                                         + ", function(){return " + booleanStatement + ";}]";
 373  0
                                         constraintCount++;
 374  
                                 }
 375  0
                                 if (((SimpleConstraint) constraint).getMaxLength() != null) {
 376  0
                                         if (constraintCount > 0) {
 377  0
                                                 rule = rule + ",\n";
 378  
                                         }
 379  0
                                         rule = rule + "maxLengthConditional: [" + ((SimpleConstraint) constraint).getMaxLength()
 380  
                                                         + ", function(){return " + booleanStatement + ";}]";
 381  0
                                         constraintCount++;
 382  
                                 }
 383  
 
 384  0
                                 if (((SimpleConstraint) constraint).getExclusiveMin() != null) {
 385  0
                                         if (constraintCount > 0) {
 386  0
                                                 rule = rule + ",\n";
 387  
                                         }
 388  0
                                         rule = rule + "minExclusive: [" + ((SimpleConstraint) constraint).getExclusiveMin()
 389  
                                                         + ", function(){return " + booleanStatement + ";}]";
 390  0
                                         constraintCount++;
 391  
                                 }
 392  
 
 393  0
                                 if (((SimpleConstraint) constraint).getInclusiveMax() != null) {
 394  0
                                         if (constraintCount > 0) {
 395  0
                                                 rule = rule + ",\n";
 396  
                                         }
 397  0
                                         rule = rule + "maxInclusive: [" + ((SimpleConstraint) constraint).getInclusiveMax()
 398  
                                                         + ", function(){return " + booleanStatement + ";}]";
 399  0
                                         constraintCount++;
 400  
                                 }
 401  
 
 402  0
                                 rule = "jq('[name=\"" + field.getBindingInfo().getBindingPath() + "\"]').rules(\"add\", {" + rule + "\n});";
 403  
                         }
 404  0
                         else if (constraint instanceof ValidCharactersConstraint) {
 405  0
                                 String regexMethod = "";
 406  0
                                 String methodName = "";
 407  0
                                 if(StringUtils.isNotEmpty(((ValidCharactersConstraint)constraint).getValue())) {
 408  0
                                         regexMethod = ClientValidationUtils.getRegexMethodWithBooleanCheck(field, (ValidCharactersConstraint) constraint) + "\n";
 409  0
                                         methodName = "validChar-" + field.getBindingInfo().getBindingPath() + methodKey;
 410  0
                                         methodKey++;
 411  
                                 }
 412  
                                 else {
 413  0
                                         if(StringUtils.isNotEmpty(((ValidCharactersConstraint)constraint).getLabelKey())){
 414  0
                                                 methodName = ((ValidCharactersConstraint)constraint).getLabelKey();
 415  
                                         }
 416  
                                 }
 417  0
                                 if (StringUtils.isNotEmpty(methodName)) {
 418  0
                                         rule = regexMethod + "jq('[name=\"" + field.getBindingInfo().getBindingPath() + "\"]').rules(\"add\", {\n\"" + methodName
 419  
                                                         + "\" : function(element){return (" + booleanStatement + ");}\n});";
 420  
                                 }
 421  0
                         }
 422  0
                         else if (constraint instanceof PrerequisiteConstraint) {
 423  0
                                 processPrerequisiteConstraint(field, (PrerequisiteConstraint) constraint, view, booleanStatement);
 424  
                         }
 425  0
                         else if (constraint instanceof CaseConstraint) {
 426  0
                                 processCaseConstraint(field, view, (CaseConstraint) constraint, booleanStatement);
 427  
                         }
 428  0
                         else if (constraint instanceof MustOccurConstraint) {
 429  0
                                 processMustOccurConstraint(field, view, (MustOccurConstraint) constraint, booleanStatement);
 430  
                         }
 431  
                 }
 432  0
                 return rule;
 433  
         }
 434  
         
 435  
 
 436  
 
 437  
         /**
 438  
          * This method is a simpler version of processPrerequisiteConstraint
 439  
          * 
 440  
          * @see AttributeField#processPrerequisiteConstraint(PrerequisiteConstraint,
 441  
          *      View, String)
 442  
          * @param constraint
 443  
          * @param view
 444  
          */
 445  
         public static void processPrerequisiteConstraint(AttributeField field, PrerequisiteConstraint constraint, View view) {
 446  0
                 processPrerequisiteConstraint(field, constraint, view, "true");
 447  0
         }
 448  
 
 449  
         /**
 450  
          * This method processes a Prerequisite constraint that should be applied
 451  
          * when the booleanStatement passed in evaluates to true.
 452  
          * 
 453  
          * @param constraint
 454  
          *            prerequisiteConstraint
 455  
          * @param view
 456  
          * @param booleanStatement
 457  
          *            the booleanstatement in js - should return true when the
 458  
          *            validation rule should be applied
 459  
          */
 460  
         public static void processPrerequisiteConstraint(AttributeField field, PrerequisiteConstraint constraint, View view, String booleanStatement) {
 461  0
                 if (constraint != null && constraint.getApplyClientSide().booleanValue()) {
 462  0
                     String dependsClass = "dependsOn-" + constraint.getAttributePath();
 463  0
                     String addClass = "jq('[name=\""+ field.getBindingInfo().getBindingPath() + "\"]').addClass('" + dependsClass + "');" +
 464  
                         "jq('[name=\""+ constraint.getAttributePath() + "\"]').addClass('" + "dependsOn-" + field.getBindingInfo().getBindingPath() + "');";
 465  0
                         addScriptToPage(view, field, addClass + getPrerequisiteStatement(field, view, constraint, booleanStatement)
 466  
                                         + getPostrequisiteStatement(field, constraint, booleanStatement));
 467  
                 //special requiredness indicator handling
 468  0
                 String showIndicatorScript = "setupShowReqIndicatorCheck('"+ field.getBindingInfo().getBindingPath() +"', '" + constraint.getAttributePath() + "', " + "function(){\nreturn (coerceValue('" + field.getBindingInfo().getBindingPath() + "') && " + booleanStatement + ");});\n";
 469  0
                 addScriptToPage(view, field, showIndicatorScript);
 470  
                 }
 471  0
         }
 472  
 
 473  
         /**
 474  
          * This method creates the script necessary for executing a prerequisite
 475  
          * rule in which this field occurs after the field specified in the
 476  
          * prerequisite rule - since it requires a specific set of UI logic. Builds
 477  
          * an if statement containing an addMethod jquery validator call. Adds a
 478  
          * "dependsOn" css class to this field for the field specified.
 479  
          * 
 480  
          * @param constraint
 481  
          *            prerequisiteConstraint
 482  
          * @param booleanStatement
 483  
          *            the booleanstatement in js - should return true when the
 484  
          *            validation rule should be applied
 485  
          * @return
 486  
          */
 487  
         private static String getPrerequisiteStatement(AttributeField field, View view, PrerequisiteConstraint constraint, String booleanStatement) {
 488  0
                 methodKey++;
 489  0
                 String message = "";
 490  0
                 if(StringUtils.isEmpty(constraint.getLabelKey())){
 491  0
                         message = configService.getPropertyValueAsString(UifConstants.Messages.VALIDATION_MSG_KEY_PREFIX + "prerequisite");
 492  
                 }
 493  
                 else{
 494  0
                         message = generateMessageFromLabelKey(constraint.getValidationMessageParams(), constraint.getLabelKey());
 495  
                 }
 496  0
                 if(StringUtils.isEmpty(message)){
 497  0
                         message = "prerequisite - No message";
 498  
                 }
 499  
                 else{
 500  0
                         AttributeField requiredField = view.getViewIndex().getAttributeFieldByPath(constraint.getAttributePath());
 501  0
                         if(requiredField != null && StringUtils.isNotEmpty(requiredField.getLabel())){
 502  0
                                 message = MessageFormat.format(message, requiredField.getLabel());
 503  
                         }
 504  
                         else{
 505  0
                                 message = MessageFormat.format(message, configService.getPropertyValueAsString(GENERIC_FIELD_MSG_KEY));
 506  
                         }
 507  
                 }
 508  
                 
 509  
                 // field occurs before case
 510  0
                 String methodName = "prConstraint-" + field.getBindingInfo().getBindingPath()+ methodKey;
 511  0
                 String addClass = "jq('[name=\""+ field.getBindingInfo().getBindingPath() + "\"]').addClass('" + methodName + "');\n";
 512  0
                 String method = "\njQuery.validator.addMethod(\""+ methodName +"\", function(value, element) {\n" +
 513  
                         " if(" + booleanStatement + "){ return (this.optional(element) || (coerceValue('" + constraint.getAttributePath() + "')));}else{return true;} " +
 514  
                         "}, \"" + message + "\");";
 515  
                 
 516  0
                 String ifStatement = "if(occursBefore('" + constraint.getAttributePath() + "','" + field.getBindingInfo().getBindingPath() + 
 517  
                 "')){" + addClass + method + "}";
 518  0
                 return ifStatement;
 519  
         }
 520  
 
 521  
         /**
 522  
          * This method creates the script necessary for executing a prerequisite
 523  
          * rule in which this field occurs before the field specified in the
 524  
          * prerequisite rule - since it requires a specific set of UI logic. Builds
 525  
          * an if statement containing an addMethod jquery validator call.
 526  
          * 
 527  
          * @param constraint
 528  
          *            prerequisiteConstraint
 529  
          * @param booleanStatement
 530  
          *            the booleanstatement in js - should return true when the
 531  
          *            validation rule should be applied
 532  
          * @return
 533  
          */
 534  
         private static String getPostrequisiteStatement(AttributeField field, PrerequisiteConstraint constraint, String booleanStatement) {
 535  
                 // field occurs after case
 536  0
                 String message = "";
 537  0
                 if(StringUtils.isEmpty(constraint.getLabelKey())){
 538  0
                         message = configService.getPropertyValueAsString(UifConstants.Messages.VALIDATION_MSG_KEY_PREFIX + "postrequisite");
 539  
                 }
 540  
                 else{
 541  0
                         message = generateMessageFromLabelKey(constraint.getValidationMessageParams(), constraint.getLabelKey());
 542  
                 }
 543  
                 
 544  0
                 if(StringUtils.isEmpty(constraint.getLabelKey())){
 545  0
                         if(StringUtils.isNotEmpty(field.getLabel())){
 546  0
                                 message = MessageFormat.format(message, field.getLabel());
 547  
                         }
 548  
                         else{
 549  0
                                 message = MessageFormat.format(message, configService.getPropertyValueAsString(GENERIC_FIELD_MSG_KEY));
 550  
                         }
 551  
                         
 552  
                 }
 553  
                 
 554  0
                 String function = "function(element){\n" +
 555  
                         "return (coerceValue('"+ field.getBindingInfo().getBindingPath() + "') && " + booleanStatement + ");}";
 556  0
                 String postStatement = "\nelse if(occursBefore('" + field.getBindingInfo().getBindingPath() + "','" + constraint.getAttributePath() + 
 557  
                         "')){\njq('[name=\""+ constraint.getAttributePath() + 
 558  
                         "\"]').rules(\"add\", { required: \n" + function 
 559  
                         + ", \nmessages: {\nrequired: \""+ message +"\"}});}\n";
 560  
                 
 561  0
                 return postStatement;
 562  
 
 563  
         }
 564  
 
 565  
         /**
 566  
          * This method processes the MustOccurConstraint. The constraint is only
 567  
          * applied when the booleanStatement evaluates to true during validation.
 568  
          * This method creates the addMethod and add rule calls for the jquery
 569  
          * validation plugin necessary for applying this constraint to this field.
 570  
          * 
 571  
          * @param view
 572  
          * @param mc
 573  
          * @param booleanStatement
 574  
          *            the booleanstatement in js - should return true when the
 575  
          *            validation rule should be applied
 576  
          */
 577  
         public static void processMustOccurConstraint(AttributeField field, View view, MustOccurConstraint mc, String booleanStatement) {
 578  0
                 methodKey++;
 579  0
                 mustOccursPathNames = new ArrayList<List<String>>();
 580  
                 // TODO make this show the fields its requiring
 581  0
                 String methodName = "moConstraint-" + field.getBindingInfo().getBindingPath() + methodKey;
 582  0
                 String method = "\njQuery.validator.addMethod(\""+ methodName +"\", function(value, element) {\n" +
 583  
                 " if(" + booleanStatement + "){return (this.optional(element) || ("+ getMustOccurStatement(field, mc) + "));}else{return true;}" +
 584  
                 "}, \"" + getMustOccursMessage(view, mc) +"\");";
 585  0
                 String rule = method + "jq('[name=\""+ field.getBindingInfo().getBindingPath() + "\"]').rules(\"add\", {\n\"" + methodName + "\": function(element){return (" + booleanStatement + ");}\n});";
 586  0
                 addScriptToPage(view, field, rule);
 587  0
         }
 588  
 
 589  
         /**
 590  
          * This method takes in a MustOccurConstraint and returns the statement used
 591  
          * in determining if the must occurs constraint has been satisfied when this
 592  
          * field is validated. Note the use of the mustOccurCheck method. Nested
 593  
          * mustOccurConstraints are ored against the result of the mustOccurCheck by
 594  
          * calling this method recursively.
 595  
          * 
 596  
          * @param constraint
 597  
          * @return
 598  
          */
 599  
         @SuppressWarnings("boxing")
 600  
         private static String getMustOccurStatement(AttributeField field, MustOccurConstraint constraint) {
 601  0
                 String statement = "";
 602  0
                 List<String> attributePaths = new ArrayList<String>();
 603  0
                 if (constraint != null && constraint.getApplyClientSide()) {
 604  0
                         String array = "[";
 605  0
                         if (constraint.getPrerequisiteConstraints() != null) {
 606  0
                                 for (int i = 0; i < constraint.getPrerequisiteConstraints().size(); i++) {
 607  0
                                         field.getControl().addStyleClass("dependsOn-"
 608  
                                                         + constraint.getPrerequisiteConstraints().get(i).getAttributePath());
 609  0
                                         array = array + "'" + constraint.getPrerequisiteConstraints().get(i).getAttributePath() + "'";
 610  0
                                         attributePaths.add(constraint.getPrerequisiteConstraints().get(i).getAttributePath());
 611  0
                                         if (i + 1 != constraint.getPrerequisiteConstraints().size()) {
 612  0
                                                 array = array + ",";
 613  
                                         }
 614  
 
 615  
                                 }
 616  
                         }
 617  0
                         array = array + "]";
 618  0
                         statement = "mustOccurTotal(" + array + ", " + constraint.getMin() + ", " + constraint.getMax() + ")";
 619  
                         //add min to string list
 620  0
                         if(constraint.getMin()!=null){
 621  0
                                 attributePaths.add(constraint.getMin().toString());
 622  
                         }
 623  
                         else{
 624  0
                                 attributePaths.add(null);
 625  
                         }
 626  
                         //add max to string list
 627  0
                         if(constraint.getMax()!=null){
 628  0
                                 attributePaths.add(constraint.getMax().toString());
 629  
                         }
 630  
                         else{
 631  0
                                 attributePaths.add(null);
 632  
                         }
 633  
                         
 634  0
                         mustOccursPathNames.add(attributePaths);
 635  0
                         if(StringUtils.isEmpty(statement)){
 636  0
                                 statement = "0";
 637  
                         }
 638  0
                         if (constraint.getMustOccurConstraints() != null) {
 639  0
                                 for (MustOccurConstraint mc : constraint.getMustOccurConstraints()) {
 640  0
                                         statement = "mustOccurCheck(" + statement + " + " + getMustOccurStatement(field, mc) +
 641  
                                                 ", " + constraint.getMin() + ", " + constraint.getMax() + ")";
 642  
                                 }
 643  
                         }
 644  
                         else{
 645  0
                                 statement = "mustOccurCheck(" + statement +
 646  
                                 ", " + constraint.getMin() + ", " + constraint.getMax() + ")";
 647  
                         }
 648  
                 }
 649  0
                 return statement;
 650  
         }
 651  
 
 652  
         
 653  
         /**
 654  
          * Generates a message for the must occur constraint (if no label key is specified).  
 655  
          * This message is most accurate when must occurs is a single
 656  
          * or double level constraint.  Beyond that, the message will still be accurate but may be confusing for
 657  
          * the user - this auto-generated message however will work in MOST use cases.
 658  
          * 
 659  
          * @param view
 660  
          * @return
 661  
          */
 662  
         private static String getMustOccursMessage(View view, MustOccurConstraint constraint){
 663  0
                 String message = "";
 664  0
                 if(StringUtils.isNotEmpty(constraint.getLabelKey())){
 665  0
                         message = generateMessageFromLabelKey(constraint.getValidationMessageParams(), constraint.getLabelKey());
 666  
                 }
 667  
                 else{
 668  0
                         String and = configService.getPropertyValueAsString(AND_MSG_KEY);
 669  0
                         String or = configService.getPropertyValueAsString(OR_MSG_KEY);
 670  0
                         String all = configService.getPropertyValueAsString(ALL_MSG_KEY);
 671  0
                         String atMost = configService.getPropertyValueAsString(ATMOST_MSG_KEY);
 672  0
                         String genericLabel = configService.getPropertyValueAsString(GENERIC_FIELD_MSG_KEY);
 673  0
                         String mustOccursMsg = configService.getPropertyValueAsString(
 674  
                                 UifConstants.Messages.VALIDATION_MSG_KEY_PREFIX + MUSTOCCURS_MSG_KEY);
 675  
                         //String postfix = configService.getPropertyValueAsString(VALIDATION_MSG_KEY_PREFIX + MUSTOCCURS_POST_MSG_KEY);
 676  0
                         String statement="";
 677  0
                         for(int i=0; i< mustOccursPathNames.size(); i++){
 678  0
                                 String andedString = "";
 679  
                                 
 680  0
                                 List<String> paths = mustOccursPathNames.get(i);
 681  0
                                 if(!paths.isEmpty()){
 682  
                                         //note that the last 2 strings are min and max and rest are attribute paths
 683  0
                                         String min = paths.get(paths.size()-2);
 684  0
                                         String max = paths.get(paths.size()-1);
 685  0
                                         for(int j=0; j<paths.size()-2;j++){
 686  0
                                                 AttributeField field = view.getViewIndex().getAttributeFieldByPath(paths.get(j).trim());
 687  0
                                                 String label = genericLabel;
 688  0
                                                 if(field != null && StringUtils.isNotEmpty(field.getLabel())){
 689  0
                                                         label = field.getLabel();
 690  
                                                 }
 691  0
                                                 if(min.equals(max)){
 692  0
                                                         if(j==0){
 693  0
                                                                 andedString = label;
 694  
                                                         }
 695  0
                                                         else if(j==paths.size()-3){
 696  0
                                                                 andedString = andedString + " " + and + " " + label;
 697  
                                                         }
 698  
                                                         else{
 699  0
                                                                 andedString = andedString + ", " + label;
 700  
                                                         }
 701  
                                                 }
 702  
                                                 else{
 703  0
                                                         andedString = andedString + "<li>" + label + "</li>";
 704  
                                                 }
 705  
                                         }
 706  0
                                         if(min.equals(max)){
 707  0
                                                 andedString = "<li>" + andedString + "</li>";
 708  
                                         }
 709  0
                                         andedString="<ul>" + andedString + "</ul>";
 710  
                                 
 711  0
                                         if(StringUtils.isNotEmpty(min) && StringUtils.isNotEmpty(max) && !min.equals(max)){
 712  0
                                                 andedString = MessageFormat.format(mustOccursMsg, min + "-" + max) + "<br/>" +andedString;
 713  
                                         }
 714  0
                                         else if(StringUtils.isNotEmpty(min) && StringUtils.isNotEmpty(max) && min.equals(max) && i==0){
 715  0
                                                 andedString = MessageFormat.format(mustOccursMsg, all) + "<br/>" +andedString;
 716  
                                         }
 717  0
                                         else if(StringUtils.isNotEmpty(min) && StringUtils.isNotEmpty(max) && min.equals(max) && i!=0){
 718  
                                                 //leave andedString as is
 719  
                                         }
 720  0
                                         else if(StringUtils.isNotEmpty(min)){
 721  0
                                                 andedString = MessageFormat.format(mustOccursMsg, min) + "<br/>" +andedString;
 722  
                                         }
 723  0
                                         else if(StringUtils.isNotEmpty(max)){
 724  0
                                                 andedString = MessageFormat.format(mustOccursMsg, atMost + " " + max) + "<br/>" +andedString;
 725  
                                         }
 726  
                                 }
 727  0
                                 if(StringUtils.isNotEmpty(andedString)){
 728  0
                                         if(i==0){
 729  0
                                                 statement = andedString;
 730  
                                         }
 731  
                                         else{
 732  0
                                                 statement = statement + or.toUpperCase() + andedString;
 733  
                                         }
 734  
                                 }
 735  
                         }
 736  0
                         if(StringUtils.isNotEmpty(statement)){
 737  0
                                 message = statement;
 738  
                         }
 739  
                 }
 740  
                 
 741  0
                 return message;
 742  
         }
 743  
 
 744  
         /**
 745  
          * This method processes all the constraints on the AttributeField passed in and adds all the necessary
 746  
          * jQuery and js required (validator's rules, methods, and messages) to the View's onDocumentReady call.
 747  
          * The result is js that will validate all the constraints contained on an AttributeField during user interaction
 748  
          * with the field using the jQuery validation plugin and custom code.
 749  
          * 
 750  
          * @param attributeField
 751  
          */
 752  
         @SuppressWarnings("boxing")
 753  
         public static void processAndApplyConstraints(AttributeField field, View view) {
 754  0
                 methodKey = 0;
 755  0
                 if ((field.getRequired() != null) && (field.getRequired().booleanValue())) {
 756  0
                         field.getControl().addStyleClass("required");
 757  
                 }
 758  
 
 759  0
                 if (field.getExclusiveMin() != null) {
 760  0
                         if (field.getControl() instanceof TextControl && ((TextControl) field.getControl()).getDatePicker() != null) {
 761  0
                                 ((TextControl) field.getControl()).getDatePicker().getComponentOptions().put("minDate", field.getExclusiveMin());
 762  
                         }
 763  
                         else{
 764  0
                                 String rule = "jq('[name=\""+ field.getBindingInfo().getBindingPath() + "\"]').rules(\"add\", {\n minExclusive: ["+ field.getExclusiveMin() + "]});";
 765  0
                                 addScriptToPage(view, field, rule);
 766  
                         }
 767  
                 }
 768  
 
 769  0
                 if (field.getInclusiveMax() != null) {
 770  0
                         if (field.getControl() instanceof TextControl && ((TextControl) field.getControl()).getDatePicker() != null) {
 771  0
                                 ((TextControl) field.getControl()).getDatePicker().getComponentOptions().put("maxDate", field.getInclusiveMax());
 772  
                         }
 773  
                         else{
 774  0
                                 String rule = "jq('[name=\""+ field.getBindingInfo().getBindingPath() + "\"]').rules(\"add\", {\n maxInclusive: ["+ field.getInclusiveMax() + "]});";
 775  0
                                 addScriptToPage(view, field, rule);
 776  
                         }
 777  
                 }
 778  
 
 779  0
                 if (field.getValidCharactersConstraint() != null && field.getValidCharactersConstraint().getApplyClientSide()) {
 780  0
                         if(StringUtils.isNotEmpty(field.getValidCharactersConstraint().getValue())) {
 781  
                                 // set regex value takes precedence
 782  0
                                 addScriptToPage(view, field, ClientValidationUtils.getRegexMethod(field, field.getValidCharactersConstraint()));
 783  0
                                 field.getControl().addStyleClass("validChar-" + field.getBindingInfo().getBindingPath()+ methodKey);
 784  0
                                 methodKey++;
 785  
                         }
 786  
                         else {
 787  
                                 //blindly assume that if there is no regex value defined that there must be a method by this name
 788  0
                                 if(StringUtils.isNotEmpty(field.getValidCharactersConstraint().getLabelKey())){
 789  0
                                         field.getControl().addStyleClass(field.getValidCharactersConstraint().getLabelKey());
 790  
                                 }
 791  
                         }
 792  
                 }
 793  
 
 794  0
                 if (field.getCaseConstraint() != null && field.getCaseConstraint().getApplyClientSide()) {
 795  0
                         processCaseConstraint(field, view, field.getCaseConstraint(), null);
 796  
                 }
 797  
 
 798  0
                 if (field.getDependencyConstraints() != null) {
 799  0
                         for (PrerequisiteConstraint prc : field.getDependencyConstraints()) {
 800  0
                                 processPrerequisiteConstraint(field, prc, view);
 801  
                         }
 802  
                 }
 803  
 
 804  0
                 if (field.getMustOccurConstraints() != null) {
 805  0
                         for (MustOccurConstraint mc : field.getMustOccurConstraints()) {
 806  0
                                 processMustOccurConstraint(field, view, mc, "true");
 807  
                         }
 808  
                 }
 809  
                 
 810  0
         }
 811  
 
 812  
 }