Example usage for org.springframework.validation BindingResult addError

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

Introduction

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

Prototype

void addError(ObjectError error);

Source Link

Document

Add a custom ObjectError or FieldError to the errors list.

Usage

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

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute Empleado empleado, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    log.debug("Elimina empleado");
    try {//from w w  w  .  j  a va  2 s .  com
        Long empresaId = (Long) request.getSession().getAttribute("empresaId");
        String nombre = empleadoManager.elimina(id);

        ambiente.actualizaSesion(request.getSession());

        redirectAttributes.addFlashAttribute("message", "empleado.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar el empleado " + id, e);
        bindingResult.addError(
                new ObjectError("empleado", new String[] { "empleado.no.eliminado.message" }, null, null));
        return Constantes.PATH_EMPLEADO_VER;
    }
    return "redirect:" + Constantes.PATH_EMPLEADO;
}

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

@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute Jefe jefe, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    log.debug("Elimina clave de empleado");
    try {/*from  ww  w  . j  a va  2 s  .co m*/
        manager.elimina(id);

        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "jefe.elimina.message");
        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
                new String[] { jefe.getJefe().getNombre() });
    } catch (Exception e) {
        log.error("No se pudo eliminar la clave con id" + id, e);
        bindingResult.addError(new ObjectError(Constantes.ADDATTRIBUTE_JEFE,
                new String[] { "jefe.no.elimina.message" }, null, null));
        return Constantes.PATH_JEFE_VER;
    }

    return "redirect:" + Constantes.PATH_JEFE_LISTA;
}

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

@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute JefeSeccion jefeSeccion, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina clave de empleado");
    try {//  w ww .j a  v a 2  s  . c o  m
        manager.elimina(id);

        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "jefeSeccion.elimina.message");
        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
                new String[] { jefeSeccion.getJefeSeccion().getNombre() });
    } catch (Exception e) {
        log.error("No se pudo eliminar la clave con id" + id, e);
        bindingResult.addError(new ObjectError(Constantes.ADDATTRIBUTE_JEFESECCION,
                new String[] { "nacionalidad.no.elimina.message" }, null, null));
        return Constantes.PATH_JEFESECCION_VER;
    }

    return "redirect:" + Constantes.PATH_JEFESECCION_LISTA;
}

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

@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute SolicitudVacacionesEmpleado vacaciones, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina clave de empleado");
    try {//from  w  w w  .j ava 2 s  .  com
        manager.elimina(id);

        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "vacaciones.elimina.message");
        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
                new String[] { vacaciones.getEmpleado().getNombre() });
    } catch (Exception e) {
        log.error("No se pudo eliminar la clave con id" + id, e);
        bindingResult.addError(new ObjectError(Constantes.ADDATTRIBUTE_SOLICITUDVACACIONESEMPLEADO,
                new String[] { "vacaciones.no.elimina.message" }, null, null));
        return Constantes.PATH_SOLICITUDVACACIONESEMPLEADO_VER;
    }

    return "redirect:" + Constantes.PATH_SOLICITUDVACACIONESEMPLEADO_LISTA;
}

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

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute TipoEmpleado tipoEmpleado, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina tipo de empleado");
    try {/*w  w  w .j ava 2s  .com*/
        String nombre = tipoEmpleadoMgr.elimina(id);

        redirectAttributes.addFlashAttribute("message", "cliente.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar el tipo de empleado " + id, e);
        bindingResult.addError(new ObjectError("tipoEmpleado",
                new String[] { "tipoEmpleado.no.eliminado.message" }, null, null));

        return Constantes.PATH_TIPOEMPLEADO_EDITA;
    }

    return "redirect:" + Constantes.PATH_TIPOEMPLEADO;
}

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

@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute VacacionesEmpleado vacacionesEmpleado, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina clave de empleado");
    try {/*from w w w  .j  a  v a 2 s .c  o m*/
        manager.elimina(id);

        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE,
                "vacacionesEmpleado.elimina.message");
        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
                new String[] { vacacionesEmpleado.getDescripcion() });
    } catch (Exception e) {
        log.error("No se pudo eliminar la clave con id" + id, e);
        bindingResult.addError(new ObjectError(Constantes.ADDATTRIBUTE_VACACIONESEMPLEADO,
                new String[] { "vacacionesEmpleado.no.elimina.message" }, null, null));
        return Constantes.PATH_VACACIONESEMPLEADO_VER;
    }

    return "redirect:" + Constantes.PATH_VACACIONESEMPLEADO_LISTA;
}

From source file:net.sourceforge.jukebox.web.ProfileManagerTest.java

/**
 * Tests update functionality with invalid profile.
 * @throws ConfigurationException configuration exception
 *///from www .  j  a v  a 2s .  c  o m
@Test
public final void testUpdateWithValidationError() throws ConfigurationException {
    ProfileManager profileManager = new ProfileManager();
    ProfileService profileService = mock(ProfileService.class);
    when(profileService.encodePassword(TEST_PASSWORD)).thenReturn(TEST_PASSWORD);
    profileManager.setProfileService(profileService);
    profileManager.setProfileConfiguration(configuration);
    Profile profile = new Profile();
    profile.setNewPassword(TEST_PASSWORD);
    BindingResult result = new DataBinder(profile).getBindingResult();
    result.addError(new ObjectError("oldPassword", "Current password is invalid"));
    String view = profileManager.update(profile, result);
    assertEquals(view, FORM_VIEW);
}

From source file:net.sourceforge.jukebox.web.SettingsConfigurationTest.java

/**
 * Tests the update method./*from  w  w w . j a  v a2s  .  c om*/
 * @throws ConfigurationException configuration exception
 */
@Test
public final void testUpdateSettings() throws ConfigurationException {
    SettingsConfiguration settingsConfiguration = new SettingsConfiguration();
    settingsConfiguration.setConfiguration(configuration);
    Settings settings = new Settings();
    BindingResult result = new DataBinder(settings).getBindingResult();
    String view = settingsConfiguration.update(settings, result);
    assertEquals(view, SUCCESS_VIEW);

    result.addError(new ObjectError("settings", "Validation error"));
    view = settingsConfiguration.update(settings, result);
    assertEquals(view, FORM_VIEW);
}

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/*from ww w  .j a  v a 2  s. c om*/
 * @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.hoteia.qalingo.core.web.mvc.controller.AbstractQalingoController.java

protected void addMessageError(BindingResult result, Exception e, String formKey, String fieldKey,
        String errorMessage) {/*w  w  w  . j  ava  2 s  . c om*/
    if (StringUtils.isEmpty(errorMessage)) {
        errorMessage = ""; // EMPTY VALUE TO EVENT VELOCITY MethodInvocationException
    }
    FieldError error = new FieldError(formKey, fieldKey, errorMessage);
    result.addError(error);
    result.rejectValue(error.getField(), "");
    if (e != null) {
        logger.error(errorMessage, e);
    } else {
        logger.warn(errorMessage);
    }
}