Example usage for org.apache.commons.validator ValidatorResources getForm

List of usage examples for org.apache.commons.validator ValidatorResources getForm

Introduction

In this page you can find the example usage for org.apache.commons.validator ValidatorResources getForm.

Prototype

public Form getForm(Locale locale, String formKey) 

Source Link

Document

Gets a Form based on the name of the form and the Locale that most closely matches the Locale passed in.

Usage

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

/**
 * Dumps out the Bean in question and the results of validating it.
 *///from ww w  .j  a  v  a 2  s  .  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:net.jawr.web.resource.bundle.generator.validator.CommonsValidatorGenerator.java

/**
 * Creates a validator for a specific form.
 * //  www . ja va2  s.co m
 * @param validatorResources
 * @param formName
 * @param locale
 * @return
 */
private StringBuffer buildFormJavascript(ValidatorResources validatorResources, String formName, Locale locale,
        String messageNS, boolean stopOnErrors) {
    Form form = validatorResources.getForm(locale, formName);
    return createDynamicJavascript(validatorResources, form, messageNS, stopOnErrors);
}

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

@Override
public int doStartTag() throws JspException {

    try {/* w w w  .j a v a  2s. co  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:org.apache.commons.validator.example.ValidateExample.java

/**
 * Dumps out the Bean in question and the results of validating it.
 *//* w w w  .  jav  a 2s  .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.taglib.html.JavascriptValidatorTag.java

/**
 * Returns fully rendered JavaScript./*from   www .j a va2  s  . c o m*/
 *
 * @since Struts 1.2
 */
protected String renderJavascript() throws JspException {
    StringBuffer results = new StringBuffer();

    ModuleConfig config = TagUtils.getInstance().getModuleConfig(pageContext);
    ValidatorResources resources = (ValidatorResources) pageContext
            .getAttribute(ValidatorPlugIn.VALIDATOR_KEY + config.getPrefix(), PageContext.APPLICATION_SCOPE);

    if (resources == null) {
        throw new JspException("ValidatorResources not found in application scope under key \""
                + ValidatorPlugIn.VALIDATOR_KEY + config.getPrefix() + "\"");
    }

    Locale locale = TagUtils.getInstance().getUserLocale(this.pageContext, null);

    Form form = null;
    if ("true".equalsIgnoreCase(dynamicJavascript)) {
        form = resources.getForm(locale, formName);
        if (form == null) {
            throw new JspException("No form found under '" + formName + "' in locale '" + locale
                    + "'.  A form must be defined in the " + "Commons Validator configuration when "
                    + "dynamicJavascript=\"true\" is set.");
        }
    }

    if (form != null) {
        if ("true".equalsIgnoreCase(dynamicJavascript)) {
            results.append(this.createDynamicJavascript(config, resources, locale, form));
        } else if ("true".equalsIgnoreCase(staticJavascript)) {
            results.append(this.renderStartElement());

            if ("true".equalsIgnoreCase(htmlComment)) {
                results.append(HTML_BEGIN_COMMENT);
            }
        }
    }

    if ("true".equalsIgnoreCase(staticJavascript)) {
        results.append(getJavascriptStaticMethods(resources));
    }

    if ((form != null)
            && ("true".equalsIgnoreCase(dynamicJavascript) || "true".equalsIgnoreCase(staticJavascript))) {
        results.append(getJavascriptEnd());
    }

    return results.toString();
}

From source file:org.caofei.taglib.html.JavascriptValidatorTag.java

/**
 * Returns fully rendered JavaScript.//from w ww  .  java 2 s  .co m
 *
 * @since Struts 1.2
 */
protected String renderJavascript() throws JspException {
    StringBuffer results = new StringBuffer();

    /*
            ModuleConfig config =
    TagUtils.getInstance().getModuleConfig(pageContext);
    */
    ValidatorResources resources = null;
    /*
    (ValidatorResources) pageContext.getAttribute(
      ValidatorPlugIn.VALIDATOR_KEY
        + config.getPrefix(), PageContext.APPLICATION_SCOPE);
    */
    if (resources == null) {
        throw new JspException("ValidatorResources is null");
        /*
        "ValidatorResources not found in application scope under key \""
        + ValidatorPlugIn.VALIDATOR_KEY + config.getPrefix() + "\"");
        */
    }
    Locale locale = null;
    /*
    TagUtils.getInstance().getUserLocale(this.pageContext, null);
    */
    Form form = null;
    if ("true".equalsIgnoreCase(dynamicJavascript)) {
        form = resources.getForm(locale, formName);
        if (form == null) {
            throw new JspException("No form found under '" + formName + "' in locale '" + locale
                    + "'.  A form must be defined in the " + "Commons Validator configuration when "
                    + "dynamicJavascript=\"true\" is set.");
        }
    }

    if (form != null) {
        if ("true".equalsIgnoreCase(dynamicJavascript)) {
            results.append(this.createDynamicJavascript(resources, locale, form));
        } else if ("true".equalsIgnoreCase(staticJavascript)) {
            results.append(this.renderStartElement());

            if ("true".equalsIgnoreCase(htmlComment)) {
                results.append(HTML_BEGIN_COMMENT);
            }
        }
    }

    if ("true".equalsIgnoreCase(staticJavascript)) {
        results.append(getJavascriptStaticMethods(resources));
    }

    if ((form != null)
            && ("true".equalsIgnoreCase(dynamicJavascript) || "true".equalsIgnoreCase(staticJavascript))) {
        results.append(getJavascriptEnd());
    }

    return results.toString();
}

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

@SuppressWarnings("null")
@Test//from   w  w w.  j  a v  a2s  .  c  o  m
public void testValidatorInitialization() {

    ValidatorResources resources = null;
    try {
        CommonsValidatorWrapper.setFilePath("/org/megatome/frame2/validator/config"); //$NON-NLS-1$
        CommonsValidatorWrapper.load(getContext());
        resources = CommonsValidatorWrapper.getValidatorResources();
        assertNotNull(resources);
    } catch (CommonsValidatorException e) {
        fail();
    }

    Form f = resources.getForm(new Locale("EN"), "ValidateBean"); //$NON-NLS-1$ //$NON-NLS-2$
    assertNotNull(f);

}

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

public int doStartTag() throws JspException {

    try {/*  ww  w. j  a  v a2s .  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.hotdeploy.ReloadGetFormInterceptor.java

public Object invoke(MethodInvocation invocation) throws Throwable {
    Form result;//from w ww . ja  va2 s .  c  om
    ValidatorResources reloadResources = this.validatorResourcesLoader.load();
    if (invocation.getArguments().length == 2) {
        Locale locale = (Locale) invocation.getArguments()[0];
        String formKey = (String) invocation.getArguments()[1];
        result = reloadResources.getForm(locale, formKey);
    } else {
        String language = (String) invocation.getArguments()[0];
        String country = (String) invocation.getArguments()[1];
        String variant = (String) invocation.getArguments()[2];
        String formKey = (String) invocation.getArguments()[3];
        result = reloadResources.getForm(language, country, variant, formKey);
    }
    if (result != null) {
        return result;
    }
    return invocation.proceed();
}

From source file:org.seasar.struts.lessconfig.autoregister.impl.StrutsConfigRegisterImpl.java

private boolean registeredValidation(ValidatorResources resources, FormBeanConfig formConfig) {
    return (resources.getForm(Locale.getDefault(), formConfig.getName()) != null);
}