/**
  * Iterate over the validation result to check for any validation failure. For the very first
  * validation failure, it reads the oneinc-resource.properties encapsulated in member variable
  * apps and set the user friendly message along with the IRC and throws the
  * OneIncValidationException.
  *
  * @param bean - Bean to be validated
  * @param results - contains the validation result
  * @param resources2 - ValidatorResources object prepared for validation-rules.xml
  * @param form - contains the mapping for field and their validation rule.
  * @throws CWValidationException - if validation gets fail.
  */
 @SuppressWarnings({"unchecked", "deprecation"})
 private void checkResults(
     Serializable bean, ValidatorResults results, ValidatorResources resources2, Form form)
     throws CWValidationException {
   Iterator propertyNames = results.getPropertyNames().iterator();
   while (propertyNames.hasNext()) {
     String propertyName = (String) propertyNames.next();
     ValidatorResult result = results.getValidatorResult(propertyName);
     Map actionMap = result.getActionMap();
     Iterator keys = actionMap.keySet().iterator();
     Field field = form.getField(propertyName);
     String prettyFieldName = apps.getString(field.getArg(0).getKey());
     while (keys.hasNext()) {
       String actName = (String) keys.next();
       ValidatorAction action = resources.getValidatorAction(actName);
       if (!result.isValid(actName)) {
         String message = apps.getString(action.getMsg());
         Object[] args = {prettyFieldName};
         String formatMsg = MessageFormat.format(message, args);
         int colonIndex = formatMsg.indexOf(',');
         String imfResponseCode = null;
         String msg = null;
         if (colonIndex > 0) {
           imfResponseCode = formatMsg.substring(0, colonIndex);
           msg = formatMsg.substring(colonIndex);
         }
         throw new CWValidationException(msg, imfResponseCode);
       }
     }
   }
 }
Beispiel #2
0
  /**
   * Gets the message arguments based on the current <code>ValidatorAction</code> and <code>Field
   * </code>.
   *
   * @param actionName action name
   * @param messages message resources
   * @param locale the locale
   * @param field the validator field
   */
  public static String[] getArgs(
      String actionName, MessageResources messages, Locale locale, Field field) {

    String[] argMessages = new String[4];

    Arg[] args =
        new Arg[] {
          field.getArg(actionName, 0),
          field.getArg(actionName, 1),
          field.getArg(actionName, 2),
          field.getArg(actionName, 3)
        };

    for (int i = 0; i < args.length; i++) {
      if (args[i] == null) {
        continue;
      }

      if (args[i].isResource()) {
        argMessages[i] = getMessage(messages, locale, args[i].getKey());
      } else {
        argMessages[i] = args[i].getKey();
      }
    }

    return argMessages;
  }
Beispiel #3
0
  /**
   * Validates that two fields match.
   *
   * @param bean
   * @param va
   * @param field
   * @param errors
   * @param request
   * @return boolean
   */
  public static boolean validateTwoFields(
      Object bean,
      ValidatorAction va,
      Field field,
      ActionMessages errors,
      HttpServletRequest request) {
    String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    String sProperty2 = field.getVarValue("secondProperty");
    String value2 = ValidatorUtils.getValueAsString(bean, sProperty2);

    if (!GenericValidator.isBlankOrNull(value)) {
      try {
        if (!value.equals(value2)) {
          errors.add(field.getKey(), Resources.getActionMessage(request, va, field));

          return false;
        }
      } catch (Exception e) {
        errors.add(field.getKey(), Resources.getActionMessage(request, va, field));

        return false;
      }
    }

    return true;
  }
Beispiel #4
0
  /**
   * Gets the locale sensitive message based on the <code>ValidatorAction</code> message and the
   * <code>Field</code>'s arg objects.
   *
   * @param messages The Message resources
   * @param locale The locale
   * @param va The Validator Action
   * @param field The Validator Field
   */
  public static String getMessage(
      MessageResources messages, Locale locale, ValidatorAction va, Field field) {

    String args[] = getArgs(va.getName(), messages, locale, field);
    String msg = field.getMsg(va.getName()) != null ? field.getMsg(va.getName()) : va.getMsg();

    return messages.getMessage(locale, msg, args);
  }
