Search in sources :

Example 11 with FieldError

use of org.springframework.validation.FieldError in project ORCID-Source by ORCID.

the class BaseController method validateEmailAddress.

protected void validateEmailAddress(String email, boolean ignoreCurrentUser, boolean isRegisterRequest, HttpServletRequest request, BindingResult bindingResult) {
    if (StringUtils.isNotBlank(email)) {
        if (!validateEmailAddress(email)) {
            String[] codes = { "Email.personalInfoForm.email" };
            String[] args = { email };
            bindingResult.addError(new FieldError("email", "email", email, false, codes, args, "Not vaild"));
        }
        if (!(ignoreCurrentUser && emailMatchesCurrentUser(email)) && emailManager.emailExists(email)) {
            OrcidProfile orcidProfile = orcidProfileManager.retrieveOrcidProfileByEmail(email);
            if (orcidProfile.getOrcidHistory().isClaimed()) {
                String[] codes = null;
                if (isRegisterRequest) {
                    if (orcidProfile.getOrcidHistory().getDeactivationDate() != null) {
                        codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                    } else {
                        codes = new String[] { "orcid.frontend.verify.duplicate_email" };
                    }
                } else {
                    codes = new String[] { "orcid.frontend.verify.claimed_email" };
                }
                String[] args = { email };
                bindingResult.addError(new FieldError("email", "email", email, false, codes, args, "Email already exists"));
            } else {
                String resendUrl = createResendClaimUrl(email, request);
                String[] codes = { "orcid.frontend.verify.unclaimed_email" };
                String[] args = { email, resendUrl };
                bindingResult.addError(new FieldError("email", "email", email, false, codes, args, "Unclaimed record exists"));
            }
        }
    }
}
Also used : OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) FieldError(org.springframework.validation.FieldError)

Example 12 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class DataBindingUtils method bindObjectToDomainInstance.

/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult or null if it wasn't successful
     */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder) GrailsWebDataBinder(grails.web.databinding.GrailsWebDataBinder)

Example 13 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class AbstractConstraint method rejectValueWithDefaultMessage.

public void rejectValueWithDefaultMessage(Object target, Errors errors, String defaultMessage, String[] codes, Object[] args) {
    BindingResult result = (BindingResult) errors;
    Set<String> newCodes = new LinkedHashSet<String>();
    if (args.length > 1 && messageSource != null) {
        if ((args[0] instanceof String) && (args[1] instanceof Class<?>)) {
            final Locale locale = LocaleContextHolder.getLocale();
            final Class<?> constrainedClass = (Class<?>) args[1];
            final String fullClassName = constrainedClass.getName();
            String classNameCode = fullClassName + ".label";
            String resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            final String classAsPropertyName = GrailsNameUtils.getPropertyName(constrainedClass);
            if (resolvedClassName.equals(fullClassName)) {
                // try short version
                classNameCode = classAsPropertyName + ".label";
                resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            }
            // update passed version
            if (!resolvedClassName.equals(fullClassName)) {
                args[1] = resolvedClassName;
            }
            String propertyName = (String) args[0];
            String propertyNameCode = fullClassName + '.' + propertyName + ".label";
            String resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName, locale);
            if (resolvedPropertyName.equals(propertyName)) {
                propertyNameCode = classAsPropertyName + '.' + propertyName + ".label";
                resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName, locale);
            }
            // update passed version
            if (!resolvedPropertyName.equals(propertyName)) {
                args[0] = resolvedPropertyName;
            }
        }
    }
    //Qualified class name is added first to match before unqualified class (which is still resolved for backwards compatibility)
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + getName() + ".error", constraintPropertyName)));
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(classShortName + '.' + constraintPropertyName + '.' + getName() + ".error", constraintPropertyName)));
    for (String code : codes) {
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + code, constraintPropertyName)));
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(classShortName + '.' + constraintPropertyName + '.' + code, constraintPropertyName)));
        //We resolve the error code on it's own last so that a global code doesn't override a class/field specific error
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(code, constraintPropertyName)));
    }
    FieldError error = new FieldError(errors.getObjectName(), errors.getNestedPath() + constraintPropertyName, getPropertyValue(errors, target), false, newCodes.toArray(new String[newCodes.size()]), args, defaultMessage);
    ((BindingResult) errors).addError(error);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Locale(java.util.Locale) BindingResult(org.springframework.validation.BindingResult) FieldError(org.springframework.validation.FieldError)

