List of usage examples for org.apache.commons.validator Validator validate
public ValidatorResults validate() throws IOException
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 ww w. ja va 2 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:com.sapienter.jbilling.client.order.NewOrderDTOForm.java
/** * Manual validation for the order review page. * This is necessary because is a multi-lined form made of X * number of beans in a Hashmap. (don't know how to acomplish this * by the normal xml declarations).//from w w w. j av a 2 s .com * @see org.apache.struts.action.ActionForm#validate(ActionMapping, HttpServletRequest) */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ServletContext application = getServlet().getServletContext(); ActionErrors errors = new ActionErrors(); Validator validator = null; Logger log = Logger.getLogger(NewOrderDTOForm.class); // validate is called even before the page is shown .. if (orderLines == null) { return null; } Collection lines = orderLines.values(); try { int lineNumber = 1; for (Iterator i = lines.iterator(); i.hasNext(); lineNumber++) { OrderLineDTO line = (OrderLineDTO) i.next(); // only editable lines get validated if (line.getEditable().booleanValue()) { validator = Resources.initValidator("orderReviewForm", line, application, request, errors, 0); validator.validate(); if (!errors.isEmpty()) { log.debug("line = " + line); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.review.bad_order_line", new Integer(lineNumber))); break; } } } } catch (ValidatorException e) { log.error("Error calling the validator", e); } return errors; }
From source file:org.apache.beehive.netui.pageflow.internal.BaseActionForm.java
/** * Run all validation (declarative validation from annotations and the result of {@link org.apache.beehive.netui.pageflow.Validatable#validate}) on * a given bean./*from w w w . j a v a2s . co m*/ * * @param bean the bean to validate. * @param beanName the name of the bean, to be passed to Validator to look up declarative validation rules. * @param mapping the current ActionMapping. * @param request the current HttpServletRequest. * @return an ActionErrors object containing errors that occurred during bean validation. */ protected ActionErrors validateBean(Object bean, String beanName, ActionMapping mapping, HttpServletRequest request) { MessageResources messageResources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY); ExpressionAwareMessageResources.update(messageResources, bean); // // See if this action uses a form that defines its own message resources. If so, use those, or combine them // with the message resources from the current module. // if (mapping instanceof PageFlowActionMapping) { PageFlowActionMapping pfam = (PageFlowActionMapping) mapping; String bundle = pfam.getFormBeanMessageResourcesKey(); if (bundle != null) { MessageResources formBeanResources = (MessageResources) request.getAttribute(bundle); ExpressionAwareMessageResources.update(formBeanResources, bean); if (formBeanResources != null) { if (messageResources != null) { formBeanResources = new MergedMessageResources(messageResources, formBeanResources); } request.setAttribute(Globals.MESSAGES_KEY, formBeanResources); messageResources = formBeanResources; } } } ServletContext servletContext = getServlet().getServletContext(); // If there's still no MessageResources for this request, create one that can evaluate expressions. if (messageResources == null) { messageResources = new ExpressionAwareMessageResources(bean, request, servletContext); request.setAttribute(Globals.MESSAGES_KEY, messageResources); } ActionErrors errors = new ActionErrors(); // // If the ValidatorPlugIn was initialized for this module, run it. // if (Resources.getValidatorResources(servletContext, request) != null) { try { // // Run validations associated with the bean. // Validator beanV = initValidator(beanName, bean, servletContext, request, errors, page); validatorResults = beanV.validate(); // // Run validations associated with the action. // Validator actionV = initValidator(mapping.getPath(), bean, servletContext, request, errors, page); validatorResults.merge(actionV.validate()); } catch (ValidatorException e) { _log.error(e.getMessage(), e); } } // // If this bean implements our Validatable interface, run its validate method. // if (bean instanceof Validatable) { ((Validatable) bean).validate(mapping, request, errors); } // Add any additional errors specified by a subclass. ActionErrors additionalActionErrors = getAdditionalActionErrors(mapping, request); if (additionalActionErrors != null) { mergeActionErrors(errors, additionalActionErrors); } return errors; }
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.// w w w. j a va 2s . c o m */ 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.DynaValidatorForm.java
/** * Validate the properties that have been set from this HTTP request, and * return an <code>ActionErrors</code> object that encapsulates any * validation errors that have been found. If no errors are found, return * <code>null</code> or an <code>ActionErrors</code> object with no * recorded error messages.// w ww . j ava 2 s .c o m * * @param mapping The mapping used to select this instance. * @param request The servlet request we are processing. * @return <code>ActionErrors</code> object that encapsulates any * validation errors. */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { this.setPageFromDynaProperty(); ServletContext application = getServlet().getServletContext(); ActionErrors errors = new ActionErrors(); String validationKey = getValidationKey(mapping, request); Validator validator = Resources.initValidator(validationKey, this, application, request, errors, page); try { validatorResults = validator.validate(); } catch (ValidatorException e) { log.error(e.getMessage(), e); } return errors; }
From source file:org.apache.struts.validator.ValidatorActionForm.java
/** * Validate the properties that have been set from this HTTP request, * and return an <code>ActionErrors</code> object that encapsulates any * validation errors that have been found. If no errors are found, return * <code>null</code> or an <code>ActionErrors</code> object with no * recorded error messages.// w w w .j a v a2 s . co m * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing * @return <code>ActionErrors</code> object that encapsulates any validation errors */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ServletContext application = getServlet().getServletContext(); ActionErrors errors = new ActionErrors(); Validator validator = Resources.initValidator(mapping.getPath(), this, application, request, errors, page); try { validatorResults = validator.validate(); } catch (ValidatorException e) { log.error(e.getMessage(), e); } return errors; }
From source file:org.apache.struts.validator.ValidatorForm.java
/** * Validate the properties that have been set from this HTTP request, and * return an <code>ActionErrors</code> object that encapsulates any * validation errors that have been found. If no errors are found, return * <code>null</code> or an <code>ActionErrors</code> object with no * recorded error messages.//from ww w . j a v a 2 s . com * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing * @return <code>ActionErrors</code> object that encapsulates any * validation errors */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ServletContext application = getServlet().getServletContext(); ActionErrors errors = new ActionErrors(); String validationKey = getValidationKey(mapping, request); Validator validator = Resources.initValidator(validationKey, this, application, request, errors, page); try { validatorResults = validator.validate(); } catch (ValidatorException e) { log.error(e.getMessage(), e); } return errors; }
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 ww w .j a v a 2 s . 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./* w ww . j a v a 2 s .co m*/ */ 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 . ja va2 s. c o m*/ validator.validate(); } catch (final ValidatorException e) { fail(); } return errors; }