Beispiel #5
0
  public static boolean validate(
      Object bean,
      ValidatorAction va,
      Field field,
      ActionMessages errors,
      HttpServletRequest request,
      ServletContext application) {

    String valueString = ValidatorUtils.getValueAsString(bean, field.getProperty());

    String sProperty2 = ValidatorUtils.getValueAsString(bean, field.getVarValue("month"));
    String sProperty3 = ValidatorUtils.getValueAsString(bean, field.getVarValue("day"));

    if (((valueString == null) && (sProperty2 == null) && (sProperty3 == null))
        || ((valueString.length() == 0)
            && (sProperty2.length() == 0)
            && (sProperty3.length() == 0))) {
      // errors.add(field.getKey(),Resources.getActionError(request, va,
      // field));
      return true;
    }

    Integer year = null;
    Integer month = null;
    Integer day = null;

    try {
      year = new Integer(valueString);
      month = new Integer(sProperty2);
      day = new Integer(sProperty3);
    } catch (NumberFormatException e) {
      errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
      return false;
    }

    if (!GenericValidator.isBlankOrNull(valueString)) {
      if (!Data.validDate(day, month, year)
          || year == null
          || month == null
          || day == null
          || year.intValue() < 1
          || month.intValue() < 0
          || day.intValue() < 1) {
        errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
      }

      return false;
    }

    return true;
  }
