Search in sources :

Example 31 with ObjectError

use of org.springframework.validation.ObjectError in project spring-boot-starter-kit by tripsta.

the class ExceptionHandlingAdvisor method handleMethodArgumentNotValidException.

@ExceptionHandler(MethodArgumentNotValidException.class)
public HttpEntity<ApiErrorResponse> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    logger.warn("Invalid request " + e.getMessage(), e);
    List<ApiError> errorsList = new ArrayList<ApiError>();
    ApiErrorResponse errorResponse = new ApiErrorResponse();
    for (ObjectError error : e.getBindingResult().getAllErrors()) {
        String errorMsg = createErrorMessage(error);
        errorsList.add(new ApiError(errorMsg, ExceptionType.FIELD_VALIDATION));
    }
    errorResponse.addErrors(errorsList);
    return new ResponseEntity<ApiErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) ObjectError(org.springframework.validation.ObjectError) ArrayList(java.util.ArrayList) ApiErrorResponse(com.sbsk.model.ApiErrorResponse) ApiError(com.sbsk.model.ApiError) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler)

Example 32 with ObjectError

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

the class RegistrationController method regEmailValidate.

public Registration regEmailValidate(HttpServletRequest request, Registration reg, boolean isOauthRequest, boolean isKeyup) {
    reg.getEmail().setErrors(new ArrayList<String>());
    if (!isKeyup && (reg.getEmail().getValue() == null || reg.getEmail().getValue().trim().isEmpty())) {
        setError(reg.getEmail(), "Email.registrationForm.email");
    }
    String emailAddress = reg.getEmail().getValue();
    MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email");
    // Validate the email address is ok        
    if (!validateEmailAddress(emailAddress)) {
        String[] codes = { "Email.personalInfoForm.email" };
        String[] args = { emailAddress };
        mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Not vaild"));
    } else {
        //If email exists
        if (emailManager.emailExists(emailAddress)) {
            String orcid = emailManager.findOrcidIdByEmail(emailAddress);
            String[] args = { emailAddress };
            //If it is claimed, should return a duplicated exception
            if (profileEntityManager.isProfileClaimedByEmail(emailAddress)) {
                String[] codes = null;
                if (profileEntityManager.isDeactivated(orcid)) {
                    codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                } else {
                    codes = new String[] { "orcid.frontend.verify.duplicate_email" };
                }
                mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Email already exists"));
            } else {
                if (profileEntityManager.isDeactivated(orcid)) {
                    String[] codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                    mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Email already exists"));
                } else if (!emailManager.isAutoDeprecateEnableForEmail(emailAddress)) {
                    //If the email is not eligible for auto deprecate, we should show an email duplicated exception                        
                    String resendUrl = createResendClaimUrl(emailAddress, request);
                    String[] codes = { "orcid.frontend.verify.unclaimed_email" };
                    args = new String[] { emailAddress, resendUrl };
                    mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Unclaimed record exists"));
                } else {
                    LOGGER.info("Email " + emailAddress + " belongs to a unclaimed record and can be auto deprecated");
                }
            }
        }
    }
    for (ObjectError oe : mbr.getAllErrors()) {
        Object[] arguments = oe.getArguments();
        if (isOauthRequest && oe.getCode().equals("orcid.frontend.verify.duplicate_email")) {
            // XXX
            reg.getEmail().getErrors().add(getMessage("oauth.registration.duplicate_email", arguments));
        } else if (oe.getCode().equals("orcid.frontend.verify.duplicate_email")) {
            Object email = "";
            if (arguments != null && arguments.length > 0) {
                email = arguments[0];
            }
            String link = "/signin";
            String linkType = reg.getLinkType();
            if ("social".equals(linkType)) {
                link = "/social/access";
            } else if ("shibboleth".equals(linkType)) {
                link = "/shibboleth/signin";
            }
            reg.getEmail().getErrors().add(getMessage(oe.getCode(), email, orcidUrlManager.getBaseUrl() + link));
        } else if (oe.getCode().equals("orcid.frontend.verify.deactivated_email")) {
            // Handle this message in angular to allow AJAX action
            reg.getEmail().getErrors().add(oe.getCode());
        } else {
            reg.getEmail().getErrors().add(getMessage(oe.getCode(), oe.getArguments()));
        }
    }
    // validate confirm if already field out
    if (reg.getEmailConfirm().getValue() != null) {
        regEmailConfirmValidate(reg);
    }
    return reg;
}
Also used : ObjectError(org.springframework.validation.ObjectError) MapBindingResult(org.springframework.validation.MapBindingResult) FieldError(org.springframework.validation.FieldError)

Example 33 with ObjectError

use of org.springframework.validation.ObjectError in project opennms by OpenNMS.

the class DefaultDistributedPollerService method resumeLocationMonitor.

/**
 * {@inheritDoc}
 */
@Override
public void resumeLocationMonitor(LocationMonitorIdCommand command, BindingResult errors) {
    if (command == null) {
        throw new IllegalStateException("command argument cannot be null");
    }
    if (errors == null) {
        throw new IllegalStateException("errors argument cannot be null");
    }
    if (errors.hasErrors()) {
        return;
    }
    OnmsLocationMonitor monitor = m_locationMonitorDao.load(command.getMonitorId());
    if (monitor.getStatus() != MonitorStatus.PAUSED) {
        errors.addError(new ObjectError(MonitorStatus.class.getName(), new String[] { "distributed.locationMonitor.notPaused" }, new Object[] { command.getMonitorId() }, "Location monitor " + command.getMonitorId() + " is not paused."));
        return;
    }
    monitor.setStatus(MonitorStatus.STARTED);
    m_locationMonitorDao.update(monitor);
}
Also used : ObjectError(org.springframework.validation.ObjectError) OnmsLocationMonitor(org.opennms.netmgt.model.OnmsLocationMonitor)

Example 34 with ObjectError

use of org.springframework.validation.ObjectError 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 35 with ObjectError

use of org.springframework.validation.ObjectError 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)

Aggregations

ObjectError (org.springframework.validation.ObjectError)57 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 BindException (org.springframework.validation.BindException)10 FieldError (org.springframework.validation.FieldError)8 BusinessRuleException (org.mifos.service.BusinessRuleException)7 ModelAndView (org.springframework.web.servlet.ModelAndView)7 BindingResult (org.springframework.validation.BindingResult)6 DocumentBuilder (javax.xml.parsers.DocumentBuilder)5 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)5 Test (org.junit.Test)5 OnmsLocationMonitor (org.opennms.netmgt.model.OnmsLocationMonitor)5 LocationMonitorIdCommand (org.opennms.web.svclayer.model.LocationMonitorIdCommand)5 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)5 MapBindingResult (org.springframework.validation.MapBindingResult)5 Document (org.w3c.dom.Document)5 Element (org.w3c.dom.Element)5 ArrayList (java.util.ArrayList)3 Errors (org.springframework.validation.Errors)3 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)3 ServletException (javax.servlet.ServletException)2