Example usage for org.apache.commons.validator Validator setParameter

List of usage examples for org.apache.commons.validator Validator setParameter

Introduction

In this page you can find the example usage for org.apache.commons.validator Validator setParameter.

Prototype

public void setParameter(String parameterClassName, Object parameterValue) 

Source Link

Document

Set a parameter of a pluggable validation method.

Usage

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

/**
 * This is the main method that will be called to initialize the Validator, create some sample beans, and
 * run the Validator against them./*from   w  w  w.ja  v  a2 s  .  co m*/
 */
@Test
public void mainTest() throws ValidatorException, IOException, SAXException {

    InputStream in = null;
    ValidatorResources resources = null;

    try {

        // Create a new instance of a ValidatorResource, then get a stream
        // handle on the XML file with the actions in it, and initialize the
        // resources from it.  This would normally be done by a servlet
        // run during JSP initialization or some other application-startup
        // routine.
        in = ValidateExample.class.getResourceAsStream("validator-example.xml");
        resources = new ValidatorResources(in);

    } finally {
        // Make sure we close the input stream.
        if (in != null) {
            in.close();
        }
    }

    // Create a test bean to validate against.
    ValidateBean bean = new ValidateBean();

    // Create a validator with the ValidateBean actions for the bean
    // we're interested in.
    Validator validator = new Validator(resources, "ValidateBean");

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

    ValidatorResults results = null;

    // Run the validation actions against the bean.  Since all of the properties
    // are null, we expect them all to error out except for street2, which has
    // no validations (it's an optional property)

    results = validator.validate();
    System.out.println(results);
    printResults(bean, results, resources);

    // Now set all the required properties, but make the age a non-integer.
    // You'll notice that age will pass the required test, but fail the int
    // test.
    bean.setLastName("Tester");
    bean.setFirstName("John");
    bean.setStreet1("1 Test Street");
    bean.setCity("Testville");
    bean.setState("TE");
    bean.setPostalCode("12345");
    bean.setAge("Too Old");
    results = validator.validate();
    printResults(bean, results, resources);

    // Now only report failed fields
    validator.setOnlyReturnErrors(true);
    results = validator.validate();
    printResults(bean, results, resources);

    // Now everything should pass.
    validator.setOnlyReturnErrors(false);
    bean.setAge("123");
    results = validator.validate();
    printResults(bean, results, resources);
}

From source file:jp.terasoluna.fw.validation.springmodules.DefaultValidatorFactoryEx.java

/**
 * Validator??/*w  ww  .  ja va 2s  . c  o  m*/
 * 
 * @param beanName ?JavaBean????
 * @param bean ?JavaBean
 * @param errors Spring?
 * @return Validator
 */
@Override
public Validator getValidator(String beanName, Object bean, Errors errors) {
    Validator validator = new CommonsValidatorEx(getValidatorResources(), beanName);

    // BindException??Validator??
    SpringValidationErrors commonErrors = createSpringValidationErrors();
    commonErrors.setErrors(errors);
    validator.setParameter(TERASOLUNA_ERRORS_KEY, commonErrors);

    validator.setParameter(Validator.BEAN_PARAM, bean);
    return validator;
}

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

/**
 * This is the main method that will be called to initialize the Validator, create some sample beans, and
 * run the Validator against them./*  ww  w .  j a  v  a 2  s .  com*/
 */
public static void main(String[] args) throws ValidatorException, IOException, SAXException {

    InputStream in = null;
    ValidatorResources resources = null;

    try {

        // Create a new instance of a ValidatorResource, then get a stream
        // handle on the XML file with the actions in it, and initialize the
        // resources from it.  This would normally be done by a servlet
        // run during JSP initialization or some other application-startup
        // routine.
        in = ValidateExample.class.getResourceAsStream("validator-example.xml");
        resources = new ValidatorResources(in);

    } finally {
        // Make sure we close the input stream.
        if (in != null) {
            in.close();
        }
    }

    // Create a test bean to validate against.
    //ValidateBean bean = new ValidateBean();
    LazyDynaClass dynaClass = new LazyDynaClass();
    dynaClass.add("lastName", String.class);
    dynaClass.add("firstName", String.class);
    dynaClass.add("street1", String.class);
    dynaClass.add("city", String.class);
    dynaClass.add("state", String.class);
    dynaClass.add("postalCode", String.class);
    dynaClass.add("age", String.class);
    LazyDynaBean dynaBean = new LazyDynaBean(dynaClass);

    // Create a validator with the ValidateBean actions for the bean
    // we're interested in.
    Validator validator = new Validator(resources, "ValidateBean");

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

    ValidatorResults results = null;

    // Run the validation actions against the bean.  Since all of the properties
    // are null, we expect them all to error out except for street2, which has
    // no validations (it's an optional property)

    results = validator.validate();
    printResults(dynaBean, results, resources);

    // Now set all the required properties, but make the age a non-integer.
    // You'll notice that age will pass the required test, but fail the int
    // test.
    dynaBean.set("lastName", "Tester");
    dynaBean.set("firstName", "John");
    dynaBean.set("street1", "1 Test Street");
    dynaBean.set("city", "Testville");
    dynaBean.set("state", "TE");
    dynaBean.set("postalCode", "12345");
    dynaBean.set("age", "Too Old");
    results = validator.validate();
    printResults(dynaBean, results, resources);

    // Now only report failed fields
    validator.setOnlyReturnErrors(true);
    results = validator.validate();
    printResults(dynaBean, results, resources);

    // Now everything should pass.
    validator.setOnlyReturnErrors(false);
    dynaBean.set("age", "123");
    results = validator.validate();
    printResults(dynaBean, results, resources);
}

