@RequestMapping(value = "role/update")
 public ModelAndView updateRole(@ModelAttribute @Valid SysRole sysRole, BindingResult result)
     throws Exception {
   Map<String, Object> map = new HashMap<String, Object>();
   SysRole checkByName = this.sysRoleUserService.selectByRoleName(sysRole.getRoleName());
   if (checkByName != null
       && checkByName.getRoleId().intValue() != sysRole.getRoleId().intValue()) {
     FieldError error = new FieldError("sysRole", "roleName", "角色名已存在!");
     result.addError(error);
   }
   SysRole checkById = this.sysRoleUserService.selectOneRole(sysRole.getRoleId());
   if (checkById == null) {
     FieldError error = new FieldError("sysRole", "roleName", "更新的角色不存在!");
     result.addError(error);
   }
   if (result.hasErrors()) {
     List<SysRight> allRights = this.sysRoleUserService.findRights();
     RightModuleBuilder builder = RightModuleBuilder.initModules(allRights);
     map.put("builder", builder);
     map.put("sysRole", sysRole);
     return new ModelAndView("sys/sys_role_edit", map);
   }
   // update SysRole
   checkById.setRoleName(sysRole.getRoleName());
   checkById.setRoleRightCodes(sysRole.getRoleRightCodes());
   this.sysRoleUserService.updateRole(checkById);
   //
   map.put("success_msg", "角色修改成功!");
   map.put("action", "update");
   return new ModelAndView("sys/sys_role_success", map);
 }
  @Transactional
  @RequestMapping(value = "/elimina", method = RequestMethod.POST)
  public String elimina(
      HttpServletRequest request,
      @RequestParam Long id,
      Model modelo,
      @ModelAttribute Almacen almacen,
      BindingResult bindingResult,
      RedirectAttributes redirectAttributes) {
    log.debug("Elimina almacen");
    try {
      Long empresaId = (Long) request.getSession().getAttribute("empresaId");
      String nombre = almacenDao.elimina(id, empresaId);

      ambiente.actualizaSesion(request);

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

    return "redirect:/inventario/almacen";
  }
 @RequestMapping(method = RequestMethod.POST)
 public ModelAndView processForm(LoginForm loginForm, BindingResult result) {
   ModelAndView modelAndView = null;
   boolean isSuccess = false;
   validate(loginForm, result);
   if (!result.hasErrors()) {
     User user =
         loginService.login(
             loginForm.getUserName(), loginForm.getTenantId(), loginForm.getPassword());
     if (user != null && user.getProfileId() != null) {
       if ("CUSTOMER".equals(user.getRole().getPrimary())) {
         modelAndView =
             accountController.getAccountOverview(user.getProfileId(), loginForm.getTenantId());
         isSuccess = true;
       } else {
         log.debug("The user don't have a CUSTOMER ROLE");
         result.addError(new ObjectError("role", "You are not authorized to login"));
       }
     } else {
       result.addError(new ObjectError("password", "Username or Password is wrong"));
     }
   }
   if (!isSuccess) {
     modelAndView = new ModelAndView("login");
     // loginForm = new LoginForm();
     loginForm.setPassword(null);
     loginForm.setUserName(null);
     modelAndView.addObject("form", loginForm);
   }
   return modelAndView;
 }
  @RequestMapping(
      value = {"/", "/login"},
      method = RequestMethod.POST)
  public String loginCheck(
      EmployeeDetails objEmployeeDetails,
      BindingResult result,
      ModelMap redirectedModel,
      HttpSession session) {

    if (objEmployeeDetails.getEmpLoginName() == null
        || objEmployeeDetails.getEmpLoginName().isEmpty()
        || objEmployeeDetails.getEmpPassword() == null
        || objEmployeeDetails.getEmpPassword().isEmpty()) {
      result.addError(
          new FieldError("empLoginName", "empLoginName", "Username or password can not be blank."));
      return "login";
    }

    EmployeeDetails objEmpChkLogin =
        objEmployeeDetailsService.getEmployeeDetailsByUserPassword(
            objEmployeeDetails.getEmpLoginName(), objEmployeeDetails.getEmpPassword());

    if (objEmpChkLogin == null) {
      result.addError(
          new FieldError("empLoginName", "empLoginName", "Username or password is wrong."));
    } else {
      session.setAttribute("empDetails", objEmpChkLogin);
      return "redirect:/home";
    }
    return "login";
  }
  @RequestMapping(value = "/staffchangepasswordsubmit", method = RequestMethod.POST)
  public ModelAndView changePasswordSubmit(
      @ModelAttribute("form") ChangePasswordForm form, BindingResult result) {

    log.debug("Entering ....");
    ModelAndView modelAndView = new ModelAndView("staffchangepassword");

    validateChangePassword(form, result);

    if (!result.hasErrors()) {
      if (form.getNewPassword().equals(form.getNewPasswordRep())) {
        User user = loginService.getUserByProfileId(form.getTenantId(), form.getStaffProfileId());
        if (user != null && form.getCurrentPassword().equals(user.getPassword())) {
          user.setPassword(form.getNewPassword());
          loginService.updateUser(user);
          modelAndView.addObject("successMessage", "Password changed successfully !!!");
        } else {
          result.addError(new ObjectError("currentPassword", "Current password is wrong"));
        }

      } else {
        result.addError(new ObjectError("newPassword", "New password doesn't match"));
      }
    }
    modelAndView.addObject("form", form);
    log.debug("Existing..........");
    return modelAndView;
  }
  @RequestMapping(
      value = {"/save"},
      method = RequestMethod.POST)
  public ModelAndView save(
      @ModelAttribute("backup") @Valid Backup backup,
      BindingResult result,
      RedirectAttributes redirectAttributes) {

    if (result.hasErrors()) return editView(backup);

    if (!canWrite(backup.getOutputFolder())) {
      ObjectError error =
          new ObjectError("backup", "The provided output folder needs write permission");
      result.addError(error);
      return editView(backup);
    }

    if (backup.getDatabases() == null || backup.getDatabases().size() == 0) {
      ObjectError error =
          new ObjectError("databases", "At least one database needs to be selected");
      result.addError(error);
      return editView(backup);
    }

    if (backup.getId() == null) backupService.save(backup);
    else backupService.update(backup);

    redirectAttributes.addFlashAttribute("backup", backup);
    return new ModelAndView("redirect:/backups/list");
  }
 /**
  * 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 = "/staffcreatenewusersubmit", method = RequestMethod.POST)
  public ModelAndView createUserSubmit(
      @ModelAttribute("form") UserForm userForm, BindingResult result) {

    log.debug("Entering....");
    ModelAndView modelAndView = new ModelAndView("staffcreatenewuser");

    boolean isSuccess = true;
    validateUserForm(userForm, result);
    if (userForm.getDateOfBirth() != null) {
      if (!AppUtil.isAValidDDMMYYYYDate(userForm.getDateOfBirth())) {
        log.error("Invalid date format " + userForm.getDateOfBirth());
        isSuccess = false;
        result.addError(
            new ObjectError(
                "dateOfBirth", "Invalid dateOfBirth. Please use the format " + DATE_FORMAT));
      }
    }
    if (isSuccess && !result.hasErrors()) {

      String tenantId = userForm.getTenantId();
      Profile staffProfile = profileService.getProfileById(userForm.getStaffProfileId(), tenantId);
      if (staffProfile != null) {
        userForm.setStaffFirstName(staffProfile.getFirstName());
        userForm.setStaffLastName(staffProfile.getLastName());
      }

      // Create Profile
      String profileId = profileService.saveProfile(createProfile(userForm));
      try {
        // Create Use Account
        loginService.CreateUser(createUser(userForm, profileId));

      } catch (Exception e) {
        log.error("Error Creating User {} ", e);
        isSuccess = false;
        profileService.deleteProfile(profileId, tenantId);
      }

      if (isSuccess) {
        modelAndView.addObject(
            "successMessage", "User '" + userForm.getUserName() + "' successfully created !!!");
        resetForm(userForm);
      } else {
        result.addError(new ObjectError("userAccount", "Error creating new user"));
      }
    }
    modelAndView.addObject("roleType", loadRoleMap());
    modelAndView.addObject("form", userForm);
    log.debug("Existing..........");
    return modelAndView;
  }
 @Override
 public ModelAndView postEditView(
     @ModelAttribute("Model") Player model, HttpServletRequest request, BindingResult result) {
   validator.validate(model, result);
   if (result.hasErrors()) {
     return getEditView(model);
   }
   // make sure not to overwrite passwordHash, verfied etc.
   Player player;
   if (model.getId() != null) {
     player = playerDAO.findById(model.getId());
   } else {
     Player existingPlayer = playerDAO.findByEmail(model.getEmail());
     if (existingPlayer != null) {
       result.addError(new ObjectError("email", msg.get("EmailAlreadyRegistered")));
       return getEditView(model);
     }
     player = new Player();
   }
   player.setEmail(model.getEmail());
   player.setFirstName(model.getFirstName());
   player.setLastName(model.getLastName());
   player.setPhone(model.getPhone());
   player.setGender(model.getGender());
   player.setInitialRanking(model.getInitialRanking());
   playerDAO.saveOrUpdate(player);
   return redirectToIndex(request);
 }
Exemple #10
0
  /*
   * This method will be called on form submission, handling POST request for
   * updating employee in database. It also validates the user input
   */
  @RequestMapping(
      value = {"/edit-{ssn}-employee"},
      method = RequestMethod.POST)
  public String updateEmployee(
      @Valid Employee employee, BindingResult result, ModelMap model, @PathVariable String ssn) {

    if (result.hasErrors()) {
      return "registration";
    }

    if (!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())) {
      FieldError ssnError =
          new FieldError(
              "employee",
              "ssn",
              messageSource.getMessage(
                  "non.unique.ssn", new String[] {employee.getSsn()}, Locale.getDefault()));
      result.addError(ssnError);
      return "registration";
    }

    service.updateEmployee(employee);

    model.addAttribute("success", "Employee " + employee.getName() + " updated successfully");
    return "success";
  }
