protected void handleResultErrors(BindingResult result) throws EscreeningDataValidationException {
    if (result.hasErrors()) {
      ErrorBuilder<EscreeningDataValidationException> errorBuilder =
          ErrorBuilder.throwing(EscreeningDataValidationException.class);

      for (ObjectError objectError : result.getAllErrors()) {

        ErrorMessage errorMessage = new ErrorMessage();

        if (objectError instanceof FieldError) {
          errorMessage.setName(((FieldError) objectError).getField());
        } else {
          errorMessage.setName(objectError.getObjectName());
        }

        errorMessage.setDescription(objectError.getDefaultMessage());
        errorBuilder.toUser(errorMessage);
      }
      // set admin message and throw error
      errorBuilder
          .toAdmin(
              "BaseDashboardRestController.handleResultErrors:  called with "
                  + result.getAllErrors().size()
                  + " errors")
          .throwIt();
    }
  }
  /**
   * AJAX Called once user is submitting upload form
   *
   * @param model
   * @param file - Uploaded file
   * @param comment - Comment for uploaded file
   * @return
   */
  @RequestMapping(method = RequestMethod.POST)
  public @ResponseBody JsonResponse uploadAction(
      @Valid @ModelAttribute(value = "image") Image image,
      @RequestParam(value = "captcha_challenge", required = true) String challenge,
      @RequestParam(value = "captcha_response", required = true) String response,
      BindingResult result,
      HttpServletRequest paramHttpServletRequest) {
    JsonResponse jsonResponse = new JsonResponse();
    String remoteAddr = paramHttpServletRequest.getRemoteAddr();
    ReCaptchaResponse reCaptchaResponse = recaptcha.checkAnswer(remoteAddr, challenge, response);
    if (!reCaptchaResponse.isValid()) {
      jsonResponse.setCaptchaError(
          context.getMessage("error.bad.captcha", null, Locale.getDefault()));
      return jsonResponse;
    }

    prepareImage(image);
    (new ImageValidator()).validate(image, result);
    if (!result.hasErrors()) {
      try {
        image.setBytes(image.getFile().getBytes());
        image.setContentType(image.getFile().getContentType());
        image = imageService.saveImage(image);
        jsonResponse.setResponse(paramHttpServletRequest.getRequestURL() + image.getId());
      } catch (Exception e) {
        log.error(e.getMessage());
      }
    } else {
      for (ObjectError error : result.getAllErrors()) {
        jsonResponse.appendError(context.getMessage(error.getCode(), null, Locale.getDefault()));
      }
    }
    return jsonResponse;
  }
 @RequestMapping(value = "/update")
 public @ResponseBody ResponseObject update(
     @RequestBody @Valid Product product, BindingResult errors) throws Exception {
   if (errors.hasErrors())
     throw new ValidateException(errors.getAllErrors().get(0).getDefaultMessage());
   return productService.update(product);
 }