Beispiel #6
0
  /**
   * Gets the <code>ActionMessage</code> based on the <code>ValidatorAction</code> message and the
   * <code>Field</code>'s arg objects.
   *
   * @param request the servlet request
   * @param va Validator action
   * @param field the validator Field
   */
  public static ActionMessage getActionMessage(
      HttpServletRequest request, ValidatorAction va, Field field) {

    String args[] =
        getArgs(
            va.getName(),
            getMessageResources(request),
            RequestUtils.getUserLocale(request, null),
            field);

    String msg = field.getMsg(va.getName()) != null ? field.getMsg(va.getName()) : va.getMsg();

    return new ActionMessage(msg, args);
  }
  protected void setUp() {
    field = new Field();
    field.setProperty(BIG_DECIMAL_PROPERTY);

    oldConverter = ConvertUtils.lookup(BigDecimal.class);
    ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
  }
  public void testValidateBigDecimalRange() {
    field.addVar(min);
    field.addVar(max);

    Map map = new HashMap();
    map.put(BIG_DECIMAL_PROPERTY, null);
    assertTrue(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "");
    assertTrue(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "-1");
    assertFalse(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "0");
    assertFalse(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "0.1");
    assertTrue(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "1");
    assertTrue(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "10.1");
    assertTrue(BasicValidator.validateBigDecimalRange(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "10.1000000000000001");
    assertFalse(BasicValidator.validateBigDecimalRange(map, field));
  }
Beispiel #9
0
  // this validator is only valid when used in year field
  public static boolean threeArgsDate(
      Object bean,
      ValidatorAction va,
      Field field,
      ActionMessages errors,
      HttpServletRequest request,
      ServletContext application) {

    String valueString1 = ValidatorUtils.getValueAsString(bean, field.getProperty());

    String sProperty2 = ValidatorUtils.getValueAsString(bean, field.getVarValue("month"));
    String sProperty3 = ValidatorUtils.getValueAsString(bean, field.getVarValue("day"));

    if (((valueString1 == null) && (sProperty2 == null) && (sProperty3 == null))
        || ((valueString1.length() == 0)
            && (sProperty2.length() == 0)
            && (sProperty3.length() == 0))) {
      // errors.add(field.getKey(),Resources.getActionError(request, va,
      // field));
      return true;
    }

    Integer year = null;
    Integer month = null;
    Integer day = null;

    try {
      year = new Integer(valueString1);
      month = new Integer(sProperty2);
      day = new Integer(sProperty3);
    } catch (NumberFormatException e) {
      errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
      return false;
    }
    String date = new String(day.toString() + "/" + month.toString() + "/" + year);
    String datePattern = "dd/MM/yyyy";
    if (!GenericValidator.isDate(date, datePattern, false)) {
      errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
      return false;
    }
    return true;
  }
  /**
   * Validates that two fields match.
   *
   * @param bean
   * @param va
   * @param field
   * @param errors
   */
  public static boolean validateTwoFields(
      Object bean, ValidatorAction va, Field field, Errors errors) {
    String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    String sProperty2 = field.getVarValue("secondProperty");
    String value2 = ValidatorUtils.getValueAsString(bean, sProperty2);

    if (!GenericValidator.isBlankOrNull(value)) {
      try {
        if (!value.equals(value2)) {
          FieldChecks.rejectValue(errors, field, va);
          return false;
        }
      } catch (Exception e) {
        FieldChecks.rejectValue(errors, field, va);
        return false;
      }
    }

    return true;
  }
Beispiel #11
0
  /**
   * Extracts the value of the given bean. If the bean is <code>null</code>, the returned value is
   * also <code>null</code>. If the bean is a <code>String</code> then the bean itself is returned.
   * In all other cases, the <code>ValidatorUtils</code> class is used to extract the bean value
   * using the <code>Field</code> object supplied.
   *
   * @see ValidatorUtils#getValueAsString(Object, String)
   */
  protected static String extractValue(Object bean, Field field) {
    String value = null;

    if (bean == null) {
      return null;
    } else if (bean instanceof String) {
      value = (String) bean;
    } else {
      value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    }

    return value;
  }
Beispiel #12
0
  /**
   * Gets the <code>ActionMessage</code> based on the <code>ValidatorAction</code> message and the
   * <code>Field</code>'s arg objects.
   *
   * @param validator the Validator
   * @param request the servlet request
   * @param va Validator action
   * @param field the validator Field
   */
  public static ActionMessage getActionMessage(
      Validator validator, HttpServletRequest request, ValidatorAction va, Field field) {

    Msg msg = field.getMessage(va.getName());
    if (msg != null && !msg.isResource()) {
      return new ActionMessage(msg.getKey(), false);
    }

    String msgKey = null;
    String msgBundle = null;
    if (msg == null) {
      msgKey = va.getMsg();
    } else {
      msgKey = msg.getKey();
      msgBundle = msg.getBundle();
    }

    if (msgKey == null || msgKey.length() == 0) {
      return new ActionMessage("??? " + va.getName() + "." + field.getProperty() + " ???", false);
    }

    ServletContext application =
        (ServletContext) validator.getParameterValue(SERVLET_CONTEXT_PARAM);
    MessageResources messages = getMessageResources(application, request, msgBundle);
    Locale locale = RequestUtils.getUserLocale(request, null);

    Arg[] args = field.getArgs(va.getName());
    String[] argValues = getArgValues(application, request, messages, locale, args);

    ActionMessage actionMessage = null;
    if (msgBundle == null) {
      actionMessage = new ActionMessage(msgKey, argValues);
    } else {
      String message = messages.getMessage(locale, msgKey, argValues);
      actionMessage = new ActionMessage(message, false);
    }
    return actionMessage;
  }
Beispiel #13
0
  /**
   * Gets the <code>Locale</code> sensitive value based on the key passed in.
   *
   * @param application the servlet context
   * @param request the servlet request
   * @param defaultMessages The default Message resources
   * @param locale The locale
   * @param va The Validator Action
   * @param field The Validator Field
   */
  public static String getMessage(
      ServletContext application,
      HttpServletRequest request,
      MessageResources defaultMessages,
      Locale locale,
      ValidatorAction va,
      Field field) {

    Msg msg = field.getMessage(va.getName());
    if (msg != null && !msg.isResource()) {
      return msg.getKey();
    }

    String msgKey = null;
    String msgBundle = null;
    MessageResources messages = defaultMessages;
    if (msg == null) {
      msgKey = va.getMsg();
    } else {
      msgKey = msg.getKey();
      msgBundle = msg.getBundle();
      if (msg.getBundle() != null) {
        messages = getMessageResources(application, request, msg.getBundle());
      }
    }

    if (msgKey == null || msgKey.length() == 0) {
      return "??? " + va.getName() + "." + field.getProperty() + " ???";
    }

    // Get the arguments
    Arg[] args = field.getArgs(va.getName());
    String[] argValues = getArgValues(application, request, messages, locale, args);

    // Return the message
    return messages.getMessage(locale, msgKey, argValues);
  }
Beispiel #14
0
  /**
   * Validates that two fields match.
   *
   * @param bean
   * @param va
   * @param field
   * @param errors
   */
  public static boolean validateTwoFields(
      Object bean, ValidatorAction va, Field field, Errors errors) {
    String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    String sProperty2 = field.getVarValue("equalTo");
    String value2 = ValidatorUtils.getValueAsString(bean, sProperty2);
    if (value == null && value2 == null) {
      return true;
    } else if (value != null && value2 == null) {
      return false;
    } else if (value == null && value2 != null) {
      return false;
    }
    try {
      if (!value.equals(value2)) {
        FieldChecks.rejectValue(errors, field, va);
        return false;
      }
    } catch (Exception e) {
      FieldChecks.rejectValue(errors, field, va);
      return false;
    }

    return true;
  }
Beispiel #15
0
  public void testValidateMax() {
    field.addVar(max);

    Map map = new HashMap();
    map.put(BIG_DECIMAL_PROPERTY, null);
    assertTrue(BasicValidator.validateMax(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "");
    assertTrue(BasicValidator.validateMax(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "1");
    assertTrue(BasicValidator.validateMax(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "10.1");
    assertTrue(BasicValidator.validateMax(map, field));

    map.put(BIG_DECIMAL_PROPERTY, "10.1000000000000001");
    assertFalse(BasicValidator.validateMax(map, field));
  }
Beispiel #16
0
  /**
   * Checks if the field matches the boolean expression specified in <code>test</code> parameter.
   *
   * @param bean The bean validation is being performed on.
   * @param va The <code>ValidatorAction</code> that is currently being performed.
   * @param field The <code>Field</code> object associated with the current field being validated.
   * @param errors The <code>ActionMessages</code> object to add errors to if any validation errors
   *     occur.
   * @param request Current request object.
   * @return <code>true</code> if meets stated requirements, <code>false</code> otherwise.
   */
  public static boolean validateValidWhen(
      Object bean,
      ValidatorAction va,
      Field field,
      ActionMessages errors,
      Validator validator,
      HttpServletRequest request) {
    Object form = validator.getParameterValue(Validator.BEAN_PARAM);
    String value = null;
    boolean valid = false;
    int index = -1;

    if (field.isIndexed()) {
      String key = field.getKey();

      final int leftBracket = key.indexOf("[");
      final int rightBracket = key.indexOf("]");

      if ((leftBracket > -1) && (rightBracket > -1)) {
        index = Integer.parseInt(key.substring(leftBracket + 1, rightBracket));
      }
    }

    if (isString(bean)) {
      value = (String) bean;
    } else {
      value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    }

    String test = null;

    try {
      test = Resources.getVarValue("test", field, validator, request, true);
    } catch (IllegalArgumentException ex) {
      String logErrorMsg =
          sysmsgs.getMessage(
              "validation.failed",
              "validwhen",
              field.getProperty(),
              validator.getFormName(),
              ex.toString());

      log.error(logErrorMsg);

      String userErrorMsg = sysmsgs.getMessage("system.error");

      errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));

      return false;
    }

    // Create the Lexer
    ValidWhenLexer lexer = null;

    try {
      lexer = new ValidWhenLexer(new StringReader(test));
    } catch (Exception ex) {
      String logErrorMsg = "ValidWhenLexer Error for field ' " + field.getKey() + "' - " + ex;

      log.error(logErrorMsg);

      String userErrorMsg = sysmsgs.getMessage("system.error");

      errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));

      return false;
    }

    // Create the Parser
    ValidWhenParser parser = null;

    try {
      parser = new ValidWhenParser(lexer);
    } catch (Exception ex) {
      String logErrorMsg = "ValidWhenParser Error for field ' " + field.getKey() + "' - " + ex;

      log.error(logErrorMsg);

      String userErrorMsg = sysmsgs.getMessage("system.error");

      errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));

      return false;
    }

    parser.setForm(form);
    parser.setIndex(index);
    parser.setValue(value);

    try {
      parser.expression();
      valid = parser.getResult();
    } catch (Exception ex) {
      String logErrorMsg = "ValidWhen Error for field ' " + field.getKey() + "' - " + ex;

      log.error(logErrorMsg);

      String userErrorMsg = sysmsgs.getMessage("system.error");

      errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));

      return false;
    }

    if (!valid) {
      errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));

      return false;
    }

    return true;
  }