Exemple #11
0
  /*
   * This method will be called on form submission, handling POST request for
   * saving employee in database. It also validates the user input
   */
  @RequestMapping(
      value = {"/new"},
      method = RequestMethod.POST)
  public String saveEmployee(@Valid Employee employee, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
      return "registration";
    }

    /*
     * Preferred way to achieve uniqueness of field [ssn] should be
     * implementing custom @Unique annotation and applying it on field [ssn]
     * of Model class [Employee].
     *
     * Below mentioned peace of code [if block] is to demonstrate that you
     * can fill custom errors outside the validation framework as well while
     * still using internationalized messages.
     */
    if (!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())) {
      FieldError ssnError =
          new FieldError(
              "employee",
              "ssn",
              messageSource.getMessage(
                  "non.unique.ssn", new String[] {employee.getSsn()}, Locale.getDefault()));
      result.addError(ssnError);
      return "registration";
    }
    employee.setId(service.getNext().intValue());
    service.saveEmployee(employee);

    model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
    return "success";
  }
  @Transactional
  @RequestMapping(value = "/elimina", method = RequestMethod.POST)
  public String elimina(
      HttpServletRequest request,
      @RequestParam Long id,
      Model modelo,
      @ModelAttribute AlumnoPaquete alumnoPaquete,
      BindingResult bindingResult,
      RedirectAttributes redirectAttributes) {
    log.debug("Elimina cuenta de tipos de becas");
    try {
      alumnoPaqueteManager.elimina(id);

      redirectAttributes.addFlashAttribute(
          Constantes.CONTAINSKEY_MESSAGE, "alumnoPaquete.eliminado.message");
      redirectAttributes.addFlashAttribute(
          Constantes.CONTAINSKEY_MESSAGE_ATTRS, new String[] {alumnoPaquete.getMatricula()});
    } catch (Exception e) {
      log.error("No se pudo eliminar el tipo de alumnoPaquete " + id, e);
      bindingResult.addError(
          new ObjectError(
              Constantes.ADDATTRIBUTE_ALUMNOPAQUETE,
              new String[] {"alumnoPaquete.no.elimina.message"},
              null,
              null));
      return Constantes.PATH_ALUMNOPAQUETE_VER;
    }

    return "redirect:/" + Constantes.PATH_ALUMNOPAQUETE_LISTA;
  }
  private void validateUpdate(
      final Complaint complaint, final BindingResult errors, final HttpServletRequest request) {
    if (complaint.getStatus() == null) errors.rejectValue("status", "status.requried");

    if (request.getParameter("approvalComent") == null
        || request.getParameter("approvalComent").trim().isEmpty())
      errors.addError(
          new ObjectError(
              "approvalComent", messageSource.getMessage("comment.not.null", null, null)));
  }
 public void validateGroup(SavingsProductFormBean savingsProductFormBean, BindingResult result) {
   if (savingsProductFormBean.isGroupSavingAccount()
       && StringUtils.isBlank(savingsProductFormBean.getSelectedGroupSavingsApproach())) {
     ObjectError error =
         new ObjectError(
             "savingsProduct",
             new String[] {"NotEmpty.savingsProduct.selectedGroupSavingsApproach"},
             new Object[] {},
             "default: ");
     result.addError(error);
   }
 }
 @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
 public String saveUser(
     HttpServletRequest request,
     ModelMap modelMap,
     @Valid @ModelAttribute UserFormBean userFormBean,
     BindingResult result,
     @RequestParam(required = false, value = "cancel") String isCancel) {
   if (isCancel != null) {
     modelMap.put(
         "message", messageSource.getMessage("ActionCanceled", null, request.getLocale()));
     return "/home";
   }
   if (!userService.isLoginFree(userFormBean.getUser().getLogin())) {
     FieldError error =
         new FieldError(
             "userFormBean",
             "user.login",
             messageSource.getMessage("UnUniq.userFormBean.user.login"));
     result.addError(error);
   }
   if (!userFormBean.getUser().getPassword().equals(userFormBean.getRepeatedPassword())) {
     result.addError(
         new FieldError(
             "userFormBean",
             "repeatedPassword",
             messageSource.getMessage("Size.userFormBean.repeatedPassword")));
   }
   if (result.hasErrors()) {
     return "/auth/signup";
   }
   if (userFormBean.getUser().getPassword().equals(userFormBean.getRepeatedPassword())) {
     userService.create(userFormBean.getUser());
     return "/auth/welcome";
   } else {
     modelMap.put(
         "message",
         messageSource.getMessage("message.RegistrationError", null, request.getLocale()));
     return "/auth/signup";
   }
 }
  @Override
  public void processPropertyAccessException(
      PropertyAccessException ex, BindingResult bindingResult) {

    System.out.println("Binding Exception! " + ex.getPropertyName() + ":" + ex.getErrorCode());

    // addError를 수행하면 더 이상 진행되지 않는다.
    bindingResult.addError(
        new FieldError(bindingResult.getObjectName(), ex.getPropertyName(), "일자포맷"));

    // super.processPropertyAccessException(ex, bindingResult);

  }
 public void validateManadtorySavingsProduct(
     SavingsProductFormBean savingsProductFormBean, BindingResult result) {
   if (savingsProductFormBean.isMandatory() && savingsProductFormBean.getAmountForDeposit() == null
       || savingsProductFormBean.getAmountForDeposit().intValue() <= 0) {
     ObjectError error =
         new ObjectError(
             "savingsProduct",
             new String[] {"Min.savingsProduct.amountForDesposit"},
             new Object[] {},
             "default: ");
     result.addError(error);
   }
 }
