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:org.smigo.species.vernacular.VernacularController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/rest/vernacular/{id:\\d+}", method = RequestMethod.PUT)
@ResponseBody/* www . jav  a  2 s. c  o m*/
public Object updateVernacular(@Valid @RequestBody Vernacular vernacular, BindingResult result,
        @PathVariable int id, @AuthenticationPrincipal AuthenticatedUser user, Locale locale,
        HttpServletResponse response) {
    log.info("Updating vernacular:" + vernacular);
    if (result.hasErrors()) {
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    Review review = vernacularHandler.updateVernacular(id, vernacular, user, locale);
    if (review == Review.MODERATOR) {
        response.setStatus(HttpStatus.ACCEPTED.value());
    }
    return null;
}

From source file:alpha.portal.webapp.controller.UserFormControllerTest.java

/**
 * Test add with missing fields.//from w  w w  .  j ava 2  s  .  c om
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void testAddWithMissingFields() throws Exception {
    this.request = this.newPost("/userform.html");
    this.user = new User();
    this.user.setFirstName("Jack");
    this.request.setRemoteUser("user");

    final BindingResult errors = new DataBinder(this.user).getBindingResult();
    this.c.onSubmit(this.user, errors, this.request, new MockHttpServletResponse(), new ExtendedModelMap());

    Assert.assertTrue(errors.getAllErrors().size() == 10);
}

From source file:com.music.web.MusicController.java

@RequestMapping("/music/get")
@ResponseBody// www  . j  a  va 2 s  .  c  o m
public long getMusic(UserPreferences preferences, BindingResult bindingResult) {
    // report and ignore errors in binding the UserPreferences object
    if (bindingResult.hasErrors()) {
        logger.error("Binding errors: " + bindingResult.getAllErrors());
    }
    if (Chance.test(7)) {
        return pieceService.getRandomTopPieceId();
    } else {
        return pieceService.getNextPieceId(preferences);
    }
}

From source file:org.jtalks.common.web.controller.UserControllerTest.java

private void assertContainsError(BindingResult bindingResult, String errorName) {
    for (ObjectError error : bindingResult.getAllErrors()) {
        if (error != null && error instanceof FieldError) {
            assertEquals(((FieldError) error).getField(), errorName);
        }//from   w  w  w .j  a v  a 2 s . c  om
    }
}

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

@RequestMapping(value = "/unlinkrequest.shtml", method = RequestMethod.POST)
public ModelAndView spUnlinkrequestPost(@RequestParam Long serviceId,
        @Valid @ModelAttribute("unlinkrequest") LinkRequest unlinkrequest, BindingResult result,
        HttpServletRequest request) {/* w  w  w.j a  v  a 2 s  .c  om*/
    Map<String, Object> m = getModelMapWithService(serviceId, request);
    m.put("unLinkRequest", unlinkrequest);
    if (result.hasErrors()) {
        LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors());
        return new ModelAndView("requests/unlinkrequest", m);
    } else {
        return new ModelAndView("requests/unlinkrequest-confirm", m);
    }
}

From source file:fr.univrouen.poste.web.membre.PosteAPourvoirController.java

@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manageposte')")
public String addFile(@PathVariable("id") Long id, @Valid PosteAPourvoirFile posteFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/posteapourvoirs/" + id.toString();
    }/*from  w w  w. j a  v a2 s  . co m*/
    uiModel.asMap().clear();

    PosteAPourvoir poste = PosteAPourvoir.findPosteAPourvoir(id);

    // upload file
    MultipartFile file = posteFile.getFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();

        boolean filenameAlreadyUsed = false;
        for (PosteAPourvoirFile pcFile : poste.getPosteFiles()) {
            if (pcFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.warn("Upload Restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour le poste " + poste.getNumEmploi());
        } else {

            Long fileSize = file.getSize();

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType="
                        + contentType);

                InputStream inputStream = file.getInputStream();
                //byte[] bytes = IOUtils.toByteArray(inputStream);

                posteFile.setFilename(filename);
                posteFile.setFileSize(fileSize);
                posteFile.setContentType(contentType);
                logger.info("Upload and set file in DB with filesize = " + fileSize);
                posteFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                posteFile.getBigFile().persist();

                Calendar cal = Calendar.getInstance();
                Date currentTime = cal.getTime();
                posteFile.setSendTime(currentTime);

                poste.getPosteFiles().add(posteFile);
                poste.persist();

                logService.logActionPosteFile(LogService.UPLOAD_ACTION, poste, posteFile, request, currentTime);
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/posteapourvoirs/" + id.toString();
}

From source file:mx.edu.um.mateo.contabilidad.web.EjercicioController.java

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Ejercicio ejercicio, 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);
        }/*from   w  w w .j  a va2  s .  co m*/
        return "contabilidad/ejercicio/edita";
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        ejercicio = ejercicioDao.actualiza(ejercicio, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear la ejercicio", e);
        errors.rejectValue("id", "campo.duplicado.message", new String[] { "id" }, null);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        return "contabilidad/ejercicio/edita";
    }

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

    return "redirect:/contabilidad/ejercicio/ver/" + ejercicio.getId().getIdEjercicio();
}

From source file:com.order.erp.web.controller.SystemController.java

@RequestMapping(path = "staff/create", method = RequestMethod.POST)
public String createStaffForPost(HttpServletRequest request, @Valid RegisterForm data, BindingResult br,
        ModelMap model) {//from  w w w.  j  a va 2 s .  co  m
    System.out.println(JSON.toJSONString(data));
    if (br.hasErrors()) {
        List<ObjectError> errorList = br.getAllErrors();
        if (errorList != null && errorList.size() >= 1) {
            ObjectError error = errorList.get(0);
            request.setAttribute("error", error.getDefaultMessage());
        }
        model.put("data", data);
        return "/system/staff_create";
    }
    Account account = accountService.findByUsername(data.getRegAccount());
    if (account != null) {
        request.setAttribute("error", "??");
        model.put("data", data);
        return "/system/staff_create";
    }
    if (!(data.getRegPassword()).equals(data.getRepeatPassword())) {
        request.setAttribute("error", "??");
        model.put("data", data);
        return "/system/staff_create";
    }

    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User me = staffService.findByAccountUsername(((UserDetails) principal).getUsername());
    Company company = me.getCompany();

    User newStaff = new User();
    Account newAccount = new Account();
    newAccount.setUsername(data.getRegAccount());
    newAccount.setPassword(this.passwordEncoder.encode(data.getRegPassword()));
    newAccount.setUser(newStaff);

    newStaff.setAccount(newAccount);
    newStaff.setMobile(data.getRegMobile());
    newStaff.setEmail(data.getRegEmail());
    newStaff.setCompany(company);
    Set<Role> roles = new HashSet<Role>();
    roles.add(roleService.findByRolename(Role.ROlE_USER));
    newStaff.setRoles(roles);

    try {
        newStaff = staffService.save(newStaff);
        return "redirect:/erp/system/staff";
    } catch (Exception e) {
        request.setAttribute("error", e.getMessage());
        model.put("data", data);
        return "/system/staff_create";
    }
}

From source file:mx.edu.um.mateo.general.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);
        }//from w  w w .j a  v a2 s  .  c o  m
        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, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear la Asociacion", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        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.general.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 ww .  j  a v a 2  s .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, 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();
}