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