Example usage for org.apache.commons.validator Form getField

List of usage examples for org.apache.commons.validator Form getField

Introduction

In this page you can find the example usage for org.apache.commons.validator Form getField.

Prototype

public Field getField(String fieldName) 

Source Link

Document

Returns the Field with the given name or null if this Form has no such field.

Usage

From source file:cn.com.ihuimobile.test.validate.ValidateExample.java

/**
 * Dumps out the Bean in question and the results of validating it.
 *//*from w ww  .  jav a2s.c o m*/
@SuppressWarnings("unchecked")
public static void printResults(ValidateBean bean, ValidatorResults results, ValidatorResources resources) {

    boolean success = true;

    // Start by getting the form for the current locale and Bean.
    Form form = resources.getForm(Locale.getDefault(), "ValidateBean");

    System.out.println("\n\nValidating:");
    System.out.println(bean);

    // Iterate over each of the properties of the Bean which had messages.
    Iterator<String> propertyNames = results.getPropertyNames().iterator();
    while (propertyNames.hasNext()) {
        String propertyName = propertyNames.next();

        // Get the Field associated with that property in the Form
        Field field = form.getField(propertyName);

        // Look up the formatted name of the field from the Field arg0
        String prettyFieldName = apps.getString(field.getArg(0).getKey());

        // Get the result of validating the property.
        ValidatorResult result = results.getValidatorResult(propertyName);

        // Get all the actions run against the property, and iterate over their names.
        Iterator<String> keys = result.getActions();
        while (keys.hasNext()) {
            String actName = keys.next();

            // Get the Action for that name.
            ValidatorAction action = resources.getValidatorAction(actName);

            // If the result is valid, print PASSED, otherwise print FAILED
            System.out.println(propertyName + "[" + actName + "] ("
                    + (result.isValid(actName) ? "PASSED" : "FAILED") + ")");

            //If the result failed, format the Action's message against the formatted field name
            if (!result.isValid(actName)) {
                success = false;
                String message = apps.getString(action.getMsg());
                Object[] args = { prettyFieldName };
                System.out.println("     Error message will be: " + MessageFormat.format(message, args));

            }
        }
    }
    if (success) {
        System.out.println("FORM VALIDATION PASSED");
    } else {
        System.out.println("FORM VALIDATION FAILED");
    }

}

From source file:alpha.portal.webapp.taglib.LabelTag.java

@Override
public int doStartTag() throws JspException {

    try {/*  w w w .j a  v  a2 s.  c o  m*/
        this.requestContext = new RequestContext((HttpServletRequest) this.pageContext.getRequest());
    } catch (final RuntimeException ex) {
        throw ex;
    } catch (final Exception ex) {
        this.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;

    final ValidatorResources resources = this.getValidatorResources();

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

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

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

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

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

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

    final Errors errors = this.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 = this.getMessageSource().getMessage(this.key, null, locale);
    } catch (final NoSuchMessageException nsm) {
        message = "???" + this.key + "???";
    }

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

    final String cssErrorClass = (this.errorClass != null) ? this.errorClass : "error";
    final StringBuffer label = new StringBuffer();

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

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

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

        if (validationError) {
            label.append("<img class=\"validationWarning\" alt=\"");
            label.append(this.getMessageSource().getMessage("icon.warning", null, locale));
            label.append("\"");

            final String context = ((HttpServletRequest) this.pageContext.getRequest()).getContextPath();

            label.append(" src=\"").append(context);
            label.append(this.getMessageSource().getMessage("icon.warning.img", null, locale));
            label.append("\" />");
        }
    }

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

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

From source file:com.sapienter.jbilling.common.GatewayBL.java