Exemple #18
0
  // update an existing group, save to database
  @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
  @Transactional
  public String update(
      @ModelAttribute("category") Category category,
      @PathVariable Integer id,
      Model uiModel,
      HttpServletRequest httpServletRequest,
      RedirectAttributes redirectAttributes,
      Locale locale,
      BindingResult bindingResult) {
    logger.info("Updating category");
    Set<ConstraintViolation<Category>> violations = validator.validate(category);

    for (ConstraintViolation<Category> violation : violations) {
      String propertyPath = violation.getPropertyPath().toString();
      String message = violation.getMessage();
      // Add JSR-303 errors to BindingResult
      // This allows Spring to display them in view via a FieldError
      bindingResult.addError(
          new FieldError("user", propertyPath, "Invalid " + propertyPath + "(" + message + ")"));
    }
    if (bindingResult.hasErrors()) {
      uiModel.addAttribute(
          "message",
          new Message(
              "error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
      uiModel.addAttribute("category", category);
      addCategoryHomeLink(uiModel);
      resetCategories(uiModel, category, categoryService.findParents());
      return "categories/update";
    }
    uiModel.asMap().clear();
    category.setCategoryId(id);
    redirectAttributes.addFlashAttribute(
        "message",
        new Message(
            "success", messageSource.getMessage("category_save_success", new Object[] {}, locale)));
    uiModel.addAttribute("category", category);
    resetCategories(uiModel, category, categoryService.findParents());

    String parentCategoryId = category.getParentCategoryId();
    if (parentCategoryId != null && !parentCategoryId.equals(""))
      category.setParentCategory(categoryService.findById(Integer.valueOf(parentCategoryId)));

    categoryService.save(category);
    return "categories/update";
  }
 @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'NEWSLETTER_WRITE')")
 @RequestMapping(value = "/write/{idNewsletter}", method = RequestMethod.POST)
 public String writeHandle(
     @ModelAttribute("newsletterWriteForm") NewsletterWriteForm newsletterWriteForm,
     Model layout,
     RedirectAttributes redAtt,
     @LoggedUser AuthenticationUserDetails user,
     @PathVariable long idNewsletter,
     HttpServletRequest request) {
   logger.info("Received POST request " + newsletterWriteForm);
   DataBinder binder = new DataBinder(newsletterWriteForm);
   binder.setValidator(
       new NewsletterWriteFormValidator(newsletterSubscriberService, csrfProtector, request));
   binder.validate();
   BindingResult results = binder.getBindingResult();
   logger.info("==================> After BookForm validation " + results);
   if (results.hasErrors()) {
     redAtt.addFlashAttribute("error", true);
     redAtt.addFlashAttribute("newsletterWriteForm", newsletterWriteForm);
     redAtt.addFlashAttribute("errors", results);
     logger.info("errors found = " + newsletterWriteForm);
   } else {
     try {
       Newsletter newsletter = null;
       if (idNewsletter != 0) {
         newsletter =
             newsletterRepository.getByIdAndAdmin(
                 idNewsletter, conversionService.convert(user, Admin.class));
         if (newsletter == null) {
           // TODO : certainement il vaut mieux implémanter une méthode du BackendController ou
           // quelque chose de ce type qui va gérer les erreurs "non autorisation d'accès"
           return "redirect:/backend/dashboard";
         }
       }
       logger.info("No error found !");
       newsletterService.addNewsletter(newsletterWriteForm, user, newsletter);
       redAtt.addFlashAttribute("success", true);
     } catch (Exception e) {
       results.addError(getExceptionError("newsletterWriteForm"));
       redAtt.addFlashAttribute("error", true);
       redAtt.addFlashAttribute("newsletterWriteForm", newsletterWriteForm);
       redAtt.addFlashAttribute("errors", results);
     }
   }
   return "redirect:/backend/newsletter/write/" + idNewsletter;
 }
Exemple #20
0
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public String uploadFile(
      @Valid UploadFormModel uploadFormModel, Model model, BindingResult bindingResult)
      throws Exception {
    if (bindingResult.hasErrors()) {
      return "upload";
    } else if (uploadFormModel.getFile().isEmpty()) {
      bindingResult.addError(new ObjectError("file", "No file specified"));
      return "upload";
    } else {
      MultipartFile file = uploadFormModel.getFile();
      String publicId =
          managementService.upload(
              file.getInputStream(),
              file.getOriginalFilename(),
              file.getContentType(),
              file.getSize(),
              uploadFormModel.getPassword());

      model.addAttribute("publicId", publicId);
      return "success";
    }
  }
Exemple #21
0
  @RequestMapping(value = "/elimina", method = RequestMethod.POST)
  public String elimina(
      HttpServletRequest request,
      @RequestParam Long id,
      Model modelo,
      @ModelAttribute Cliente cliente,
      BindingResult bindingResult,
      RedirectAttributes redirectAttributes) {
    log.debug("Elimina cliente");
    try {
      String nombre = clienteDao.elimina(id);

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

    return "redirect:/admin/cliente";
  }
  /**
   * This method will be called on form submission, handling POST request for saving user in
   * database. It also validates the user input
   */
  @RequestMapping(
      value = {"/newuser"},
      method = RequestMethod.POST)
  public String saveUser(@Valid User user, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
      return "registration";
    }

    /*
     * Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation
     * and applying it on field [sso] of Model class [User].
     *
     * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
     * framework as well while still using internationalized messages.
     *
     */
    if (!userService.isUserSSOUnique(user.getId(), user.getSsoId())) {
      FieldError ssoError =
          new FieldError(
              "user",
              "ssoId",
              messageSource.getMessage(
                  "non.unique.ssoId", new String[] {user.getSsoId()}, Locale.getDefault()));
      result.addError(ssoError);
      return "registration";
    }

    userService.saveUser(user);

    model.addAttribute("user", user);
    model.addAttribute(
        "success",
        "User " + user.getFirstName() + " " + user.getLastName() + " registered successfully");
    // return "success";
    return "registrationsuccess";
  }
  /**
   * This method will be called on form submission, handling POST request for saving in database. It
   * also validates the input
   */
  @RequestMapping(
      value = {"/newProducto"},
      method = RequestMethod.POST)
  public String saveProducto(@Valid Producto producto, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
      return "registration";
    }

    /*
     * Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation
     * and applying it on field [sso] of Model class [Producto].
     *
     * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
     * framework as well while still using internationalized messages.
     *
     */
    if (!productoService.isProductoDescripcionUnique(producto.getId(), producto.getDescripcion())) {
      FieldError descripcionError =
          new FieldError(
              "producto",
              "descripcion",
              messageSource.getMessage(
                  "non.unique.descripcion",
                  new String[] {producto.getDescripcion()},
                  Locale.getDefault()));
      result.addError(descripcionError);
      return "registration";
    }

    productoService.saveProducto(producto);

    model.addAttribute(
        "success", "Producto " + producto.getDescripcion() + " registered successfully");
    // return "success";
    return "registrationsuccess";
  }
