Example usage for org.springframework.validation BindingResult getAllErrors

List of usage examples for org.springframework.validation BindingResult getAllErrors

Introduction

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

Prototype

List<ObjectError> getAllErrors();

Source Link

Document

Get all errors, both global and field ones.

Usage

From source file:io.mandrel.spider.SpiderService.java

public Spider add(Spider spider) throws BindException {
    BindingResult errors = Validators.validate(spider);

    if (errors.hasErrors()) {
        errors.getAllErrors().stream().forEach(oe -> log.info(oe.toString()));
        throw new BindException(errors);
    }//from   ww w. j a  va2 s  .c  om

    spider.setStatus(SpiderStatuses.INITIATED);
    spider.setCreated(LocalDateTime.now());
    spider = spiderRepository.add(spider);

    updateTimeline(spider, SpiderEventType.SPIDER_CREATED);

    return spider;
}

From source file:mx.edu.um.mateo.colportor.web.AsociacionController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Asociacion asociacion,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from  ww  w  . j ava2s .  c o m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }
        modelo.addAttribute(Constantes.CONTAINSKEY_UNIONES,
                unionDao.lista(null).get(Constantes.CONTAINSKEY_UNIONES));
        return Constantes.PATH_ASOCIACION_NUEVA;
    }
    try {
        Usuario usuario = null;
        if (ambiente.obtieneUsuario() != null) {
            usuario = ambiente.obtieneUsuario();
        }
        asociacion = asociacionDao.crea(asociacion, usuario);
        ambiente.actualizaSesion(request.getSession(), usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al Asociacion", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        modelo.addAttribute(Constantes.CONTAINSKEY_UNIONES,
                unionDao.lista(null).get(Constantes.CONTAINSKEY_UNIONES));
        return Constantes.PATH_ASOCIACION_NUEVA;
    }
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "asociacion.creada.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { asociacion.getNombre() });
    return "redirect:" + Constantes.PATH_ASOCIACION_VER + "/" + asociacion.getId();
}

From source file:mx.edu.um.mateo.colportor.web.AsociacionController.java

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Asociacion asociacion, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        log.error("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }/* ww w .  j  ava  2s .co m*/
        modelo.addAttribute(Constantes.CONTAINSKEY_UNIONES,
                unionDao.lista(null).get(Constantes.CONTAINSKEY_UNIONES));
        return Constantes.PATH_ASOCIACION_EDITA;
    }
    try {
        Usuario usuario = null;
        if (ambiente.obtieneUsuario() != null) {
            usuario = ambiente.obtieneUsuario();
        }
        if (asociacion.getStatus() == "0") {
            asociacion.setStatus(Constantes.STATUS_INACTIVO);
        } else {
            asociacion.setStatus(Constantes.STATUS_ACTIVO);
        }
        asociacion = asociacionDao.actualiza(asociacion, usuario);
        ambiente.actualizaSesion(request.getSession(), usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear la Asociacion", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        modelo.addAttribute(Constantes.CONTAINSKEY_UNIONES,
                unionDao.lista(null).get(Constantes.CONTAINSKEY_UNIONES));
        return Constantes.PATH_ASOCIACION_EDITA;
    }
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "asociacion.actualizada.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { asociacion.getNombre() });
    return "redirect:" + Constantes.PATH_ASOCIACION_VER + "/" + asociacion.getId();
}

From source file:mx.edu.um.mateo.colportor.web.UnionController.java

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Union union, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        log.error("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }/* w  w w.j a v a 2s  .  c  o m*/
        return Constantes.PATH_UNION_EDITA;
    }
    try {
        Usuario usuario = null;
        if (ambiente.obtieneUsuario() != null) {
            usuario = ambiente.obtieneUsuario();
        }
        if (union.getStatus() == "0") {
            union.setStatus(Constantes.STATUS_INACTIVO);
        } else {
            union.setStatus(Constantes.STATUS_ACTIVO);
        }
        union = unionDao.actualiza(union, usuario);
        ambiente.actualizaSesion(request.getSession(), usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al union", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        return Constantes.PATH_UNION_EDITA;
    }

    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "union.actualizada.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { union.getNombre() });

    return "redirect:" + Constantes.PATH_UNION_VER + "/" + union.getId();
}

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

public void despliegaBindingResultErrors(BindingResult bindingResult) {
    List<ObjectError> errores = bindingResult.getAllErrors();
    for (ObjectError err : errores) {
        log.error("{}", err);

    }/*from   w w  w . j  av  a2 s .c om*/
}

From source file:mx.edu.um.mateo.rh.web.ColegioController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response, @Valid Colegio colegio,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from   w  w w.  jav a 2s .  co  m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }
        return Constantes.COLEGIO_PATH_NUEVO;
    }

    Boolean isNew = colegio.getId() == null;

    try {
        //La organizacion la asignamos aunque esten modificando el registro
        //porque considero que es mas vulnerable si tomo organizacion.id de los parametros del jsp
        Usuario usuario = ambiente.obtieneUsuario();
        colegio.setOrganizacion(usuario.getEmpresa().getOrganizacion());

        colegioManager.crea(colegio);

    } catch (Exception e) {
        log.error("No se pudo crear al colegio", e);
        errors.rejectValue("nombre", "colegio.errors.creado", e.toString());
        return Constantes.COLEGIO_PATH_NUEVO;
    }

    if (isNew)
        redirectAttributes.addFlashAttribute("message", "colegio.creado.message");
    else
        redirectAttributes.addFlashAttribute("message", "colegio.actualizado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { colegio.getNombre() });

    return "redirect:" + Constantes.COLEGIO_PATH;
}