Beispiel #4
0
 public static void printResultErrors(BindingResult result) {
   if (result.hasErrors()) {
     List<ObjectError> errors = result.getAllErrors();
     for (ObjectError error : errors)
       System.out.println(error.getObjectName() + ", " + error.getDefaultMessage());
   }
 }
  /**
   * Зарегестрировать
   *
   * @param registrationInfo - Информация о пользователе и его организации
   * @return - отображение запрашиваемого ресурса
   * @throws UnsupportedEncodingException - ошибка о не правильной раскодировке
   */
  @RequestMapping(method = RequestMethod.POST)
  public String registration(@Valid RegistrationInfo registrationInfo, BindingResult result)
      throws UnsupportedEncodingException {

    HttpSession session = getSession();

    // Получаем сообщения об ошибках, если они есть
    List<ObjectError> erorList = result.getAllErrors();
    List<String> erorMessageList = new ArrayList<>();
    try {
      if (!erorList.isEmpty()) {
        erorMessageList = CompanyController.getListMessageForEror(erorList);
        session.setAttribute("uncorrectRegistrationUserCompany", registrationInfo);
        session.setAttribute("listErorRegistration", erorMessageList);
        return "redirect:/registration";
      }

      OrganizationInfo regestratingCompany = userService.registration(registrationInfo);

      session.removeAttribute("uncorrectRegistrationUserCompany");
      session.removeAttribute("listErorRegistration");
      return "redirect:/login";

    } catch (Exception e) {
      erorMessageList.add("Системная ошибка!");
      session.setAttribute("listErorRegistration", erorMessageList);
      session.setAttribute("uncorrectRegistrationUserCompany", registrationInfo);
      return "redirect:/registration";
    }
  }
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView update(
      @Valid SearchElementEntity elementDefinition,
      BindingResult bindingResult,
      HttpServletRequest httpServletRequest,
      ServerHttpResponse response) {
    LOGGER.info(
        "Creating an filed element: "
            + elementDefinition.getClazz().getSimpleName()
            + " for preset: "
            + elementDefinition.getPreset().getSlug());

    ModelAndView model = new ModelAndView("admin/SearchElementDefinition/updateForm");

    if (bindingResult.hasErrors()) {
      LOGGER.error("Bindding has error...");
      for (ObjectError error : bindingResult.getAllErrors()) {
        LOGGER.error("Error: " + error.getDefaultMessage());
      }
      response.setStatusCode(HttpStatus.PRECONDITION_FAILED);
      return model;
    }
    try {
      elementDefinition = repository.save(elementDefinition);
    } catch (Exception e) {
      LOGGER.error("Could not save elementDefinition", e);
    }
    model.addObject("searchElementDefinition", elementDefinition);
    return model;
  }
  @Transactional
  @RequestMapping(value = "/actualiza", method = RequestMethod.POST)
  public String actualiza(
      HttpServletRequest request,
      @Valid Almacen almacen,
      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);
      }
      return "inventario/almacen/edita";
    }

    try {
      Usuario usuario = ambiente.obtieneUsuario();
      almacen = almacenDao.actualiza(almacen, usuario);

      ambiente.actualizaSesion(request, usuario);
    } catch (ConstraintViolationException e) {
      log.error("No se pudo crear la almacen", e);
      errors.rejectValue("nombre", "campo.duplicado.message", new String[] {"nombre"}, null);
      return "inventario/almacen/edita";
    }

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

    return "redirect:/inventario/almacen/ver/" + almacen.getId();
  }
  @ResourceMapping(value = "submitMeteruseinfoForm")
  public Resultmsg onSubmitMeteruseinfoForm(
      @ModelAttribute("meteruseinfo") Meteruseinfo meteruseinfo,
      BindingResult result,
      SessionStatus status,
      ResourceRequest request,
      ResourceResponse response) {
    Resultmsg msg = new Resultmsg();
    boolean isnew = true;
    if (request.getParameter("isnew") == null) {
      msg.setMsg("页面缺少新增或编辑标记 isnew");
    } else {
      isnew = Boolean.valueOf(request.getParameter("isnew"));
    }
    new MeteruseinfoValidator().validate(meteruseinfo, result);
    if (result.hasErrors()) {
      logger.error(result);
      StringBuilder sb = new StringBuilder();
      for (ObjectError err : result.getAllErrors()) {
        sb.append(err.getDefaultMessage());
      }
      msg.setMsg(sb.toString());
    } else {
      try {
        if (!StringUtils.hasLength(meteruseinfo.getBuildregioninfo().getRegionId())) {
          meteruseinfo.setBuildregioninfo(null);
        }
        Circuitinfo circuitinfo =
            circuitinfoService.getCircuitinfo(meteruseinfo.getCircuitinfo().getCircuitId());
        meteruseinfo.setCircuitinfo(circuitinfo);
        if ("系统生成".equals(meteruseinfo.getMeterId()) || "".equals(meteruseinfo.getMeterId())) {
          meteruseinfoService.addMeteruseinfo(meteruseinfo);
        } else {
          meteruseinfoService.updateMeteruseinfo(meteruseinfo);
        }

        // meteruseinfoService.saveOrUpdateMeteruseinfo(meteruseinfo);

        // 保存分类分项与装表关系数据
        if (StringUtils.hasLength(request.getParameter("energyItemcode"))) {
          String energyItemcode = request.getParameter("energyItemcode").trim();
          String resultId = request.getParameter("resultId").trim();
          Energyitemresult energyitemresult = new Energyitemresult();
          energyitemresult.setResultId(resultId);
          energyitemresult.setMeteruseinfo(meteruseinfo);
          Energyitemdict energyitemdict = energyitemdictService.getEnergyitemdict(energyItemcode);
          energyitemresult.setEnergyitemdict(energyitemdict);
          energyitemresultService.saveOrUpdateEnergyitemresult(energyitemresult);
        }
        status.setComplete();
        msg.setMsg(meteruseinfo.getMeterId());
        msg.setSuccess("true");
      } catch (Exception e) {
        msg.setMsg(e.getMessage());
        logger.error(e);
      }
    }
    return msg;
  }