public boolean validate(String name, Object bean) throws ValidatorException {
    // only validate there's no errors already detected
    if (code != RES_CODE_OK) {
        return false;
    }/*from  w  w w .  ja v  a 2  s  . com*/
    boolean success = true;
    ;
    // Tell the validator which bean to validate against.
    validator.setFormName(name);
    validator.setParameter(Validator.BEAN_PARAM, bean);

    ValidatorResults results = null;

    // Run the validation actions against the bean.
    log.info("Validating " + name); // can't print the bean... it put plain credit card numbers in the logs
    results = validator.validate();
    Form form = resources.getForm(Locale.getDefault(), name);
    // Iterate over each of the properties of the Bean which had messages.
    Iterator propertyNames = results.getPropertyNames().iterator();
    while (propertyNames.hasNext()) {
        String propertyName = (String) propertyNames.next();
        // log.debug("name " + propertyName);

        // Get the Field associated with that property in the Form
        Field field = form.getField(propertyName);

        // Look up the formatted name of the field from the Field arg0
        // String prettyFieldName =
        // apps.getString(field.getArg(0).getKey());

        // Get the result of validating the property.
        ValidatorResult result = results.getValidatorResult(propertyName);

        // Get all the actions run against the property, and iterate over
        // their names.
        Map actionMap = result.getActionMap();
        Iterator keys = actionMap.keySet().iterator();
        while (keys.hasNext()) {
            String actName = (String) keys.next();

            // Get the Action for that name.
            ValidatorAction action = resources.getValidatorAction(actName);

            /*
             * If the result is valid, print PASSED, otherwise print FAILED
             * log.debug(propertyName + "[" + actName + "] (" +
             * (result.isValid(actName) ? "PASSED" : "FAILED") + ")");
             */

            // If the result failed, format the Action's message against the
            // formatted field name
            if (!result.isValid(actName)) {
                if (!success) {
                    text += "-";
                } else {
                    success = false;
                    code = RES_CODE_ERROR;
                    subCode = RES_SUB_CODE_ERR_VALIDATION;
                }
                String message = apps.getString(action.getMsg());
                // read the variables
                Map vars = field.getVars();
                // will need some changes to accomodate 'range'
                Object[] args = new Object[2];
                args[0] = propertyName;
                Var var = field.getVar(actName);
                if (var != null) {
                    args[1] = var.getValue();
                }
                text += "Object type " + name + ":" + MessageFormat.format(message, args);
            }
        }
    }
    log.debug("Done. result " + success + " message:" + text);
    return success;
}

From source file:org.apache.commons.validator.example.ValidateExample.java

/**
 * Dumps out the Bean in question and the results of validating it.
 *//*from  w  ww  . j ava  2 s.c  o m*/
public static void printResults(Object bean, ValidatorResults results, ValidatorResources resources) {

    boolean success = true;

    // Start by getting the form for the current locale and Bean.
    Form form = resources.getForm(Locale.getDefault(), "ValidateBean");

    System.out.println("\n\nValidating:");
    System.out.println(bean);

    // Iterate over each of the properties of the Bean which had messages.
    Iterator propertyNames = results.getPropertyNames().iterator();
    while (propertyNames.hasNext()) {
        String propertyName = (String) propertyNames.next();

        // Get the Field associated with that property in the Form
        Field field = form.getField(propertyName);

        // Look up the formatted name of the field from the Field arg0
        String prettyFieldName = apps.getString(field.getArg(0).getKey());

        // Get the result of validating the property.
        ValidatorResult result = results.getValidatorResult(propertyName);

        // Get all the actions run against the property, and iterate over their names.
        Map actionMap = result.getActionMap();
        Iterator keys = actionMap.keySet().iterator();
        while (keys.hasNext()) {
            String actName = (String) keys.next();

            // Get the Action for that name.
            ValidatorAction action = resources.getValidatorAction(actName);

            // If the result is valid, print PASSED, otherwise print FAILED
            System.out.println(propertyName + "[" + actName + "] ("
                    + (result.isValid(actName) ? "PASSED" : "FAILED") + ")");

            //If the result failed, format the Action's message against the formatted field name
            if (!result.isValid(actName)) {
                success = false;
                String message = apps.getString(action.getMsg());
                Object[] args = { prettyFieldName };
                System.out.println("     Error message will be: " + MessageFormat.format(message, args));

            }
        }
    }
    if (success) {
        System.out.println("FORM VALIDATION PASSED");
    } else {
        System.out.println("FORM VALIDATION FAILED");
    }

}

From source file:org.hyperic.util.validator.common.CommonValidator.java

/**
 * Perform all form-specific the validation. All form specific validation
 * is performed and then finally a CommonValidatorException object will be
 * thrown if (AND ONLY IF) validation errors were detected. The exception
 * object will contain a collection of error Strings see
 * {@ref CommonValidatorException}.// w w  w.  j a va  2s. co  m
 *
 * @param validationMappingRes A String containing the name of the
 * mapping resource file.
 * @param formName A String containing the name of the form containing
 * the validation action references.
 * @param beanInstance An instance of the bean to apply validation on.
 * @throws CommonValidatorException - Exception containing collection of
 * messages.
 **/
