/**
  * Process the given JSR-303 ConstraintViolations, adding corresponding errors to the provided
  * Spring {@link Errors} object.
  *
  * @param violations the JSR-303 ConstraintViolation results
  * @param errors the Spring errors object to register to
  */
 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);
             }
             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);
       }
     }
   }
 }
  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public @ResponseBody UserJsonResponse handleRegistration(
      @Valid @RequestBody User user,
      BindingResult result,
      Locale locale,
      Model model,
      HttpServletRequest request) {
    logger.info(user.toString());
    UserJsonResponse userJsonResponse = new UserJsonResponse();
    if (request.getSession().getAttribute("loggedIn") != null) {
      userJsonResponse.setStatus("SUCCESS");
      return userJsonResponse;
    }

    if (result.hasErrors()) {

      Map<String, String> errors = new HashMap<String, String>();
      List<FieldError> fieldErrors = result.getFieldErrors();
      for (FieldError fieldError : fieldErrors) {
        String[] resolveMessageCodes = result.resolveMessageCodes(fieldError.getCode());
        String string = resolveMessageCodes[0];
        // System.out.println("resolveMessageCodes : "+string);
        String message =
            messageSource.getMessage(
                string + "." + fieldError.getField(),
                new Object[] {fieldError.getRejectedValue()},
                locale);
        // System.out.println("Meassage : "+message);
        errors.put(fieldError.getField(), message);
      }
      userJsonResponse.setStatus("ERROR");
      userJsonResponse.setErrorsMap(errors);
      return userJsonResponse;
    }

    UserDAO userDao = (UserDAO) context.getBean("userDao");
    if (userDao.get(user.getUsername()) != null) {
      return handleError(userJsonResponse, "username", locale);
    } else if (userDao.getUserBySerialNumber(user.getSerialNumber()) != null) {
      return handleError(userJsonResponse, "serialNumber", locale);
    } else {
      String hash = DaoHelper.getInstance().getPasswordHashing().getHashAndSalt(user.getPassword());
      user.setHash(hash);
      user.setRole("Student");
      Student student = new Student(user);
      student.setSubscriptionDate(new Date());
      logger.info(student.toString());
      userDao.create(student);
      userJsonResponse.setStatus("SUCCESS");
      return userJsonResponse;
    }
  }