Beispiel #17
0
  public int doStartTag() throws JspException {

    try {
      this.requestContext = new RequestContext((HttpServletRequest) this.pageContext.getRequest());
    } catch (RuntimeException ex) {
      throw ex;
    } catch (Exception ex) {
      pageContext.getServletContext().log("Exception in custom tag", ex);
    }

    // Look up this key to see if its a field of the current form
    boolean requiredField = false;
    boolean validationError = false;

    ValidatorResources resources = getValidatorResources();

    Locale locale = pageContext.getRequest().getLocale();

    if (locale == null) {
      locale = Locale.getDefault();
    }

    // get the name of the bean from the key
    String formName = key.substring(0, key.indexOf('.'));
    String fieldName = key.substring(formName.length() + 1);

    if (resources != null) {
      Form form = resources.getForm(locale, formName);

      if (form != null) {
        Field field = form.getField(fieldName);

        if (field != null) {
          if (field.isDependency("required") || field.isDependency("validwhen")) {
            requiredField = true;
          }
        }
      }
    }

    Errors errors = requestContext.getErrors(formName, false);
    List fes = null;
    if (errors != null) {
      fes = errors.getFieldErrors(fieldName);
      // String errorMsg = getErrorMessages(fes);
    }

    if (fes != null && fes.size() > 0) {
      validationError = true;
    }

    // Retrieve the message string we are looking for
    String message = null;
    try {
      message = getMessageSource().getMessage(key, null, locale);
    } catch (NoSuchMessageException nsm) {
      message = "???" + key + "???";
    }

    String cssClass = null;
    if (styleClass != null) {
      cssClass = styleClass;
    } else if (requiredField) {
      cssClass = "required";
    }

    String cssErrorClass = (errorClass != null) ? errorClass : "error";
    StringBuilder label = new StringBuilder();

    if ((message == null) || "".equals(message.trim())) {
      label.append("");
    } else {
      label.append("<label for=\"").append(fieldName).append("\"");

      if (cssClass != null) {
        label.append(" class=\"").append(cssClass);
        if (validationError) {
          label.append(" ").append(cssErrorClass);
        }
      }

      label.append("\">").append(message);
      label.append((requiredField) ? " <span class=\"required\">*</span>" : "");
      label.append((colon) ? ":" : "");
      label.append("</label>");
    }

    // Print the retrieved message to our output writer
    try {
      writeMessage(label.toString());
    } catch (IOException io) {
      io.printStackTrace();
      throw new JspException("Error writing label: " + io.getMessage());
    }

    // Continue processing this page
    return (SKIP_BODY);
  }