public void validate(String validationMappingRes, String formName, Object beanInstance)
        throws CommonValidatorException, SAXException {
    InputStream xmlStream = null;
    CommonValidatorException cve = null;
    ValidatorResults results;

    try {
        // Start by setting the "ValidatorResources" object. Its only
        // created if necessary. Contains FormSets stored against locale.
        setValidatorResources(validationMappingRes, beanInstance, xmlStream);

        // Get the form for the current locale and Bean.
        Form form = _validatorResources.getForm(Locale.getDefault(), formName);

        // Instantiate the validator (coordinates the validation
        // while the ValidatorResources implements the validation)
        Validator validator = new Validator(_validatorResources, formName);

        // Tell the validator which bean to validate against.
        validator.setParameter(Validator.BEAN_PARAM, beanInstance);

        // Get the results
        results = validator.validate();

        // Localize a reference for future access.
        setValidatorResults(results);

        // Iterate over each of the properties of the Bean which had messages.
        Iterator propertyNames = results.getPropertyNames().iterator();

        while (propertyNames.hasNext()) {
            // There were errors. Instantiate CVE

            String propertyName = (String) propertyNames.next();

            // Get the Field associated with that property in the Form
            Field field = (Field) form.getField(propertyName);

            // Look up the formatted name of the field from the Field arg0
            String prettyFieldName = _properties.getString(field.getArg(0).getKey());

            // Get the result of validating the property.
            ValidatorResult result = results.getValidatorResult(propertyName);

            // Get all the actions run against the property, and iterate
            // over their names. Check for invalid results.
            Map actionMap = result.getActionMap();
            Iterator keys = actionMap.keySet().iterator();
            while (keys.hasNext()) {
                String actName = (String) keys.next();
                // Get the Action for that name.
                ValidatorAction action = _validatorResources.getValidatorAction(actName);
                if (!result.isValid(actName)) {
                    String message = _properties.getString(action.getMsg());
                    Object[] args = { prettyFieldName };
                    if (cve == null) {
                        cve = new CommonValidatorException();
                    }
                    cve.addMessage(MessageFormat.format(message, args));
                }
            }
        }
    } catch (IOException ex) {
        // Note: This exception shouldn't be reported to user since it
        // wasn't likely caused by user input.
        ex.printStackTrace(); //log this
    } catch (ValidatorException ex) {
        // Note: This exception shouldn't bubble up to user since it
        // wasn't likely caused by user input.
        ex.printStackTrace(); //log this
    } finally {
        // Make sure we close the input stream.
        if (xmlStream != null)
            try {
                xmlStream.close();
            } catch (Exception e) {
            }
        // Lastly, if we had any invalid fields, throw CVE.
        if (cve != null)
            throw cve;
    }
}

From source file:org.openmobster.core.common.validation.ObjectValidator.java

/**
 * Validates the value of the specified Field on the target Object
 * //from www.  j  a v a2s  .c o  m
 * @param object
 * @param fieldName
 * @return a Set of Validation Error Keys
 * @throws ValidationException
 */
public Set<String> validate(Object object, String fieldName) throws ValidationException {
    try {
        Set<String> errorKeys = new HashSet<String>();
        String objectId = object.getClass().getName();

        //Setup the Validator
        Validator validator = new Validator(this.validatorResources, objectId);
        validator.setParameter(Validator.BEAN_PARAM, object);
        validator.setFieldName(fieldName);

        ValidatorResults results = validator.validate();

        Form form = this.validatorResources.getForm(Locale.getDefault(), objectId);
        Iterator propertyNames = results.getPropertyNames().iterator();
        while (propertyNames.hasNext()) {
            String property = (String) propertyNames.next();
            ValidatorResult result = results.getValidatorResult(property);
            Map actionMap = result.getActionMap();
            Iterator keys = actionMap.keySet().iterator();
            while (keys.hasNext()) {
                String actionName = (String) keys.next();
                if (!result.isValid(actionName)) {
                    Field field = form.getField(property);
                    Arg[] args = field.getArgs(actionName);
                    if (args != null) {
                        for (int i = 0; i < args.length; i++) {
                            errorKeys.add(args[i].getKey());
                        }
                    }
                }
            }
        }

        return errorKeys;
    } catch (Exception e) {
        log.error(this, e);
        throw new ValidationException(e);
    }
}