From source file:org.apache.struts.validator.Resources.java

/**
 * Initialize the <code>Validator</code> to perform validation.
 *
 * @param key         The key that the validation rules are under (the
 *                    form elements name attribute).
 * @param bean        The bean validation is being performed on.
 * @param application servlet context//from w ww.  j a  v a  2 s . co m
 * @param request     The current request object.
 * @param errors      The object any errors will be stored in.
 * @param page        This in conjunction with  the page property of a
 *                    <code>Field<code> can control the processing of
 *                    fields.  If the field's page is less than or equal
 *                    to this page value, it will be processed.
 */
public static Validator initValidator(String key, Object bean, ServletContext application,
        HttpServletRequest request, ActionMessages errors, int page) {
    ValidatorResources resources = Resources.getValidatorResources(application, request);

    Locale locale = RequestUtils.getUserLocale(request, null);

    Validator validator = new Validator(resources, key);

    validator.setUseContextClassLoader(true);

    validator.setPage(page);

    validator.setParameter(SERVLET_CONTEXT_PARAM, application);
    validator.setParameter(HTTP_SERVLET_REQUEST_PARAM, request);
    validator.setParameter(Validator.LOCALE_PARAM, locale);
    validator.setParameter(ACTION_MESSAGES_PARAM, errors);
    validator.setParameter(Validator.BEAN_PARAM, bean);

    return validator;
}

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}./*from w  ww. j  a va  2s .c o  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.megatome.frame2.validator.CommonsValidatorWrapper.java

/**
 * Method to be called by the CommonsValidatorEvent class. signature will be
 * modified.//  www  . j a v  a 2  s  .  c om
 */
public static void validate(String beanName, Object o, Errors errors) {
    try {
        Validator validator = new Validator(validatorResources, beanName);
        // add the name bean to the validator as a resource
        // for the validations to be performed on.
        validator.setParameter(Validator.BEAN_PARAM, o);
        validator.setParameter(Globals.ERRORS_KEY, errors);

        validator.validate();
    } catch (ValidatorException e) {
        LOGGER.info("Error validating HttpEvent " + beanName + " : " + e); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (IllegalArgumentException e) {
        LOGGER.warn("Error validating: " + e.getMessage()); //$NON-NLS-1$
    }

}

From source file:org.megatome.frame2.validator.TestCommonsFieldValidator.java

License:asdf

private Errors setupAndRunValidate(final CommonsValidatorBean testBean, final String fieldBeanName) {
    // Add an error to verify the error is passed in..
    final Errors errors = ErrorsFactory.newInstance();
    errors.add("seed", "dude"); //$NON-NLS-1$ //$NON-NLS-2$

    final Validator validator = new Validator(this.validatorResources, fieldBeanName);
    // add the name bean to the validator as a resource
    // for the validations to be performed on.
    validator.setParameter(Validator.BEAN_PARAM, testBean);
    validator.setParameter(Globals.ERRORS_KEY, errors);

    // Get results of the validation.
    try {// w w  w .  j a  va2  s  .c o  m
        validator.validate();
    } catch (final ValidatorException e) {
        fail();
    }
    return errors;
}

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

/**
 * Validates the value of the specified Field on the target Object
 * /*w  ww  .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
 * /*w  ww.j  a  v  a2  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.springmodules.commons.validator.DefaultValidatorFactory.java

/**
 * Gets a new instance of a <code>org.apache.commons.validator.Validator</code> for the given bean.
 *
 * @param beanName The name of the bean for which this <code>Validator</code> will be created
 * @see org.apache.commons.validator.Validator
 *///from  w  w  w . ja  v  a 2s  .co m
public Validator getValidator(String beanName, Object bean, Errors errors) {
    System.out.println("[getValidator] beanName = " + beanName);
    System.out.println("[getValidator] bean = " + bean);
    System.out.println("[getValidator] errors = " + errors);
    Validator validator = new Validator(validatorResources, beanName);
    validator.setParameter(ERRORS_KEY, errors);
    validator.setParameter(Validator.BEAN_PARAM, bean);
    return validator;
}