Beispiel #9
0
 protected void handleBindingValidation(BindingResult bindingResult) throws MyException {
   if (bindingResult.hasErrors()) {
     List<ObjectError> list = bindingResult.getAllErrors();
     StringBuilder msg = new StringBuilder();
     for (ObjectError error : list) {
       msg.append(error.getDefaultMessage() + ";");
     }
     throw new MyException("0", msg.toString());
   }
 }
 @RequestMapping(method = RequestMethod.POST)
 public ModelAndView create(
     @Valid Product product, BindingResult result, RedirectAttributes redirectAttributes) {
   if (result.hasErrors()) {
     return new ModelAndView("products/form", "formErrors", result.getAllErrors());
   }
   product = productRepository.save(product);
   redirectAttributes.addFlashAttribute("globalMessage", "Successfully created a new product");
   return new ModelAndView("redirect:/products/{product.id}", "product.id", product.getId());
 }
 @RequestMapping(method = RequestMethod.POST)
 public ModelAndView create(
     @Valid Course course, BindingResult result, RedirectAttributes redirect) {
   if (result.hasErrors()) {
     return new ModelAndView("courses/form", "formErrors", result.getAllErrors());
   }
   course = courseService.save(course);
   redirect.addFlashAttribute("globalMessage", "Curso creado correctamente");
   return new ModelAndView("redirect:/{course.id}", "course.id", course.getId());
 }
 protected String getViewWithBindingErrorMessages(
     final Model model, final BindingResult bindingErrors) {
   for (final ObjectError error : bindingErrors.getAllErrors()) {
     if (isTypeMismatchError(error)) {
       model.addAttribute(ERROR_MSG_TYPE, QUANTITY_INVALID_BINDING_MESSAGE_KEY);
     } else {
       model.addAttribute(ERROR_MSG_TYPE, error.getDefaultMessage());
     }
   }
   return ControllerConstants.Views.Fragments.Cart.AddToCartPopup;
 }
  @Test
  public void testAddWithMissingFields() throws Exception {
    request = newPost("/userform.html");
    user = new User();
    user.setFirstName("Jack");
    request.setRemoteUser("user");

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

    assertEquals(4, errors.getAllErrors().size());
  }
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public String validateUser(
      @Valid UserForm userForm,
      BindingResult bindingResult,
      RedirectAttributes redirectAttributes) {

    if (bindingResult.hasErrors()) {
      log.error("errors = " + bindingResult.getAllErrors());
      return "index";
    }
    redirectAttributes.addAttribute("name", userForm.getName());
    redirectAttributes.addAttribute("age", userForm.getAge());
    return "redirect:/results";
  }