From source file:org.openmobster.core.common.validation.ObjectValidator.java

/**
 * Fully validates all the Fields of the specified Object
 * //from  w ww .j a  v  a 2 s.co  m
 * @param object
 * @return a Map of Fields to their corresponding Validation Error Keys
 * 
 * @throws ValidationException
 */
public Map<String, String[]> validate(Object object) throws ValidationException {
    try {
        Map<String, String[]> errorKeys = new HashMap<String, String[]>();
        String objectId = object.getClass().getName();

        //Setup the Validator
        Validator validator = new Validator(this.validatorResources, objectId);
        validator.setParameter(Validator.BEAN_PARAM, object);

        ValidatorResults results = validator.validate();

        Form form = this.validatorResources.getForm(Locale.getDefault(), objectId);
        Iterator propertyNames = results.getPropertyNames().iterator();
        while (propertyNames.hasNext()) {
            Set<String> cour = new HashSet<String>();
            String property = (String) propertyNames.next();
            ValidatorResult result = results.getValidatorResult(property);
            Map actionMap = result.getActionMap();
            Iterator keys = actionMap.keySet().iterator();
            boolean errorFound = false;
            while (keys.hasNext()) {
                String actionName = (String) keys.next();
                if (!result.isValid(actionName)) {
                    Field field = form.getField(property);
                    Arg[] args = field.getArgs(actionName);
                    if (args != null) {
                        for (int i = 0; i < args.length; i++) {
                            cour.add(args[i].getKey());
                            errorFound = true;
                        }
                    }
                }
            }
            if (errorFound) {
                errorKeys.put(property, cour.toArray(new String[cour.size()]));
            }
        }

        return errorKeys;
    } catch (Exception e) {
        log.error(this, e);
        throw new ValidationException(e);
    }
}

From source file:org.openmrs.contrib.metadatarepository.webapp.taglib.LabelTag.java

public int doStartTag() throws JspException {

    try {//from  ww w .ja va  2 s  .  c om
        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";
    StringBuffer label = new StringBuffer();

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

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

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

        if (validationError) {
            label.append("<img class=\"validationWarning\" alt=\"");
            label.append(getMessageSource().getMessage("icon.warning", null, locale));
            label.append("\"");

            String context = ((HttpServletRequest) pageContext.getRequest()).getContextPath();

            label.append(" src=\"").append(context);
            label.append(getMessageSource().getMessage("icon.warning.img", null, locale));
            label.append("\" />");
        }
    }

    // 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);
}

From source file:org.seasar.struts.customizer.ActionCustomizerTest.java

/**
 * @throws Exception/*from   w  w w  .j  a va  2  s  .  c  o  m*/
 */
public void testRegisterValidator() throws Exception {
    Map<String, Form> forms = new HashMap<String, Form>();
    Form form = new Form();
    forms.put("execute", form);
    Form form2 = new Form();
    forms.put("execute2", form2);
    Field field = BbbAction.class.getDeclaredField("hoge");
    Required r = field.getAnnotation(Required.class);
    Map<String, Object> props = AnnotationUtil.getProperties(r);
    customizer.registerValidator("hoge", "required", props, validatorResources, forms);
    assertNotNull(form.getField("hoge"));
    assertNotNull(form2.getField("hoge"));
}

From source file:org.seasar.struts.customizer.ActionCustomizerTest.java

/**
 * @throws Exception//  ww w  .  ja v a 2 s.  co m
 */
public void testRegisterValidator_target() throws Exception {
    Map<String, Form> forms = new HashMap<String, Form>();
    Form form = new Form();
    forms.put("execute", form);
    Form form2 = new Form();
    forms.put("execute2", form2);
    Field field = BbbAction.class.getDeclaredField("hoge2");
    Validwhen v = field.getAnnotation(Validwhen.class);
    Map<String, Object> props = AnnotationUtil.getProperties(v);
    customizer.registerValidator("hoge2", "validwhen", props, validatorResources, forms);
    assertNotNull(form.getField("hoge2"));
    assertNull(form2.getField("hoge2"));
}