Example 14 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class ValidationErrorsMarshaller method marshalObject.

public void marshalObject(Object object, JSON json) throws ConverterException {
    Errors errors = (Errors) object;
    JSONWriter writer = json.getWriter();
    try {
        writer.object();
        writer.key("errors");
        writer.array();
        for (Object o : errors.getAllErrors()) {
            if (o instanceof FieldError) {
                FieldError fe = (FieldError) o;
                writer.object();
                json.property("object", fe.getObjectName());
                json.property("field", fe.getField());
                json.property("rejected-value", fe.getRejectedValue());
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    json.property("message", applicationContext.getMessage(fe, locale));
                } else {
                    json.property("message", fe.getDefaultMessage());
                }
                writer.endObject();
            } else if (o instanceof ObjectError) {
                ObjectError fe = (ObjectError) o;
                writer.object();
                json.property("object", fe.getObjectName());
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    json.property("message", applicationContext.getMessage(fe, locale));
                } else {
                    json.property("message", fe.getDefaultMessage());
                }
                writer.endObject();
            }
        }
        writer.endArray();
        writer.endObject();
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + object.getClass().getName(), e);
    }
}
Also used : JSONWriter(org.grails.web.json.JSONWriter) Locale(java.util.Locale) Errors(org.springframework.validation.Errors) ConverterException(org.grails.web.converters.exceptions.ConverterException) ObjectError(org.springframework.validation.ObjectError) FieldError(org.springframework.validation.FieldError) ConverterException(org.grails.web.converters.exceptions.ConverterException)

Example 15 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class ValidationErrorsMarshaller method marshalObject.

public void marshalObject(Object object, XML xml) throws ConverterException {
    Errors errors = (Errors) object;
    try {
        for (Object o : errors.getAllErrors()) {
            if (o instanceof FieldError) {
                FieldError fe = (FieldError) o;
                xml.startNode("error");
                xml.attribute("object", fe.getObjectName());
                xml.attribute("field", fe.getField());
                xml.startNode("rejected-value").convertAnother(fe.getRejectedValue());
                xml.end();
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    xml.startNode("message").chars(applicationContext.getMessage(fe, locale)).end();
                } else {
                    String defaultMessage = fe.getDefaultMessage();
                    if (defaultMessage != null)
                        xml.startNode("message").chars(defaultMessage).end();
                }
                xml.end();
            }
        }
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + object.getClass().getName(), e);
    }
}
Also used : Locale(java.util.Locale) Errors(org.springframework.validation.Errors) ConverterException(org.grails.web.converters.exceptions.ConverterException) FieldError(org.springframework.validation.FieldError) BeansException(org.springframework.beans.BeansException) ConverterException(org.grails.web.converters.exceptions.ConverterException)

Aggregations

FieldError (org.springframework.validation.FieldError)25 ObjectError (org.springframework.validation.ObjectError)8 Errors (org.springframework.validation.Errors)7 Test (org.junit.Test)6 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)5 Locale (java.util.Locale)4 BindingResult (org.springframework.validation.BindingResult)4 BigDecimal (java.math.BigDecimal)2 HashMap (java.util.HashMap)2 ConverterException (org.grails.web.converters.exceptions.ConverterException)2 LocalDate (org.joda.time.LocalDate)2 MessageContext (org.springframework.binding.message.MessageContext)2 BindException (org.springframework.validation.BindException)2 DuplicateUserException (com.jappstart.exception.DuplicateUserException)1 UserAccount (com.jappstart.model.auth.UserAccount)1 GrailsApplication (grails.core.GrailsApplication)1 GrailsDomainClass (grails.core.GrailsDomainClass)1 CollectionDataBindingSource (grails.databinding.CollectionDataBindingSource)1 DataBinder (grails.databinding.DataBinder)1 DataBindingSource (grails.databinding.DataBindingSource)1