Example usage for org.springframework.validation Errors getFieldErrors

List of usage examples for org.springframework.validation Errors getFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation Errors getFieldErrors.

Prototype

List<FieldError> getFieldErrors(String field);

Source Link

Document

Get all errors associated with the given field.

Usage

From source file:jetx.ext.springmvc.SpringMvcFunctions.java

/**
 * ??/* w  w  w  .j  a va 2  s  .  co m*/
 */
public static List<String> fieldErrors(JetPageContext ctx, String fieldName) {

    Errors errors = FunctionUtils.findErrors(ctx.getContext());
    if (errors == null) {
        return EMPTY_STRING_LIST;
    }

    List<FieldError> fes = errors.getFieldErrors(fieldName);
    List<String> msgs = new ArrayList<String>(0);

    for (FieldError fe : fes) {
        String[] codes = fe.getCodes();
        String defaultMsg = fe.getDefaultMessage();
        Object[] args = fe.getArguments();
        Locale locale = getLocale(ctx);
        MessageSource ms = getMessageSource(ctx);

        if (codes == null || codes.length == 0 || ms == null) {
            msgs.add(defaultMsg);
        } else {
            String msg = null;
            for (int i = 0; i < codes.length; i++) {
                try {
                    msg = ms.getMessage(codes[i], args, locale);
                } catch (NoSuchMessageException e) {
                    // 
                }
                if (msg == null) {
                    msg = defaultMsg;
                }
            }
            msgs.add(msg);
        }
    }
    return Collections.unmodifiableList(msgs);
}

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

public int doStartTag() throws JspException {

    try {/*from www  . jav a 2 s  .  c  o m*/
        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:alpha.portal.webapp.taglib.LabelTag.java

@Override
public int doStartTag() throws JspException {

    try {//from w  w  w.  j  a v a 2  s . c o 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:pl.chilldev.facelets.taglib.spring.web.form.ErrorsTag.java

/**
 * {@inheritDoc}//from w ww  .  ja  v a  2 s .co  m
 *
 * @since 0.0.1
 */
@Override
public void apply(FaceletContext context, UIComponent parent) throws IOException {
    RequestContext requestContext = this.getRequestContext(context);

    // unsupported execution context
    if (requestContext == null) {
        return;
    }

    List<String> errorMessages = new ArrayList<>();
    try {
        String beanName;
        String path = this.path.getValue(context);

        // split property path
        int position = path.indexOf('.');
        if (position == -1) {
            beanName = path;
            path = null;
        } else {
            beanName = path.substring(0, position);
            path = path.substring(position + 1);
        }

        Errors errors = requestContext.getErrors(beanName, false);

        // nothing was wrong
        if (errors == null) {
            return;
        }

        // find error objects
        List<? extends ObjectError> objectErrors;
        if (path != null) {
            if ("*".equals(path)) {
                objectErrors = errors.getAllErrors();
            } else {
                objectErrors = errors.getFieldErrors(path);
            }
        } else {
            objectErrors = errors.getGlobalErrors();
        }

        // build messages
        for (ObjectError error : objectErrors) {
            errorMessages.add(requestContext.getMessage(error, false));
        }
    } catch (IllegalStateException error) {
        return;
    }

    String var = this.var.getValue(context);
    Object value = context.getAttribute(var);

    try {
        // invoke tag content for every error message
        for (String message : errorMessages) {
            context.setAttribute(var, message);
            this.nextHandler.apply(context, parent);
        }
    } finally {
        // recover old values
        context.setAttribute(var, value);
    }
}

From source file:org.tonguetied.web.KeywordValidator.java

/**
 * This validation method checks if the set of {@link Translation}s for a 
 * {@link Keyword} contains duplicate entries of the business key.
 * //w  w  w.  jav a  2  s . c  om
 * @param translations the set of {@link Translation}s to validate
 * @param errors contextual state about the validation process (never null)
 */
protected void validateDuplicates(SortedSet<Translation> translations, Errors errors) {
    Collection<Translation> output;
    TranslationPredicate predicate;
    List<FieldError> fieldErrors;
    if (translations.size() > 1) {
        for (Translation translation : translations) {
            predicate = new TranslationPredicate(translation.getBundle(), translation.getCountry(),
                    translation.getLanguage());
            output = CollectionUtils.select(translations, predicate);
            if (output.size() > 1) {
                final String[] errorArgs = new String[] { getLanguageName(translation.getLanguage()),
                        getCountryName(translation.getCountry()), getBundleName(translation.getBundle()) };
                fieldErrors = errors.getFieldErrors(FIELD_TRANSLATIONS);
                boolean containsError = false;
                for (FieldError error : fieldErrors) {
                    containsError = containsError || Arrays.equals(error.getArguments(), errorArgs);
                }
                if (!containsError) {
                    errors.rejectValue(FIELD_TRANSLATIONS, "error.duplicate.translations", errorArgs,
                            "default");
                }
            }
        }
    }
}