Example usage for org.springframework.validation ObjectError ObjectError

List of usage examples for org.springframework.validation ObjectError ObjectError

Introduction

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

Prototype

public ObjectError(String objectName, @Nullable String[] codes, @Nullable Object[] arguments,
        @Nullable String defaultMessage) 

Source Link

Document

Create a new instance of the ObjectError class.

Usage

From source file:org.runway.utils.FormErrorHandlingUtils.java

public static ObjectError createFormProcessingError(String objectName, String message) {
    ObjectError error = new ObjectError(objectName, new String[] { "PROCESS_ERROR" }, new String[] {}, message);
    return error;
}

From source file:org.dspace.webmvc.controller.LoginController.java

/**
 * Method to authenticate the user credentials supplied in loginForm.
 * <p/>/*from   w  w  w  . jav a2  s. co  m*/
 * Note that the order of parameters is important - the BindingResult must immediately follow the model attribute
 * being validated.
 *
 * @param context
 * @param loginService
 * @param loginForm
 * @param bindingResult
 * @return
 */
@RequestMapping(params = "submit")
public String processForm(@RequestAttribute Context context, LoginService loginService,
        @Valid LoginForm loginForm, BindingResult bindingResult) {
    if (!bindingResult.hasErrors()) {
        int status = AuthenticationManager.authenticate(context, loginForm.getEmail(), loginForm.getPassword(),
                null, null /*request*/);
        if (status == AuthenticationMethod.SUCCESS) {
            loginService.createUserSession(context, context.getCurrentUser());
            String redirectUrl = loginService.getInterruptedRequestURL();
            return "redirect:" + (StringUtils.isEmpty(redirectUrl) ? "/" : redirectUrl);
        } else {
            bindingResult.addError(new ObjectError("loginForm",
                    new String[] { "InvalidPassword.loginForm", "InvalidPassword" }, null /* arguments */,
                    "default message"));
        }
    }

    return "pages/login";
}

From source file:com.mitchellbosecke.pebble.spring.PebbleViewResolverTest.java

private void initBindingResultAllErrors() {
    when(this.bindingResult.hasErrors()).thenReturn(true);

    List<ObjectError> allErrors = new ArrayList<>();
    allErrors.add(/*from ww  w. j  ava  2  s.c  o m*/
            new ObjectError(FORM_NAME, new String[] { "error.test" }, new String[] {}, "???error.test???"));
    when(this.bindingResult.getAllErrors()).thenReturn(allErrors);
}

From source file:com.br.uepb.validator.adapter.CustomConstraintSpringValidatorAdapter.java

@Override
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                String errorCode = violation.getConstraintDescriptor().getAnnotation().annotationType()
                        .getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field,
                        violation.getConstraintDescriptor());
                if (errors instanceof BindingResult) {
                    // can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                    String nestedField = bindingResult.getNestedPath() + field;
                    ObjectError error;//from  w  w  w  .  j av  a 2 s  . c om
                    if ("".equals(nestedField)) {
                        error = new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage());
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && invalidValue == violation.getLeafBean()) {
                            // bean constraint with property path: retrieve the actual property value
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }
                        if (violation.getMessage() != null && violation.getMessage().startsWith("{")
                                && violation.getMessage().endsWith("}")) {
                            String keyMessage = violation.getMessage();
                            keyMessage = keyMessage.replace("{", "");
                            keyMessage = keyMessage.replace("}", "");
                            List<String> temp = new ArrayList<String>(Arrays.asList(errorCodes));
                            temp.add(keyMessage);
                            errorCodes = temp.toArray(new String[temp.size()]);
                            error = new FieldError(errors.getObjectName(), nestedField, invalidValue, false,
                                    errorCodes, errorArgs, violation.getMessage());
                        } else {
                            error = new FieldError(errors.getObjectName(), nestedField, invalidValue, false,
                                    errorCodes, errorArgs, violation.getMessage());
                        }
                    }
                    bindingResult.addError(error);
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    if (violation.getMessage() != null && violation.getMessage().startsWith("{")
                            && violation.getMessage().endsWith("}")) {
                        String keyMessage = violation.getMessage();
                        keyMessage = keyMessage.replace("{", "");
                        keyMessage = keyMessage.replace("}", "");
                        errors.rejectValue(field, keyMessage);
                    } else {
                        errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                    }
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:com.mitchellbosecke.pebble.spring.PebbleViewResolverTest.java

private void initBindingResultGlobalErrors() {
    when(this.bindingResult.hasGlobalErrors()).thenReturn(true);

    List<ObjectError> globalErrors = new ArrayList<>();
    globalErrors.add(new ObjectError(FORM_NAME, new String[] { "error.global.test.params" },
            new String[] { "param1", "param2" }, "???error.global.test.params???"));
    when(this.bindingResult.getGlobalErrors()).thenReturn(globalErrors);
}

From source file:com.company.simple.util.validator.GlobeValidator.java

protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = cd.getAnnotation().annotationType().getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage()));
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && (invalidValue == violation.getLeafBean()
                                || (field.contains(".") && !field.contains("[]")))) {
                            // Possibly a bean constraint with property path: retrieve the actual property value.
                            // However, explicitly avoid this for "address[]" style paths that we can't handle.
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }//from w  w  w  . ja  v a 2  s  . co m
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, invalidValue,
                                false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:nl.surfnet.coin.selfservice.control.requests.LinkrequestController.java

/**
 * BACKLOG-1128: Impersonating users (as a 'super user') cannot really submit the request/question they're about to submit.
 * Those are caught here, adding an error to the BindingResult, resulting in the error displayed in the view.
 * @param result the BindingResult, to which an error will be added if needed
 *//*from ww w. j  a v a 2s .  c om*/
private void denySuperUser(BindingResult result) {
    if (SpringSecurity.getCurrentUser().getAuthorityEnums()
            .contains(CoinAuthority.Authority.ROLE_DASHBOARD_SUPER_USER)) {
        result.addError(new ObjectError("superuser.impersonation", new String[] { "superuser.impersonation" },
                null, "Impersonated: cannot submit"));
    }
}

From source file:mx.edu.um.mateo.general.web.ProveedorController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute Proveedor proveedor, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina proveedor");
    try {//  w  w w . jav  a2s  . com
        String nombre = proveedorDao.elimina(id);

        redirectAttributes.addFlashAttribute("message", "proveedor.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la proveedor " + id, e);
        bindingResult.addError(
                new ObjectError("proveedor", new String[] { "proveedor.no.eliminado.message" }, null, null));
        return "admin/proveedor/ver";
    }

    return "redirect:/admin/proveedor";
}

From source file:mx.edu.um.mateo.general.web.TipoClienteController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute TipoCliente tipoCliente, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina tipoCliente");
    try {/*from   w w  w.j ava2 s. co m*/
        String nombre = tipoClienteDao.elimina(id);

        redirectAttributes.addFlashAttribute("message", "tipoCliente.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la tipoCliente " + id, e);
        bindingResult.addError(new ObjectError("tipoCliente",
                new String[] { "tipoCliente.no.eliminado.message" }, null, null));
        return "admin/tipoCliente/ver";
    }

    return "redirect:/admin/tipoCliente";
}