Beispiel #15
0
 /**
  * Build a error message with all errors.
  *
  * @return String with error message
  */
 public String getErrorMessage() {
   StringBuilder sb = new StringBuilder();
   if (errors.hasErrors()) {
     sb.append("\n");
     Iterator<ObjectError> iter = errors.getAllErrors().iterator();
     while (iter.hasNext()) {
       ObjectError oe = (ObjectError) iter.next();
       sb.append("- ");
       sb.append(getMessage(oe));
       sb.append("\n");
     }
   }
   sb.append("\n");
   return sb.toString();
 }
 @RequiresPermissions(value = "cartype:save")
 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public String editCarType(
     CarType carType,
     BindingResult bindingResult,
     @RequestParam(value = "file") MultipartFile file,
     HttpSession httpSession) {
   if (bindingResult.hasErrors()) {
     for (ObjectError error : bindingResult.getAllErrors()) {
       System.out.println(error.getObjectName() + " : " + error.getDefaultMessage());
     }
   }
   carTypeService.updateCarType(carType, file, httpSession);
   return "redirect:/admin/cartype/list";
 }
  /** 更新 */
  @RequestMapping(value = "/update", method = RequestMethod.POST)
  public @ResponseBody Result update(
      @ModelAttribute("pluginConfig") @Valid PluginConfig pluginConfig,
      BindingResult result,
      Model model) {

    preUpdate(pluginConfig, result, model);

    if (result.hasErrors()) {
      return Result.validateError(result.getAllErrors());
    }

    pluginConfigService.save(pluginConfig);

    return Result.success();
  }
  // TODO Validierung, ob es ein Bild oder eine andere Datei, am besten je
  // nach kontext anpassbar.
  @RequestMapping(value = URL.StorageFile.UPLOAD, method = RequestMethod.POST)
  public @ResponseBody String save(
      @Valid UploadFile uploadFile, BindingResult result, Principal principal) throws IOException {
    if (result.hasErrors()) {
      return result.getAllErrors().toString();
    }

    log.debug("file Upload " + uploadFile.getName());
    log.debug(uploadFile.getContentType() + " filename: " + uploadFile.getOriginalFilename());
    String username = principal.getName();

    StorageFile storedFile = uploadFile.toStorageFile();
    storedFile.setUsername(username);
    fileService.save(storedFile);
    return storedFile.getId();
  }
 @Override
 public Message update(Orator object, BindingResult result) {
   if (result.hasErrors()) {
     Message oratorMessage = new Message("There is error in inserting the orator", false);
     List<String> errorOrator = new ArrayList<String>();
     for (ObjectError error : result.getAllErrors()) {
       errorOrator.add(error.getDefaultMessage());
     }
     oratorMessage.setErrors(errorOrator);
     return oratorMessage;
   } else {
     oratorRepository.save(object);
     Message oratorMessage = new Message("Orator save successfully", true);
     oratorMessage.setId(object.getIdOrator());
     return oratorMessage;
   }
 }
  @RequestMapping(method = RequestMethod.POST)
  public String processSubmit(@ModelAttribute("bean") @Valid Bean bean, BindingResult result) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    logger.info(validator.getClass());

    logger.info(bean.toString());

    logger.info(result.getAllErrors().toString());

    if (result.hasErrors()) {
      return "bean/form";
    }

    return "bean/done";
  }
 /**
  * Validates and saves Job to database.
  *
  * @param model Model of page
  * @param principal Current user details
  * @return Redirection to jobs-method if succesful, otherwise back to "createjob"-page
  */
 @RequestMapping(
     value = "/addJob",
     method = {RequestMethod.GET, RequestMethod.POST})
 public String addJob(
     @ModelAttribute("job") Job job, BindingResult result, Principal principal, Model model) {
   System.out.println("addjob");
   User user = userDao.findByEmail(principal.getName());
   model.addAttribute("user", user);
   job.setUser(user);
   new JobValidator().validate(job, result);
   if (result.hasErrors()) {
     result.getAllErrors();
     return "createjob";
   } else {
     jobDao.save(job);
     return "redirect:jobs";
   }
 }
 /** 处理参数校验错误 */
 @ExceptionHandler({BindException.class})
 @ResponseStatus(value = HttpStatus.BAD_REQUEST)
 @ResponseBody
 public BaseResponseEntity<List<String>> handleException(
     BindException exception, HttpServletRequest request) {
   BindingResult bindingResult = exception.getBindingResult();
   List<ObjectError> objectErrors = bindingResult.getAllErrors();
   List<String> errorMessages = new LinkedList<String>();
   for (ObjectError objectError : objectErrors) {
     errorMessages.add(objectError.getDefaultMessage());
   }
   return BaseResponseEntity.build(
       HttpStatus.BAD_REQUEST.value(),
       APIStatus.INVALID_PARAMETER.getStatus(),
       APIStatus.INVALID_PARAMETER.name(),
       errorMessages,
       request);
 }
  @RequestMapping(value = "/srchtest", method = RequestMethod.GET, produces = "application/json")
  public @ResponseBody JqGridData<?> ValidatePage(ScorecardPage sp, BindingResult result) {
    // ScorecardPage sp = new ScorecardPage();
    // sp.setZipcode("921");
    // sp.setPlaydate("10/02/2013");
    // logger.info("Comes inside with searlize object" + sp.getTeetype());
    // logger.info("Comes inside with searlize object" + p.getGender());
    // logger.info("Comes inside with searlize object" + p.getPlayer_id());

    this.sv.validate(sp, result);
    List<ObjectError> obj;
    obj = result.getAllErrors();
    if (result.hasErrors()) {
      logger.info("Scorecard has errors");
      JqGridData<GolfCourseHolesMap> errorData =
          new JqGridData<GolfCourseHolesMap>(
              numberOfRows, pageNumber, totalNumberOfRecords, null, obj);
      return errorData;
    }
    return null;
  }
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView submitWorklog(
      @ModelAttribute("worklogWrapper") WorklogWrapper worklogWrapper,
      BindingResult errors,
      @PathVariable("user") String user,
      @RequestParam(value = "date", defaultValue = "") String date) {

    if (errors.hasErrors()) {
      List<ObjectError> l = errors.getAllErrors();

      for (ObjectError ob : l) {
        System.out.println("------ " + ob.getDefaultMessage());
      }
    }

    populateObjects(worklogWrapper.getWorklog(), user, date);
    worklogService.addWorklog(worklogWrapper.getWorklog());
    ModelAndView modelAndView =
        dataHolder.getModelAndView("redirect:/spring/" + user + "/showWorklog");
    return modelAndView;
  }
 @RequestMapping(value = "admin/user/useraddaction", method = RequestMethod.POST)
 public String addContact(
     @ModelAttribute("user") @Valid User user, BindingResult result, ModelMap m) {
   System.out.println("user : "******"lasterror", "");
   if (result.hasErrors()) {
     String errorOutput = "Registration failed : </br>";
     List<ObjectError> e = result.getAllErrors();
     for (ObjectError a : e) {
       errorOutput += a.getObjectName() + " : " + a.getDefaultMessage() + "</br>";
     }
     EMF.getHttpSession().setAttribute("lasterror", errorOutput);
     return "redirect:/app/admin/user/";
   }
   try {
     EMF.save(user);
     EMF.commit();
   } catch (Exception e) {
     m.addAttribute("error", e.getMessage());
   }
   return "redirect:/app/admin/user/";
 }
  /*
      speaking url accepts 3 parametars
  -amount of money to convert
  -currency from which we convert
  -currency to which we convert amount
  we do validation and if there is error we return error message if everything is right we connecting to external api
  and returning converted amount etc...
  */
  @RequestMapping(value = "/convert/{amount}/{from}/{to}")
  public Object Convert(
      @PathVariable Double amount, @PathVariable String from, @PathVariable String to) {

    CurrencyConverter currencyConverter = new CurrencyConverter();

    Currency currencyFrom = new Currency();
    currencyFrom.setAmount(amount);
    currencyFrom.setCurrency(from);
    currencyConverter.setFrom(currencyFrom);

    Currency toCurrency = new Currency();
    toCurrency.setCurrency(to);
    currencyConverter.setTo(toCurrency);

    DataBinder binder = new DataBinder(currencyConverter);
    binder.setValidator(new CurrencyConverterValidator(new CurrencyValidator()));
    binder.validate();

    BindingResult result = binder.getBindingResult();
    if (result.hasErrors()) {
      return new Error(result.getAllErrors().get(0).getCode());
    } else {

      RestTemplate restTemplate = new RestTemplate();
      String url =
          "http://api.fixer.io/latest?symbols="
              + toCurrency.currencyGetShort()
              + "&base="
              + currencyConverter.getFrom().currencyGetShort();
      ExchangeRates exchangeRates = restTemplate.getForObject(url, ExchangeRates.class);

      currencyConverter.setExchangeRate(
          exchangeRates.getRates().get(toCurrency.currencyGetShort()));
      currencyConverter.calcualteChangedAmount();
    }

    return currencyConverter;
  }
  @RequestMapping(value = "/timesheet", method = RequestMethod.POST)
  public ModelAndView sendTimeSheet(
      @ModelAttribute("timeSheetForm") TimeSheetForm tsForm, BindingResult result) {
    logger.info(
        "Processing form validation for employee {} ({}).",
        tsForm.getEmployeeId(),
        tsForm.getCalDate());
    tsFormValidator.validate(tsForm, result);
    if (result.hasErrors()) {
      logger.info(
          "TimeSheetForm for employee {} has errors. Form not validated.", tsForm.getEmployeeId());
      ModelAndView mavWithErrors = new ModelAndView("timesheet");
      mavWithErrors.addObject("timeSheetForm", tsForm);
      mavWithErrors.addObject("errors", result.getAllErrors());
      mavWithErrors.addObject("selectedProjectsJson", getSelectedProjectsJson(tsForm));
      mavWithErrors.addObject("selectedProjectRolesJson", getSelectedProjectRolesJson(tsForm));
      mavWithErrors.addObject("selectedProjectTasksJson", getSelectedProjectTasksJson(tsForm));
      mavWithErrors.addObject("selectedWorkplaceJson", getSelectedWorkplaceJson(tsForm));
      mavWithErrors.addObject("selectedActCategoriesJson", getSelectedActCategoriesJson(tsForm));
      mavWithErrors.addObject(
          "selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
      mavWithErrors.addObject("selectedCalDateJson", getSelectedCalDateJson(tsForm));
      mavWithErrors.addObject("getDateByDefault", getDateByDefault(tsForm.getEmployeeId()));
      mavWithErrors.addObject("getFirstWorkDate", getEmployeeFirstWorkDay(tsForm.getEmployeeId()));
      mavWithErrors.addAllObjects(getListsToMAV());

      return mavWithErrors;
    }
    TimeSheet timeSheet = timeSheetService.storeTimeSheet(tsForm);
    overtimeCauseService.store(timeSheet, tsForm);
    sendMailService.performMailing(tsForm);

    ModelAndView mav = new ModelAndView("selected");
    mav.addObject("timeSheetForm", tsForm);
    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    return mav;
  }
  /** 执行仪表属性提交 */
  @ResourceMapping(value = "submitMeteruseattributeForm")
  public Resultmsg onSubmitMeteruseattributeForm(
      @ModelAttribute("meteruseattribute") Meteruseattribute meteruseattribute,
      BindingResult result,
      SessionStatus status,
      ResourceRequest request,
      ResourceResponse response) {
    Resultmsg msg = new Resultmsg();

    String meterId = "";
    if (request.getParameter("meterId") != null) {
      meterId = request.getParameter("meterId");
      MeteruseattributeId id = new MeteruseattributeId();
      id.setMeterId(meterId);
      id.setMeterattrName(meteruseattribute.getId().getMeterattrName());
      meteruseattribute.setId(id);
    }

    new MeteruseattributeValidator().validate(meteruseattribute, result);
    if (result.hasErrors()) {
      logger.error(result);
      StringBuilder sb = new StringBuilder();
      for (ObjectError err : result.getAllErrors()) {
        sb.append(err.getDefaultMessage());
      }
      msg.setMsg(sb.toString());
    } else {
      try {
        meteruseinfoService.saveOrUpdateMeteruseattribute(meteruseattribute);
        status.setComplete();
        msg.setSuccess("true");
      } catch (Exception e) {
        logger.error(e);
        msg.setMsg(e.getMessage());
      }
    }
    return msg;
  }
  // Пользователь списывает занятость за продолжительные отпуск или болезнь.
  @RequestMapping(value = "/timesheetLong", method = RequestMethod.POST)
  public ModelAndView sendTimeSheetLong(
      @ModelAttribute("timeSheetForm") TimeSheetForm tsForm, BindingResult result) {
    logger.info(
        "Processing form validation for employee {} ({}) (long).",
        tsForm.getEmployeeId(),
        tsForm.getCalDate());
    tsFormValidator.validate(tsForm, result);
    if (result.hasErrors()) {
      logger.info(
          "TimeSheetForm for employee {} has errors. Form not validated (long).",
          tsForm.getEmployeeId());
      ModelAndView mavWithErrors = new ModelAndView("timesheet");
      mavWithErrors.addObject("timeSheetForm", tsForm);
      mavWithErrors.addObject("errors", result.getAllErrors());
      mavWithErrors.addObject("selectedProjectRolesJson", "[{row:'0', role:''}]");
      mavWithErrors.addObject("selectedProjectTasksJson", "[{row:'0', task:''}]");
      mavWithErrors.addObject("selectedProjectsJson", "[{row:'0', project:''}]");
      mavWithErrors.addObject("selectedActCategoriesJson", "[{row:'0', actCat:''}]");
      mavWithErrors.addObject("selectedWorkplace", "[{row:'0', workplace:''}]");
      mavWithErrors.addObject("selectedCalDateJson", "''");
      mavWithErrors.addObject(
          "selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
      mavWithErrors.addAllObjects(getListsToMAV());

      return mavWithErrors;
    }
    timeSheetService.storeTimeSheetLong(tsForm);
    sendMailService.performMailing(tsForm);

    ModelAndView mav = new ModelAndView("selected");
    mav.addObject("timeSheetForm", tsForm);
    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    return mav;
  }
  /**
   * @should void the old person address and replace it with a new one when it is edited
   * @should void the old person address and replace it with a new one when it is edited
   * @should not void the existing address if there are no changes
   */
  public String post(
      UiSessionContext sessionContext,
      PageModel model,
      @RequestParam("patientId") @BindParams Patient patient,
      @BindParams PersonAddress address,
      @SpringBean("patientService") PatientService patientService,
      @RequestParam("appId") AppDescriptor app,
      @RequestParam("returnUrl") String returnUrl,
      @SpringBean("adminService") AdministrationService administrationService,
      HttpServletRequest request,
      @SpringBean("messageSourceService") MessageSourceService messageSourceService,
      Session session,
      @SpringBean("patientValidator") PatientValidator patientValidator,
      UiUtils ui)
      throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonAddress() != null && address != null) {
      PersonAddress currentAddress = patient.getPersonAddress();
      if (!currentAddress.equalsContent(address)) {
        // void the old address and replace it with the new one
        patient.addAddress(address);
        currentAddress.setVoided(true);
      }
    }

    NavigableFormStructure formStructure = RegisterPatientFormBuilder.buildFormStructure(app);

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);
    RegistrationAppUiUtils.validateLatitudeAndLongitudeIfNecessary(address, errors);

    if (formStructure != null) {
      RegisterPatientFormBuilder.resolvePersonAttributeFields(
          formStructure, patient, request.getParameterMap());
    }

    if (!errors.hasErrors()) {
      try {
        // The person address changes get saved along as with the call to save patient
        patientService.savePatient(patient);
        InfoErrorMessageUtil.flashInfoMessage(
            request.getSession(),
            ui.message("registrationapp.editContactInfoMessage.success", patient.getPersonName()));

        return "redirect:" + returnUrl;
      } catch (Exception e) {
        log.warn("Error occurred while saving patient's contact info", e);
        session.setAttribute(
            UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "registrationapp.save.fail");
      }

    } else {
      model.addAttribute("errors", errors);
      StringBuffer errorMessage =
          new StringBuffer(messageSourceService.getMessage("error.failed.validation"));
      errorMessage.append("<ul>");
      for (ObjectError error : errors.getAllErrors()) {
        errorMessage.append("<li>");
        errorMessage.append(
            messageSourceService.getMessage(
                error.getCode(), error.getArguments(), error.getDefaultMessage(), null));
        errorMessage.append("</li>");
      }
      errorMessage.append("</ul>");
      session.setAttribute(
          UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    addModelAttributes(model, patient, formStructure, administrationService, returnUrl);
    // redisplay the form
    return null;
  }