List of usage examples for org.apache.commons.validator ValidatorAction getMsg
public String getMsg()
From source file:cn.com.ihuimobile.test.validate.ValidateExample.java
/** * Dumps out the Bean in question and the results of validating it. */// w w w .j a v a2 s. co 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:net.sourceforge.fenixedu.presentationTier.validator.form.ValidateCompareTwoFields.java
/** * Compares the two fields using the given comparator * /*from w w w. j av a 2 s . c o m*/ * @param bean * @param va * @param field * @param errors * @param request * @param comparator * @return */ private static boolean validate(Object bean, ValidatorAction va, Field field, ActionMessages errors, HttpServletRequest request, Comparator comparator) { String greaterInputString = ValidatorUtils.getValueAsString(bean, field.getProperty()); String secondProperty = field.getVarValue("secondProperty"); String lowerInputString = ValidatorUtils.getValueAsString(bean, secondProperty); if (!GenericValidator.isBlankOrNull(lowerInputString) && !GenericValidator.isBlankOrNull(greaterInputString)) { try { Double lowerInput = new Double(lowerInputString); Double greaterInput = new Double(greaterInputString); // if comparator result != VALUE then the condition is false if (comparator.compare(lowerInput, greaterInput) != VALUE) { errors.add(field.getKey(), Resources.getActionMessage(request, va, field)); return false; } return true; } catch (NumberFormatException e) { errors.add(field.getKey(), new ActionMessage(va.getMsg())); return false; } } return true; }
From source file:net.jawr.web.resource.bundle.generator.validator.CommonsValidatorGenerator.java
@SuppressWarnings("unchecked") private StringBuffer createDynamicJavascript(ValidatorResources resources, Form form, String messageNS, boolean stopOnErrors) { StringBuffer results = new StringBuffer(); List<ValidatorAction> actions = this.createActionList(resources, form); final String methods = this.createMethods(actions, stopOnErrors); String jsFormName = form.getName(); results.append(this.getJavascriptBegin(jsFormName, methods)); for (Iterator<ValidatorAction> i = actions.iterator(); i.hasNext();) { ValidatorAction va = i.next(); int jscriptVar = 0; String functionName = null; if ((va.getJsFunctionName() != null) && (va.getJsFunctionName().length() > 0)) { functionName = va.getJsFunctionName(); } else {/* w w w . j a v a 2 s. c om*/ functionName = va.getName(); } results.append(" function " + jsFormName + "_" + functionName + " () { \n"); for (Iterator<Field> x = form.getFields().iterator(); x.hasNext();) { Field field = x.next(); // Skip indexed fields for now until there is a good way to // handle error messages (and the length of the list (could // retrieve from scope?)) if (field.isIndexed() || !field.isDependency(va.getName())) { continue; } String message = null; Msg msg = field.getMessage(va.getName()); if ((msg != null) && !msg.isResource()) { message = JavascriptStringUtil.quote(msg.toString()); } else { if (msg == null) { message = va.getMsg(); } else { message = msg.getKey(); } Arg[] args = field.getArgs(va.getName()); message = messageNS + "." + message + "("; for (int a = 0; a < args.length; a++) { if (args[a] != null) { if (args[a].isResource()) { message += messageNS + "." + args[a].getKey() + "()"; } else { message += "\"" + args[a].getKey() + "\""; } message += ","; } } message += "null)"; } message = (message != null) ? message : ""; // prefix variable with 'a' to make it a legal identifier results.append( " this.a" + jscriptVar++ + " = [\"" + field.getKey() + "\", " + (message) + ", "); results.append("function(varName){"); Map<String, Var> vars = field.getVars(); // Loop through the field's variables. Iterator<Entry<String, Var>> varsIterator = vars.entrySet().iterator(); while (varsIterator.hasNext()) { Entry<String, Var> varEntry = varsIterator.next(); String varName = varEntry.getKey(); Var var = varEntry.getValue(); String varValue = var.getValue(); // Non-resource variable if (var.isResource()) { varValue = messageNS + "." + varValue + "()"; } else varValue = "'" + varValue + "'"; String jsType = var.getJsType(); // skip requiredif variables field, fieldIndexed, fieldTest, // fieldValue if (varName.startsWith("field")) { continue; } String varValueEscaped = JavascriptStringUtil.escape(varValue); if (Var.JSTYPE_INT.equalsIgnoreCase(jsType)) { results.append("this." + varName + "=+" + varValueEscaped + "; "); } else if (Var.JSTYPE_REGEXP.equalsIgnoreCase(jsType)) { results.append("this." + varName + "=eval('/'+" + varValueEscaped + "+'/'); "); } else if (Var.JSTYPE_STRING.equalsIgnoreCase(jsType)) { results.append("this." + varName + "=" + varValueEscaped + "; "); // So everyone using the latest format doesn't need to // change their xml files immediately. } else if ("mask".equalsIgnoreCase(varName)) { results.append("this." + varName + "=eval('/'+" + varValueEscaped + "+'/'); "); } else { results.append("this." + varName + "=" + varValueEscaped + "; "); } } results.append(" return this[varName];}];\n"); } results.append(" } \n\n"); } return results; }
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; }// ww w . 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.apache.commons.validator.example.ValidateExample.java
/** * Dumps out the Bean in question and the results of validating it. *//*from w ww . j a v a2s. 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.apache.struts.validator.Resources.java
/** * 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//from ww w .j av a2s.c o m * @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); }
From source file:org.apache.struts.validator.Resources.java
/** * Gets the <code>Locale</code> sensitive value based on the key passed * in./*from ww w .j a va2 s. c o m*/ * * @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); }
From source file:org.apache.struts.validator.Resources.java
/** * Gets the <code>ActionMessage</code> based on the * <code>ValidatorAction</code> message and the <code>Field</code>'s arg * objects.//from w w w.j a v a 2 s. c o m * <p> * <strong>Note:</strong> this method does not respect bundle information * stored with the field's <msg> or <arg> elements, and localization * will not work for alternative resource bundles. This method is * deprecated for this reason, and you should use * {@link #getActionMessage(Validator,HttpServletRequest,ValidatorAction,Field)} * instead. * * @param request the servlet request * @param va Validator action * @param field the validator Field * @deprecated Use getActionMessage(Validator, HttpServletRequest, * ValidatorAction, Field) method instead */ 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); }
From source file:org.apache.struts.validator.Resources.java
/** * Gets the <code>ActionMessage</code> based on the * <code>ValidatorAction</code> message and the <code>Field</code>'s arg * objects./*from ww w.j a v a2s . co m*/ * * @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; }
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 v a2s. 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; } }