Exemple #24
0
  @Transactional
  @RequestMapping(value = "/elimina", method = RequestMethod.POST)
  public String elimina(
      HttpServletRequest request,
      @RequestParam Long id,
      Model modelo,
      @ModelAttribute Entrada entrada,
      BindingResult bindingResult,
      RedirectAttributes redirectAttributes) {
    log.debug("Elimina entrada");
    try {
      String nombre = entradaDao.elimina(id);

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

    return "redirect:/inventario/entrada";
  }
 @RequestMapping(value = "role/save")
 public ModelAndView saveRole(@ModelAttribute @Valid SysRole sysRole, BindingResult result)
     throws Exception {
   Map<String, Object> map = new HashMap<String, Object>();
   SysRole checkOne = this.sysRoleUserService.selectByRoleName(sysRole.getRoleName());
   if (checkOne != null) {
     FieldError error = new FieldError("sysRole", "roleName", "角色名已存在!");
     result.addError(error);
   }
   if (result.hasErrors()) {
     List<SysRight> allRights = this.sysRoleUserService.findRights();
     RightModuleBuilder builder = RightModuleBuilder.initModules(allRights);
     map.put("builder", builder);
     return new ModelAndView("sys/sys_role_new", map);
   }
   // create SysRole
   sysRole.setAuditStatus(EntityConstants.IS_VALILD_0);
   sysRole.setIsValid(EntityConstants.IS_VALILD_1);
   this.sysRoleUserService.createRole(sysRole);
   //
   map.put("success_msg", "角色创建成功!");
   map.put("action", "new");
   return new ModelAndView("sys/sys_role_success", map);
 }
  @RequestMapping(value = "/prueba", method = RequestMethod.POST)
  public String create(
      @Valid @ModelAttribute("prueba") Prueba prueba,
      BindingResult result,
      ModelMap modelMap,
      SessionStatus status,
      HttpServletRequest request) {
    if (prueba == null) throw new IllegalArgumentException("A prueba is required");

    if ((prueba.getPorcentajeCompletitud() < 0) || (prueba.getPorcentajeCompletitud() > 100)) {
      result.addError(
          new FieldError(
              result.getObjectName(),
              "porcentajeCompletitud",
              "El pocentaje debe estar entre 0 y 100"));
    }

    // Metodo para traer los usuario de la UAI de una institucion en
    // especifico
    Util util = new Util();
    Query query = Auditor.findAuditorsById_OrganismoEnte(util.traerIdRif());
    List<Auditor> todos = query.getResultList();
    List<Auditor> losQueSon = new LinkedList<Auditor>();
    for (Auditor a : todos) {
      List<Usuario> usuarios = Usuario.findUsuariosByLogin(a.getLogin()).getResultList();
      for (Usuario u : usuarios) {
        for (RolUsuario r : u.getRoles()) {
          if (r.getNombre().equals("ROLE_UNIDAD_COORDINADOR")) {
            losQueSon.add(a);
            break;
          } else if (r.getNombre().equals("ROLE_UNIDAD_AUDITOR")) {
            losQueSon.add(a);
            break;
          } else if (r.getNombre().equals("ROLE_UNIDAD_GERENTE")) {
            losQueSon.add(a);
            break;
          }
        }
      }
    }

    if (result.hasErrors()) {
      modelMap.addAttribute("prueba", prueba);
      // modelMap.addAttribute("actuacions",
      // Actuacion.findAllActuacions());
      modelMap.addAttribute("auditors", losQueSon);
      modelMap.addAttribute("documentoes", Documento.findAllDocumentoes());
      modelMap.addAttribute(
          "estadoactividadactuacions", EstadoActividadActuacion.findAllEstadoActividadActuacions());
      modelMap.addAttribute(
          "requerimientoes",
          Requerimiento.findRequerimientoesByActuacion(prueba.getCodigoActuacion())
              .getResultList());
      return "prueba/create";
    }

    prueba.persist();
    Util.registrarEntradaEnBitacora(prueba, "Se creó la Prueba ", request.getRemoteAddr());
    status.setComplete();
    return "redirect:/prueba/" + prueba.getId();
  }
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(value = "/admin/users/save.html", method = RequestMethod.POST)
  public String saveUser(
      @Valid @ModelAttribute("user") User user,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      Locale locale)
      throws Exception {

    setMenu(model, request);

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

    this.populateUserObjects(user, store, model, locale);

    Language language = user.getDefaultLanguage();

    Language l = languageService.getById(language.getId());

    user.setDefaultLanguage(l);

    Locale userLocale = LocaleUtils.getLocale(l);

    User dbUser = null;

    // edit mode, need to get original user important information
    if (user.getId() != null) {
      dbUser = userService.getByUserName(user.getAdminName());
      if (dbUser == null) {
        return "redirect://admin/users/displayUser.html";
      }
    }

    List<Group> submitedGroups = user.getGroups();
    Set<Integer> ids = new HashSet<Integer>();
    for (Group group : submitedGroups) {
      ids.add(Integer.parseInt(group.getGroupName()));
    }

    // validate security questions not empty
    if (StringUtils.isBlank(user.getAnswer1())) {
      ObjectError error =
          new ObjectError(
              "answer1", messages.getMessage("security.answer.question1.message", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(user.getAnswer2())) {
      ObjectError error =
          new ObjectError(
              "answer2", messages.getMessage("security.answer.question2.message", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(user.getAnswer3())) {
      ObjectError error =
          new ObjectError(
              "answer3", messages.getMessage("security.answer.question3.message", locale));
      result.addError(error);
    }

    if (user.getQuestion1().equals(user.getQuestion2())
        || user.getQuestion1().equals(user.getQuestion3())
        || user.getQuestion2().equals(user.getQuestion1())
        || user.getQuestion1().equals(user.getQuestion3())
        || user.getQuestion3().equals(user.getQuestion1())
        || user.getQuestion1().equals(user.getQuestion2())) {

      ObjectError error =
          new ObjectError(
              "question1", messages.getMessage("security.questions.differentmessages", locale));
      result.addError(error);
    }

    Group superAdmin = null;

    if (user.getId() != null && user.getId() > 0) {
      if (user.getId().longValue() != dbUser.getId().longValue()) {
        return "redirect://admin/users/displayUser.html";
      }

      List<Group> groups = dbUser.getGroups();
      // boolean removeSuperAdmin = true;
      for (Group group : groups) {
        // can't revoke super admin
        if (group.getGroupName().equals("SUPERADMIN")) {
          superAdmin = group;
        }
      }

    } else {

      if (user.getAdminPassword().length() < 6) {
        ObjectError error =
            new ObjectError(
                "adminPassword", messages.getMessage("message.password.length", locale));
        result.addError(error);
      }
    }

    if (superAdmin != null) {
      ids.add(superAdmin.getId());
    }

    List<Group> newGroups = groupService.listGroupByIds(ids);

    // set actual user groups
    user.setGroups(newGroups);

    if (result.hasErrors()) {
      return ControllerConstants.Tiles.User.profile;
    }

    String decodedPassword = user.getAdminPassword();
    if (user.getId() != null && user.getId() > 0) {
      user.setAdminPassword(dbUser.getAdminPassword());
    } else {
      String encoded = passwordEncoder.encodePassword(user.getAdminPassword(), null);
      user.setAdminPassword(encoded);
    }

    if (user.getId() == null || user.getId().longValue() == 0) {

      // save or update user
      userService.saveOrUpdate(user);

      try {

        // creation of a user, send an email
        String userName = user.getFirstName();
        if (StringUtils.isBlank(userName)) {
          userName = user.getAdminName();
        }
        String[] userNameArg = {userName};

        Map<String, String> templateTokens =
            EmailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, userLocale);
        templateTokens.put(
            EmailConstants.EMAIL_NEW_USER_TEXT,
            messages.getMessage("email.greeting", userNameArg, userLocale));
        templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, user.getFirstName());
        templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, user.getLastName());
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_USERNAME_LABEL,
            messages.getMessage("label.generic.username", userLocale));
        templateTokens.put(EmailConstants.EMAIL_ADMIN_NAME, user.getAdminName());
        templateTokens.put(
            EmailConstants.EMAIL_TEXT_NEW_USER_CREATED,
            messages.getMessage("email.newuser.text", userLocale));
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL,
            messages.getMessage("label.generic.password", userLocale));
        templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD, decodedPassword);
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_URL_LABEL,
            messages.getMessage("label.adminurl", userLocale));
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_URL, FilePathUtils.buildAdminUri(store, request));

        Email email = new Email();
        email.setFrom(store.getStorename());
        email.setFromEmail(store.getStoreEmailAddress());
        email.setSubject(messages.getMessage("email.newuser.title", userLocale));
        email.setTo(user.getAdminEmail());
        email.setTemplateName(NEW_USER_TMPL);
        email.setTemplateTokens(templateTokens);

        emailService.sendHtmlEmail(store, email);

      } catch (Exception e) {
        LOGGER.error("Cannot send email to user", e);
      }

    } else {
      // save or update user
      userService.saveOrUpdate(user);
    }

    model.addAttribute("success", "success");
    return ControllerConstants.Tiles.User.profile;
  }
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(value = "/admin/users/savePassword.html", method = RequestMethod.POST)
  public String changePassword(
      @ModelAttribute("password") Password password,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      HttpServletResponse response,
      Locale locale)
      throws Exception {
    setMenu(model, request);
    String userName = request.getRemoteUser();
    User dbUser = userService.getByUserName(userName);

    if (password.getUser().getId().longValue() != dbUser.getId().longValue()) {
      return "redirect:/admin/users/displayUser.html";
    }

    // validate password not empty
    if (StringUtils.isBlank(password.getPassword())) {
      ObjectError error =
          new ObjectError(
              "password",
              new StringBuilder()
                  .append(messages.getMessage("label.generic.password", locale))
                  .append(" ")
                  .append(messages.getMessage("message.cannot.empty", locale))
                  .toString());
      result.addError(error);
      return ControllerConstants.Tiles.User.password;
    }

    String tempPass = passwordEncoder.encodePassword(password.getPassword(), null);

    // password match
    if (!tempPass.equals(dbUser.getAdminPassword())) {
      ObjectError error =
          new ObjectError("password", messages.getMessage("message.password.invalid", locale));
      result.addError(error);
      return ControllerConstants.Tiles.User.password;
    }

    if (StringUtils.isBlank(password.getNewPassword())) {
      ObjectError error =
          new ObjectError(
              "newPassword",
              new StringBuilder()
                  .append(messages.getMessage("label.generic.newpassword", locale))
                  .append(" ")
                  .append(messages.getMessage("message.cannot.empty", locale))
                  .toString());
      result.addError(error);
    }

    if (StringUtils.isBlank(password.getRepeatPassword())) {
      ObjectError error =
          new ObjectError(
              "newPasswordAgain",
              new StringBuilder()
                  .append(messages.getMessage("label.generic.newpassword.repeat", locale))
                  .append(" ")
                  .append(messages.getMessage("message.cannot.empty", locale))
                  .toString());
      result.addError(error);
    }

    if (!password.getRepeatPassword().equals(password.getNewPassword())) {
      ObjectError error =
          new ObjectError(
              "newPasswordAgain", messages.getMessage("message.password.different", locale));
      result.addError(error);
    }

    if (password.getNewPassword().length() < 6) {
      ObjectError error =
          new ObjectError("newPassword", messages.getMessage("message.password.length", locale));
      result.addError(error);
    }

    if (result.hasErrors()) {
      return ControllerConstants.Tiles.User.password;
    }

    String pass = passwordEncoder.encodePassword(password.getNewPassword(), null);
    dbUser.setAdminPassword(pass);
    userService.update(dbUser);

    model.addAttribute("success", "success");
    return ControllerConstants.Tiles.User.password;
  }
  @RequestMapping(value = "/register.html", method = RequestMethod.POST)
  public String registerCustomer(
      @Valid @ModelAttribute("customer") SecuredShopPersistableCustomer customer,
      BindingResult bindingResult,
      Model model,
      HttpServletRequest request,
      final Locale locale)
      throws Exception {
    MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = super.getLanguage(request);

    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPublicKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));
    reCaptcha.setPrivateKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PRIVATE_KEY));

    String userName = null;
    String password = null;

    model.addAttribute(
        "recapatcha_public_key", coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));

    if (StringUtils.isNotBlank(customer.getRecaptcha_challenge_field())
        && StringUtils.isNotBlank(customer.getRecaptcha_response_field())) {
      ReCaptchaResponse reCaptchaResponse =
          reCaptcha.checkAnswer(
              request.getRemoteAddr(),
              customer.getRecaptcha_challenge_field(),
              customer.getRecaptcha_response_field());
      if (!reCaptchaResponse.isValid()) {
        LOGGER.debug("Captcha response does not matched");
        FieldError error =
            new FieldError(
                "recaptcha_challenge_field",
                "recaptcha_challenge_field",
                messages.getMessage("validaion.recaptcha.not.matched", locale));
        bindingResult.addError(error);
      }
    }

    if (StringUtils.isNotBlank(customer.getUserName())) {
      if (customerFacade.checkIfUserExists(customer.getUserName(), merchantStore)) {
        LOGGER.debug(
            "Customer with username {} already exists for this store ", customer.getUserName());
        FieldError error =
            new FieldError(
                "userName",
                "userName",
                messages.getMessage("registration.username.already.exists", locale));
        bindingResult.addError(error);
      }
      userName = customer.getUserName();
    }

    if (StringUtils.isNotBlank(customer.getPassword())
        && StringUtils.isNotBlank(customer.getCheckPassword())) {
      if (!customer.getPassword().equals(customer.getCheckPassword())) {
        FieldError error =
            new FieldError(
                "password",
                "password",
                messages.getMessage("message.password.checkpassword.identical", locale));
        bindingResult.addError(error);
      }
      password = customer.getPassword();
    }

    if (bindingResult.hasErrors()) {
      LOGGER.debug(
          "found {} validation error while validating in customer registration ",
          bindingResult.getErrorCount());
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    }

    @SuppressWarnings("unused")
    CustomerEntity customerData = null;
    try {
      customerData = customerFacade.registerCustomer(customer, merchantStore, language);
    } catch (CustomerRegistrationException cre) {
      LOGGER.error("Error while registering customer.. ", cre);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    } catch (Exception e) {
      LOGGER.error("Error while registering customer.. ", e);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    }

    /** Send registration email */
    emailTemplatesUtils.sendRegistrationEmail(
        customer, merchantStore, locale, request.getContextPath());

    /** Login user */
    try {

      // refresh customer
      Customer c = customerFacade.getCustomerByUserName(customer.getUserName(), merchantStore);
      // authenticate
      customerFacade.authenticate(c, userName, password);
      super.setSessionAttribute(Constants.CUSTOMER, c, request);

      return "redirect:/shop/customer/dashboard.html";

    } catch (Exception e) {
      LOGGER.error("Cannot authenticate user ", e);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
    }

    StringBuilder template =
        new StringBuilder()
            .append(ControllerConstants.Tiles.Customer.register)
            .append(".")
            .append(merchantStore.getStoreTemplate());
    return template.toString();
  }
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(value = "/manager/saveSystemNotification", method = RequestMethod.POST)
  public String saveSystemNotification(
      @ModelAttribute("systemNotificationForm") @Validated
          SystemNotificationForm systemNotificationForm,
      BindingResult bindingResult,
      Model model,
      final RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
      redirectAttributes.addFlashAttribute(
          "org.springframework.validation.BindingResult.systemNotificationForm", bindingResult);
      redirectAttributes.addFlashAttribute("systemNotificationForm", systemNotificationForm);
      return "redirect:/manager/system?notifUpdateSuccess=false";
    }
    SystemNotification returnedSystemNotification = null;

    // Map form to model
    SystemNotificationModel systemNotificationModel = new SystemNotificationModel();
    systemNotificationModel.setId(systemNotificationForm.getId());
    systemNotificationModel.setStartDate(systemNotificationForm.getStartDate());
    systemNotificationModel.setEndDate(systemNotificationForm.getEndDate());
    systemNotificationModel.setMessage(systemNotificationForm.getMessage());
    systemNotificationModel.setAllPages(systemNotificationForm.isAllPages());
    systemNotificationModel.setNotificationType(systemNotificationForm.getNotificationType());
    systemNotificationModel.setNotificationSeverity(
        systemNotificationForm.getNotificationSeverity());

    boolean success = false;

    try {
      // Check if editing or not
      if (systemNotificationModel.getId() != null && systemNotificationModel.getId() > 0) {
        returnedSystemNotification =
            systemNotificationService.editSystemNotification(systemNotificationModel);
        if (returnedSystemNotification != null) {
          success = true;
        }
      } else {
        returnedSystemNotification =
            systemNotificationService.addSystemNotification(systemNotificationModel);
        if (returnedSystemNotification != null
            && returnedSystemNotification.getId() != null
            && returnedSystemNotification.getId() > 0) {
          success = true;
        }
      }
    } catch (Exception ex) {
      log.info("Error updating systemNotification.", ex);
      String[] codes = {"transaction.genericError"};
      ObjectError error =
          new ObjectError(
              "systemNotificationForm",
              codes,
              null,
              "An error occurred processing your request.  Please try again.");
      bindingResult.addError(error);

      redirectAttributes.addFlashAttribute(
          "org.springframework.validation.BindingResult.systemNotificationForm", bindingResult);
      redirectAttributes.addFlashAttribute("systemNotificationForm", systemNotificationForm);
    }

    return "redirect:/manager/system?notifUpdateSuccess=" + success;
  }