From source file:mx.edu.um.mateo.rh.web.ConceptoController.java

@Transactional
@RequestMapping(value = "/graba", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response, @Valid Concepto concepto,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from   www. j  ava  2s  .co m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }
        return Constantes.PATH_CONCEPTO_NUEVO;
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        conceptoManager.graba(concepto, usuario);
        log.debug("concepto{}", concepto);

        ambiente.actualizaSesion(request.getSession(), usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al concepto", e);
        /**
         * TODO CORREGIR MENSAJE DE ERROR
         */

        errors.rejectValue("nombre", "concepto.errors.creado", e.toString());
        return Constantes.PATH_CONCEPTO_NUEVO;
    }

    redirectAttributes.addFlashAttribute("message", "concepto.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { concepto.getNombre() });

    //return "redirect:/rh/concepto/ver/" + concepto.getId();
    log.debug("concepto{}", concepto);
    return "redirect:" + Constantes.PATH_CONCEPTO;
}

From source file:mx.edu.um.mateo.rh.web.EmpleadoController.java

@RequestMapping(value = "/graba", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response, @Valid Empleado empleado,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from   w  w  w .j  a  va2  s .co  m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }
        return Constantes.PATH_EMPLEADO_NUEVO;
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        empleadoManager.saveEmpleado(empleado, usuario);

        ambiente.actualizaSesion(request.getSession(), usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al empleado", e);
        errors.rejectValue("nombre", "empleado.errors.creado", e.toString());
        return Constantes.PATH_EMPLEADO_NUEVO;
    }

    redirectAttributes.addFlashAttribute("message", "empleado.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { empleado.getNombre() });

    return "redirect:" + Constantes.PATH_EMPLEADO;
}

From source file:org.codehaus.groovy.grails.web.binding.DataBindingUtils.java

/**
 * 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/*ww w.ja v  a2 s  .c o  m*/
 * @param source The source object
 * @param include The list of properties to include
 * @param exclude The list of properties to exclud
 * @param filter The prefix to filter by
 *
 * @see org.codehaus.groovy.grails.commons.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;
    boolean useSpringBinder = false;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getGrailsApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = GrailsWebRequest.lookupApplication();
    }
    if (grailsApplication != null) {
        if (Boolean.TRUE.equals(grailsApplication.getFlatConfig().get("grails.databinding.useSpringBinder"))) {
            useSpringBinder = true;
        }
    }
    if (!useSpringBinder) {
        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()));
        }
    } else {
        if (source instanceof GrailsParameterMap) {
            GrailsParameterMap parameterMap = (GrailsParameterMap) source;
            HttpServletRequest request = parameterMap.getRequest();
            GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request);
            dataBinder.bind(parameterMap, filter);
            bindingResult = dataBinder.getBindingResult();
        } else if (source instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) source;
            GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request);
            performBindFromRequest(dataBinder, request, filter);
            bindingResult = dataBinder.getBindingResult();
        } else if (source instanceof Map) {
            Map propertyMap = convertPotentialGStrings((Map) source);
            GrailsDataBinder binder = createDataBinder(object, include, exclude, null);
            performBindFromPropertyValues(binder, new MutablePropertyValues(propertyMap), filter);
            bindingResult = binder.getBindingResult();
        }

        else {
            GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
            if (webRequest != null) {
                GrailsDataBinder binder = createDataBinder(object, include, exclude,
                        webRequest.getCurrentRequest());
                HttpServletRequest request = webRequest.getCurrentRequest();
                performBindFromRequest(binder, request, filter);
            }
        }
    }

    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;
}

From source file:org.davidmendoza.irsvped.web.ProfileController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@Valid Event event, BindingResult bindingResult, RedirectAttributes redirectAttributes,
        Principal principal, Model model, HttpServletRequest request) {
    String back = "home/edit";
    if (request.getParameterMap().containsKey("cancel")) {
        return back;
    }/*from  www .  j av  a2 s. c  o m*/
    if (bindingResult.hasErrors()) {
        log.warn("Could not create event {}", bindingResult.getAllErrors());
        return back;
    }

    try {
        User user = userService.get(principal.getName());
        event.setUser(user);
        event.setStatus(Constants.PUBLISHED);

        event = eventService.createOrUpdate(event);

        redirectAttributes.addFlashAttribute("event", event);
        redirectAttributes.addFlashAttribute("successMessage", "event.updated");
        redirectAttributes.addFlashAttribute("successMessageAttrs", event.getName());

        return "redirect:/profile/" + event.getId();
    } catch (Exception e) {
        log.error("Could not update event", e);

        model.addAttribute("errorMessage", "event.not.updated");
        model.addAttribute("errorMessageAttr", e.getMessage());

        return back;
    }
}