List of usage examples for org.apache.commons.validator Validator BEAN_PARAM
String BEAN_PARAM
To view the source code for org.apache.commons.validator Validator BEAN_PARAM.
Click Source Link
From source file:jp.terasoluna.fw.validation.springmodules.DefaultValidatorFactoryEx.java
/** * Validator??/*www .j av a2s .co 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: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 ww . ja v a 2s . c o 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.core.validators.CommonValidator.java
public static boolean validateRequiredIf(Object bean, Field field, Validator validator) { Object form = validator.getParameterValue(Validator.BEAN_PARAM); String value = null;/*from ww w. jav a 2s .c o m*/ boolean required = false; if (isString(bean)) { value = (String) bean; } else { value = ValidatorUtils.getValueAsString(bean, field.getProperty()); } int i = 0; String fieldJoin = "AND"; if (!GenericValidator.isBlankOrNull(field.getVarValue("fieldJoin"))) { fieldJoin = field.getVarValue("fieldJoin"); } if (fieldJoin.equalsIgnoreCase("AND")) { required = true; } while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + i + "]"))) { String dependProp = field.getVarValue("field[" + i + "]"); String dependTest = field.getVarValue("fieldTest[" + i + "]"); String dependTestValue = field.getVarValue("fieldValue[" + i + "]"); String dependIndexed = field.getVarValue("fieldIndexed[" + i + "]"); if (dependIndexed == null) dependIndexed = "false"; String dependVal = null; boolean this_required = false; if (field.isIndexed() && dependIndexed.equalsIgnoreCase("true")) { String key = field.getKey(); if ((key.indexOf("[") > -1) && (key.indexOf("]") > -1)) { String ind = key.substring(0, key.indexOf(".") + 1); dependProp = ind + dependProp; } } dependVal = ValidatorUtils.getValueAsString(form, dependProp); if (dependTest.equals(FIELD_TEST_NULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { this_required = false; } else { this_required = true; } } if (dependTest.equals(FIELD_TEST_NOTNULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { this_required = true; } else { this_required = false; } } if (dependTest.equals(FIELD_TEST_EQUAL)) { this_required = dependTestValue.equalsIgnoreCase(dependVal); } if (fieldJoin.equalsIgnoreCase("AND")) { required = required && this_required; } else { required = required || this_required; } i++; } if (required) { if ((value != null) && (value.length() > 0)) { return true; } else { return false; } } return true; }
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; }// w ww .j a va 2 s . c o m 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.agnitas.service.impl.NewImportWizardServiceImpl.java
public void doBeansValidate() throws Exception { List<ProfileRecipientFields> lTempProfileRecipientFields = new LinkedList<ProfileRecipientFields>(); for (ProfileRecipientFields prRecipientFields : getBeans()) { ProfileRecipientFields newProfileRecipientFields = new ProfileRecipientFieldsImpl(); newProfileRecipientFields.setChange_date(prRecipientFields.getChange_date()); newProfileRecipientFields.setCreation_date(prRecipientFields.getCreation_date()); Map<String, String> newCustomFields = new LinkedHashMap<String, String>(); for (String key : prRecipientFields.getCustomFields().keySet()) { newCustomFields.put(key, prRecipientFields.getCustomFields().get(key)); }/* ww w . j ava 2 s. c o m*/ newProfileRecipientFields.setCustomFields(newCustomFields); newProfileRecipientFields.setEmail(prRecipientFields.getEmail()); newProfileRecipientFields.setFirstname(prRecipientFields.getFirstname()); newProfileRecipientFields.setGender(prRecipientFields.getGender()); newProfileRecipientFields.setLastname(prRecipientFields.getLastname()); newProfileRecipientFields.setMailtype(prRecipientFields.getMailtype()); newProfileRecipientFields.setTemporaryId(prRecipientFields.getTemporaryId()); newProfileRecipientFields.setTitle(prRecipientFields.getTitle()); newProfileRecipientFields.setMailtypeDefined(prRecipientFields.getMailtypeDefined()); lTempProfileRecipientFields.add(newProfileRecipientFields); } List<ProfileRecipientFields> lProfileRecipientFields = getBeans(); Map<String, Boolean> mColumnMapping = new LinkedHashMap<String, Boolean>(); for (ColumnMapping columnMapping : this.importProfile.getColumnMapping()) { mColumnMapping.put(columnMapping.getDatabaseColumn(), columnMapping.getMandatory()); } for (ProfileRecipientFields tprofileRecipientFields : lTempProfileRecipientFields) { if ((mColumnMapping.get("gender") == null) || (!mColumnMapping.get("gender") && StringUtils.isEmpty(tprofileRecipientFields.getGender()))) { tprofileRecipientFields.setGender("2"); } for (String key : tprofileRecipientFields.getCustomFields().keySet()) { if (mColumnMapping.containsKey(key) && !mColumnMapping.get(key) && FieldsFactory.mTypeColums.containsKey(key)) { if (FieldsFactory.mTypeColums.get(key).equals(DataType.DOUBLE)) { if (tprofileRecipientFields.getCustomFields().get(key).isEmpty()) { tprofileRecipientFields.getCustomFields().put(key, "0.0"); } } else if (FieldsFactory.mTypeColums.get(key).equals(DataType.INTEGER)) { if (tprofileRecipientFields.getCustomFields().get(key).isEmpty()) { tprofileRecipientFields.getCustomFields().put(key, "0"); } } else if (FieldsFactory.mTypeColums.get(key).equals(DataType.DATE)) { if (tprofileRecipientFields.getCustomFields().get(key).isEmpty()) { final SimpleDateFormat dateFormat = new SimpleDateFormat( DateFormat.getValue(this.getImportProfile().getDateFormat())); tprofileRecipientFields.getCustomFields().put(key, dateFormat.format(new Date(System.currentTimeMillis()))); } } } } } // Tell the validator which bean to validate against. int iterator = 0; for (ProfileRecipientFields profileRecipientFields : lTempProfileRecipientFields) { /* * AGNEMM-1696: * For umlauts in domains, validate punycoded domain name. * 1. Make backup of original email address * 2. Punycode email address * 3. Validate * 4. Restore email address */ // Umlaut-domains (1): make backup of email address String originalEmail = profileRecipientFields.getEmail(); // Umlaut-domains (2): punycode address profileRecipientFields.setEmail(StringOps.punycoded(originalEmail)); validator.setParameter(Validator.BEAN_PARAM, profileRecipientFields); if (logger.isInfoEnabled()) logger.info("Import ID: " + importProfile.getImportId() + " Preparing to validate recipient: " + Toolkit.getValueFromBean(profileRecipientFields, importProfile.getKeyColumn())); ValidatorResults results = validator.validate(); if (results.isEmpty()) { validRecipients.put(lProfileRecipientFields.get(iterator), null); } else { invalidRecipients.put(lProfileRecipientFields.get(iterator), results); } // Umlaut-domains (4): restore email address profileRecipientFields.setEmail(originalEmail); if (logger.isInfoEnabled()) logger.info("Import ID: " + importProfile.getImportId() + " Validated recipient: " + Toolkit.getValueFromBean(profileRecipientFields, importProfile.getKeyColumn())); iterator++; } }
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.//from ww w . ja 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.FieldChecks.java
/** * Checks if the field isn't null based on the values of other fields. * * @param bean The bean validation is being performed on. * @param va The <code>ValidatorAction</code> that is currently * being performed./*from w ww . j a v a2 s . com*/ * @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 validator The <code>Validator</code> instance, used to access * other field values. * @param request Current request object. * @return true if meets stated requirements, false otherwise. */ public static boolean validateRequiredIf(Object bean, ValidatorAction va, Field field, ActionMessages errors, Validator validator, HttpServletRequest request) { Object form = validator.getParameterValue(org.apache.commons.validator.Validator.BEAN_PARAM); String value = null; boolean required = false; value = evaluateBean(bean, field); int i = 0; String fieldJoin = "AND"; if (!GenericValidator.isBlankOrNull(field.getVarValue("fieldJoin"))) { fieldJoin = field.getVarValue("fieldJoin"); } if (fieldJoin.equalsIgnoreCase("AND")) { required = true; } while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + i + "]"))) { String dependProp = field.getVarValue("field[" + i + "]"); String dependTest = field.getVarValue("fieldTest[" + i + "]"); String dependTestValue = field.getVarValue("fieldValue[" + i + "]"); String dependIndexed = field.getVarValue("fieldIndexed[" + i + "]"); if (dependIndexed == null) { dependIndexed = "false"; } String dependVal = null; boolean thisRequired = false; if (field.isIndexed() && dependIndexed.equalsIgnoreCase("true")) { String key = field.getKey(); if ((key.indexOf("[") > -1) && (key.indexOf("]") > -1)) { String ind = key.substring(0, key.indexOf(".") + 1); dependProp = ind + dependProp; } } dependVal = ValidatorUtils.getValueAsString(form, dependProp); if (dependTest.equals(FIELD_TEST_NULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { thisRequired = false; } else { thisRequired = true; } } if (dependTest.equals(FIELD_TEST_NOTNULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { thisRequired = true; } else { thisRequired = false; } } if (dependTest.equals(FIELD_TEST_EQUAL)) { thisRequired = dependTestValue.equalsIgnoreCase(dependVal); } if (fieldJoin.equalsIgnoreCase("AND")) { required = required && thisRequired; } else { required = required || thisRequired; } i++; } if (required) { if (GenericValidator.isBlankOrNull(value)) { errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field)); return false; } else { return true; } } return true; }
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 w w. j a va 2 s .com*/ * @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.apache.struts.validator.validwhen.ValidWhen.java
/** * 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./*from ww w .ja va 2 s . co m*/ * @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(), 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; }
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 va2 s . com*/ * * @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; } }