@RequestMapping(method = RequestMethod.POST)
  public ModelAndView processFormSubmit(
      @RequestParam(value = CANCEL_PARAM, required = false) String cancel,
      @ModelAttribute("savingsProduct") @Valid SavingsProductFormBean savingsProductFormBean,
      BindingResult result,
      SessionStatus status) {

    ModelAndView modelAndView =
        new ModelAndView("redirect:/previewSavingsProducts.ftl?editFormview=editSavingsProduct");

    configurationDto = this.configurationServiceFacade.getAccountingConfiguration();
    modelAndView.addObject("GLCodeMode", configurationDto.getGlCodeMode());

    if (StringUtils.isNotBlank(cancel)) {
      modelAndView.setViewName(REDIRECT_TO_ADMIN_SCREEN);
      status.setComplete();
    } else if (result.hasErrors()) {
      new SavingsProductValidator().validateGroup(savingsProductFormBean, result);
      modelAndView.setViewName("editSavingsProduct");
    } else {
      new SavingsProductValidator().validateGroup(savingsProductFormBean, result);
      if (result.hasErrors()) {
        modelAndView.setViewName("editSavingsProduct");
      }
    }

    return modelAndView;
  }
  @Transactional
  @RequestMapping(value = "/fileRegistered", method = RequestMethod.POST)
  public ModelAndView newFileRegistered(
      @ModelAttribute("file") file file,
      BindingResult result1,
      @ModelAttribute("client") @Valid client client,
      BindingResult result2,
      ModelAndView model) {

    if (result1.hasErrors()) {
      model.setViewName("error");
      System.out.println("File error");
      return model;
    }

    if (result2.hasErrors()) {
      model.setViewName("error");
      System.out.println("Client error");
      return model;
    }

    model.setViewName("success");

    em.persist(client);
    em.flush();
    em.refresh(client);

    file.setClient_ClientID(client.getClientId());
    em.persist(file);

    mapFileWithEmployee(file.getFileNumber(), file.getFileName(), file.getAssignedAdvocate());

    return model;
  }
  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public String registerUserAccount(
      @ModelAttribute("user") UserDto accountDto,
      BindingResult result,
      HttpServletRequest request,
      Errors errors,
      Model model) {

    // Let's manually check if password and other fields are empty
    if (accountDto.getUsername().equals("")) {
      model.addAttribute("viewErrMsg", "Field 'Username' cannot be empty!");
      return "register";
    }

    if (accountDto.getPassword().equals("")) {
      model.addAttribute("viewErrMsg", "Field 'Password' cannot be empty!");
      // return new ModelAndView("register",
      return "register";
    }

    if (accountDto.getMatchingPassword().equals("")) {
      model.addAttribute("viewErrMsg", "Field 'Matching password' cannot be empty!");
      return "register";
    }

    if (!accountDto.getPassword().equals(accountDto.getMatchingPassword())) {
      model.addAttribute("viewErrMsg", "Passwords do not match!");
      return "register";
    }

    Users user = new Users();
    if (!result.hasErrors()) {
      user = createUserAccount(accountDto, result);
    }
    if (user == null) {

      model.addAttribute("viewErrMsg", "User not created! There is a user with such name!");
      return "register";
    }

    if (result.hasErrors()) {

      model.addAttribute("viewErrMsg", "Unknown error!");
      return "register";
    } else {

      // I added this from stackoverflow example
      authenticateUserAndSetSession(user, request);

      model.addAttribute("username", user.getusername());
      model.addAttribute("viewMsg", user.getusername() + " successfully registered!");
      return "settings";
    }
  }
  @RequestMapping(value = "/update-email", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updateEmail(
      final UpdateEmailForm updateEmailForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes,
      final HttpServletRequest request)
      throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors()
        && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
      bindingResult.rejectValue(
          "chkEmail",
          "validation.checkEmail.equals",
          new Object[] {},
          "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
      returnAction = errorUpdatingEmail(model);
    } else {
      try {
        customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
        GlobalMessages.addFlashMessage(
            redirectAttributes,
            GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.account.profile.confirmationUpdated",
            null);

        // Replace the spring security authentication with the new UID
        final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
        final Authentication oldAuthentication =
            SecurityContextHolder.getContext().getAuthentication();
        final UsernamePasswordAuthenticationToken newAuthentication =
            new UsernamePasswordAuthenticationToken(
                newUid, null, oldAuthentication.getAuthorities());
        newAuthentication.setDetails(oldAuthentication.getDetails());
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);
      } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "profile.email.unique");
        returnAction = errorUpdatingEmail(model);
      } catch (final PasswordMismatchException passwordMismatchException) {
        bindingResult.rejectValue("password", "profile.currentPassword.invalid");
        returnAction = errorUpdatingEmail(model);
      }
    }

    return returnAction;
  }
  @RequestMapping(value = "/update-password", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updatePassword(
      final UpdatePasswordForm updatePasswordForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes)
      throws CMSItemNotFoundException {
    getPasswordValidator().validate(updatePasswordForm, bindingResult);
    if (!bindingResult.hasErrors()) {
      if (updatePasswordForm.getNewPassword().equals(updatePasswordForm.getCheckNewPassword())) {
        try {
          customerFacade.changePassword(
              updatePasswordForm.getCurrentPassword(), updatePasswordForm.getNewPassword());
        } catch (final PasswordMismatchException localException) {
          bindingResult.rejectValue(
              "currentPassword",
              "profile.currentPassword.invalid",
              new Object[] {},
              "profile.currentPassword.invalid");
        }
      } else {
        bindingResult.rejectValue(
            "checkNewPassword",
            "validation.checkPwd.equals",
            new Object[] {},
            "validation.checkPwd.equals");
      }
    }

    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
      setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));

      model.addAttribute(
          "breadcrumbs",
          accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile.updatePasswordForm"));
      return ControllerConstants.Views.Pages.Account.AccountChangePasswordPage;
    } else {
      GlobalMessages.addFlashMessage(
          redirectAttributes,
          GlobalMessages.CONF_MESSAGES_HOLDER,
          "text.account.confirmation.password.updated",
          null);
      return REDIRECT_TO_PROFILE_PAGE;
    }
  }
  @RequestMapping(value = "/manage/category/update.html", method = RequestMethod.POST)
  public String processSubmit(
      @ModelAttribute("category") TicketCategory category,
      BindingResult result,
      SessionStatus status,
      ModelMap map) {
    validator.validate(category, result);
    if (result.hasErrors()) {
      return MANAGE_TICKET_CATEGORY_EDIT;
    }

    // jeśli walidacja się powiedzie to można przystąpić do zapisania kategorii
    if (category.getTicketCategoryId() != null) {
      categoryDAO.updateCategory(category);
    } else {
      if (category.getParentCategory() != null) {
        TicketCategory parent =
            categoryDAO.getById(category.getParentCategory()); // TODO: parametr w URLu
        categoryDAO.insertCategory(category, parent);
      } else {
        categoryDAO.insertRootCategory(category);
      }
    }
    status.setComplete();
    return "redirect:/manage/category/" + category.getTicketCategoryId() + "/show.html";
  }
  @ResponseBody
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  public ImmutableMap<String, Object> linkEdit(@Valid Link link, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      Map<String, Object> errorMessage = Maps.newHashMap();
      errorMessage.put("status", 0);
      List<FieldError> fes = bindingResult.getFieldErrors();
      for (FieldError fe : fes) {
        errorMessage.put(fe.getField(), fe.getDefaultMessage());
      }
      return ImmutableMap.<String, Object>builder().putAll(errorMessage).build();
    }

    if (link.getLinkId() == null || link.getLinkId() == 0) {
      Link result = linkService.save(link);
      if (result == null || result.getLinkId() == null || result.getLinkId() == 0) {
        LOGGER.warn("内容链接失败,链接{}", result);
        return ImmutableMap.<String, Object>of(
            "status", "0", "message", getMessage("link.addfailed.message"));
      }
      LOGGER.info("内容添加成功,链接ID{}", result.getLinkId());
      return ImmutableMap.<String, Object>of(
          "status", "1", "message", getMessage("link.addsuccess.message"));
    }
    try {
      linkService.save(link);
    } catch (Exception e) {
      LOGGER.error("链接修改失败,{}", e);
      return ImmutableMap.<String, Object>of(
          "status", "0", "message", getMessage("link.updatefailed.message"));
    }
    LOGGER.info("链接添加成功,{}", link);
    return ImmutableMap.<String, Object>of(
        "status", "1", "message", getMessage("link.updatesuccess.message"));
  }
  @RequestMapping(value = "curso/{codigo}/estrutura/adicionar", method = RequestMethod.POST)
  public String adicionar(
      @Valid EstruturaCurricular estruturaCurricular,
      BindingResult result,
      @PathVariable("codigo") Integer codigo,
      RedirectAttributes redirectAttributes,
      ModelMap modelMap) {
    Curso curso = this.cursoService.getCursoByCodigo(codigo);
    modelMap.addAttribute("curso", curso);

    if (result.hasErrors()) {
      return "curso/estrutura/adicionar";
    }

    if (estruturaCurricular.getCodigo().trim().isEmpty()) {
      result.rejectValue("codigo", "Repeat.estrutura.codigo", "Campo obrigatório.");
      return "curso/estrutura/adicionar";
    }

    if (estruturaCurricularService.getOutraEstruturaCurricularByCodigo(
            curso.getCodigo(), estruturaCurricular.getCodigo())
        != null) {
      result.rejectValue(
          "codigo", "Repeat.estruturas.codigo", "Ano e Semestre já existe para curso");
      return "curso/estrutura/adicionar";
    }

    estruturaCurricular.setCurso(curso);
    estruturaCurricular.setId(null);

    estruturaCurricularService.save(estruturaCurricular);

    redirectAttributes.addFlashAttribute("info", "Estrutura Curricular adicionada com sucesso.");
    return "redirect:/curso/" + curso.getCodigo() + "/visualizar";
  }
  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();
    }
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should populate model and view with obs occuring thrown APIException",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_ShouldPopulateModelAndViewWithObsOccuringThrownAPIException()
      throws Exception {

    MockHttpSession mockSession = new MockHttpSession();
    MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest();
    mockRequest.addParameter("editReason", "Test Edit Reason");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    mockObs.setConcept(new Concept());
    final String fileName = "test.txt";
    final byte[] content = "Hello World".getBytes();
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile("complexDataFile", fileName, "text/plain", content);

    mockRequest.addFile(mockMultipartFile);
    APIException apiException = new APIException("Test Exception Handling");
    when(obsService.saveObs(mockObs, "Test Edit Reason")).thenThrow(apiException);
    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);
    assertThat(modelAndView.getViewName(), is("module/radiology/radiologyObsForm"));
    assertNotNull(modelAndView);

    assertThat(modelAndView.getModelMap(), hasKey("obs"));
    Obs obs = (Obs) modelAndView.getModelMap().get("obs");
    assertThat(obs, is(mockObs));
  }
  @RequestMapping(value = URL_PROFILE_ADDTAG, method = RequestMethod.POST)
  public ModelAndView addTag(
      @ModelAttribute(COMMAND_TAG) @Valid Tool tool, BindingResult result, Locale locale) {

    if (result.hasErrors()) {
      // basic validation fails
      ModelAndView modelAndView = constructModelAndView(tool, locale);
      modelAndView.addObject(COMMAND_TAG, tool);

      return modelAndView;
    }

    if (profileService.isKnownTag(tool.getTagName())) {

      profileService.storeTag(tool.getTagName());
      ModelAndView modelAndView = new ModelAndView(new RedirectView(URL_ACCOUNT_VITEA));

      return modelAndView;
    } else if (tool.getTagName().equals(tool.getPreviousTagName())) {
      profileService.storeTag(tool.getTagName());
      ModelAndView modelAndView = new ModelAndView(new RedirectView(URL_ACCOUNT_VITEA));

      return modelAndView;
    } else {
      List<String> alternatives = profileService.searchForTags(tool.getTagName(), locale);

      ModelAndView modelAndView = constructModelAndView(tool, locale);
      modelAndView.addObject(COMMAND_TAG, tool);
      modelAndView.addObject("alternatives", alternatives);
      tool.setPreviousTagName(tool.getTagName());

      return modelAndView;
    }
  }
  /**
   * @see RadiologyObsFormController#voidObs(HttpServletRequest, HttpServletResponse, Order, Obs,
   *     String, String, Obs, BindingResult)
   */
  @Test
  @Verifies(
      value =
          "should void obs for given request, response, orderId, obsId, voidObs, voidReason, and obs",
      method =
          "voidObs(HttpServletRequest, HttpServletResponse, Order, Obs, String, String, Obs, BindingResult)")
  public void voidObs_ShouldVoidObsForGivenRequestResponseOrderIdObsIdVoidObsVoidReasonAndObs() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("voidObs", "voidObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);

    ModelAndView modelAndView =
        radiologyObsFormController.voidObs(
            mockRequest, null, mockRadiologyOrder, mockObs, "Test Void Reason");

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat(
        (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR),
        is("Obs.voidedSuccessfully"));
    assertThat(
        (String) modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
  /**
   * 모바일 기기 정보 등록 Service interface 호출 및 결과를 반환한다.
   *
   * @param deviceIdentVO
   */
  @RequestMapping(value = "/mbl/com/mdi/insertDeviceIdent.do")
  @Secured("ROLE_ADMIN")
  public String insertDeviceIdent(
      @ModelAttribute DeviceIdentVO deviceIdentVO, BindingResult bindingResult, ModelMap model) {

    beanValidator.validate(deviceIdentVO, bindingResult);
    if (bindingResult.hasErrors()) {

      model.addAttribute("browserCmmCodeDetailList", cmmUseService.selectCmmCodeList("COM083"));
      model.addAttribute("osCmmCodeDetailList", cmmUseService.selectCmmCodeList("COM084"));

      RequestContextHolder.getRequestAttributes()
          .setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
      return WebUtil.adjustViewName("/com/mdi/DeviceIdentRegist");
    }

    // 로그인VO에서 사용자 정보 가져오기
    LoginVO loginVO = (LoginVO) UserDetailsHelper.getAuthenticatedUser();
    deviceIdentVO.setMberId(loginVO.getId());
    deviceIdentVO.setBrowserNm("COM083");
    deviceIdentVO.setOsNm("COM084");

    deviceIdentService.insertDeviceIdent(deviceIdentVO);

    // XML 파일 생성
    deviceIdentService.createDeviceIndentListToXML();

    model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
    return WebUtil.redirectJsp(model, "/mbl/com/mdi/listDeviceIdent.do");
  }
  /**
   * 기 등록 된 PROCESS모니터링 정보를 수정 한다.
   *
   * @param processNm - PROCESS모니터링 model
   * @return String - 리턴 Url
   * @param processNm
   */
  @RequestMapping(value = "/utl/sys/prm/EgovComUtlProcessMonModify.do")
  public String updateProcessMon(
      @ModelAttribute("processMonVO") ProcessMonVO processMonVO,
      BindingResult bindingResult,
      Map commandMap,
      ModelMap model)
      throws Exception {

    // 로그인 객체 선언
    LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

    String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");
    if (sCmd.equals("")) {
      ProcessMonVO vo = processMonService.selectProcessMon(processMonVO);
      model.addAttribute("processMonVO", vo);
      return "egovframework/com/utl/sys/prm/EgovComUtlProcessMonModify";
    } else if (sCmd.equals("Modify")) {
      beanValidator.validate(processMonVO, bindingResult);
      if (bindingResult.hasErrors()) {
        ProcessMonVO vo = processMonService.selectProcessMon(processMonVO);
        model.addAttribute("processMonVO", vo);
        return "egovframework/com/utl/sys/prm/EgovComUtlProcessMonModify";
      }

      // 아이디 설정
      processMonVO.setFrstRegisterId((String) loginVO.getUniqId());
      processMonVO.setLastUpdusrId((String) loginVO.getUniqId());

      processMonService.updateProcessMon(processMonVO);
      return "forward:/utl/sys/prm/EgovComUtlProcessMonList.do";
    } else {
      return "forward:/utl/sys/prm/EgovComUtlProcessMonList.do";
    }
  }
  /**
   * PROCESS모니터링 정보를 신규로 등록한다.
   *
   * @param processNm - PROCESS모니터링 model
   * @return String - 리턴 Url
   * @param processNm
   */
  @RequestMapping(value = "/utl/sys/prm/EgovComUtlProcessMonRegist.do")
  public String insertProcessMon(
      @ModelAttribute("processMonVO") ProcessMonVO processMonVO,
      BindingResult bindingResult,
      ModelMap model)
      throws Exception {

    // 0. Spring Security 사용자권한 처리
    Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
    if (!isAuthenticated) {
      model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
      return "egovframework/com/uat/uia/EgovLoginUsr";
    }

    // 로그인 객체 선언
    LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

    if (processMonVO.getProcessNm() == null || processMonVO.getProcessNm().equals("")) {
      return "egovframework/com/utl/sys/prm/EgovComUtlProcessMonRegist";
    }

    // 서버  validate 체크
    beanValidator.validate(processMonVO, bindingResult);
    if (bindingResult.hasErrors()) {
      return "egovframework/com/utl/sys/prm/EgovComUtlProcessMonRegist";
    }

    // 아이디 설정
    processMonVO.setFrstRegisterId((String) loginVO.getUniqId());
    processMonVO.setLastUpdusrId((String) loginVO.getUniqId());

    processMonService.insertProcessMon(processMonVO);
    return "forward:/utl/sys/prm/EgovComUtlProcessMonList.do";
  }
  @RequestMapping(value = "/addCustomer.htm", method = RequestMethod.POST)
  public ModelAndView addCustomer(
      @ModelAttribute("customer") @Valid Customer customer,
      BindingResult result,
      SessionStatus status) {

    ModelAndView mav = new ModelAndView();

    if (result.hasErrors()) {
      LOGGER.info("Error occurred in AddCustomer form ");
      mav.setViewName("AddCustomer");
      mav.addObject("customer", customer);
      return mav;
    } else {
      int resultValue = 0;
      resultValue = customerService.addCustomer(customer);
      if (StringUtils.isBlank(customer.getCustomerID()))
        customer.setCustomerID(Integer.toString(resultValue));

      LOGGER.info("Customer added !! ");
      mav.setViewName("AddCustomer");
      // mav.addObject("resultValue", resultValue);
      mav.addObject("customer", customer);
      return mav;
    }
  }
Example #17
0
  public CreateJournalEntry(
      TravelLogDAO dao,
      Journal journal,
      BindingResult result,
      boolean preload,
      ModelMap map,
      Logger logger) {

    // If we're preloading the sample, just skip to the preload method
    if (preload) {
      preloadJournal(dao, logger);
    } else {
      if (journal.getTitle().length() == 0) {
        result.reject("title", "Title cannot be blank");
      }

      // check to make sure we don't already have a journal
      if (dao.getJournals().size() > 0) {
        result.reject("title", "Journal already exists.  Please reload page.");
      }

      if (!result.hasErrors()) {
        dao.saveJournal(journal);
      }
    }
  }
  // posting edited comment
  @RequestMapping(
      value = "/posts/{postId:\\d+}/comments/{commentId:\\d+}/edit",
      method = RequestMethod.POST)
  public String onPostCommentEdit(
      @PathVariable long postId,
      @PathVariable long commentId,
      Model model,
      Principal principal,
      @Valid Comment editedComment,
      BindingResult result) {

    Comment oldComment = commentService.findById(commentId);
    Post post = postService.findById(postId);
    if (oldComment != null
        && post != null
        && post.getPostId() == oldComment.getPost().getPostId()) {
      if (result.hasErrors()) {
        model.addAttribute("logged_user", principal.getName());
        model.addAttribute("post", post);
        model.addAttribute("comments", commentService.findAllCommentsOfPost(postId));
        return "comment_edit";
      } else {
        commentService.merge(oldComment, editedComment);
        return "redirect:/posts/" + postId + "/comments";
      }
    } else return "404";
  }
  /**
   * 모바일 기기 정보 수정 Service interface 호출 및 결과를 반환한다.
   *
   * @param deviceIdentVO
   */
  @RequestMapping(value = "/mbl/com/mdi/updateDeviceIdent.do")
  @Secured("ROLE_ADMIN")
  public String updateDeviceIdent(
      @ModelAttribute DeviceIdentVO deviceIdentVO, BindingResult bindingResult, ModelMap model) {

    // Validation
    beanValidator.validate(deviceIdentVO, bindingResult);
    if (bindingResult.hasErrors()) {

      model.addAttribute("browserCmmCodeDetailList", cmmUseService.selectCmmCodeList("COM083"));
      model.addAttribute("osCmmCodeDetailList", cmmUseService.selectCmmCodeList("COM084"));

      RequestContextHolder.getRequestAttributes()
          .setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
      return WebUtil.adjustViewName("/com/mdi/DeviceIdentEdit");
    }

    deviceIdentService.updateDeviceIdent(deviceIdentVO);

    // XML 파일 생성
    deviceIdentService.createDeviceIndentListToXML();

    model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
    return WebUtil.redirectJsp(model, "/mbl/com/mdi/listDeviceIdent.do");
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should edit obs with edit reason and complex concept",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_ShouldEditObsWithEditReasonAndComplexConcept() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("saveObs", "saveObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    ConceptComplex concept = new ConceptComplex();
    ConceptDatatype cdt = new ConceptDatatype();
    cdt.setHl7Abbreviation("ED");
    concept.setDatatype(cdt);
    mockObs.setConcept(concept);

    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved"));
    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
  /**
   * @see RadiologyObsFormController#unvoidObs(HttpServletRequest, HttpServletResponse, Obs, String)
   */
  @Test
  @Verifies(
      value = "should unvoid voided obs for given request, response and obs",
      method = "unvoidObs(HttpServletRequest, HttpServletResponse, Obs, String)")
  public void unvoidObs_shouldUnvoidVoidedObsForGivenRequestResponseAndObs() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("unvoidObs", "unvoidObs");
    mockRequest.setSession(mockSession);
    when(obsErrors.hasErrors()).thenReturn(false);

    mockObs.setVoided(true);

    ModelAndView modelAndView = radiologyObsFormController.unvoidObs(mockRequest, null, mockObs);
    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
    assertThat(
        (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR),
        is("Obs.unvoidedSuccessfully"));
  }
  /**
   * 기 등록 된 지식정보평가 정보를 수정 한다.
   *
   * @param AppraisalknoAps - 지식정보평가 model
   * @return String - 리턴 Url
   * @param knoAps
   */
  @RequestMapping(value = "/dam/app/EgovComDamAppraisalModify.do")
  public String updateKnoAppraisal(
      @ModelAttribute("knoId") KnoAppraisal knoAppraisal,
      BindingResult bindingResult,
      Map commandMap,
      ModelMap model)
      throws Exception {

    // 로그인 객체 선언
    LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

    String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");
    if (sCmd.equals("")) {
      KnoAppraisal vo = knoAppraisalService.selectKnoAppraisal(knoAppraisal);
      model.addAttribute("knoAppraisal", vo);
      return "egovframework/com/dam/app/EgovComDamAppraisalModify";
    } else if (sCmd.equals("Modify")) {
      beanValidator.validate(knoAppraisal, bindingResult);
      if (bindingResult.hasErrors()) {
        KnoAppraisal vo = knoAppraisalService.selectKnoAppraisal(knoAppraisal);
        model.addAttribute("knoAppraisal", vo);
        return "egovframework/com/dam/app/EgovComDamAppraisalModify";
      }

      // 아이디 설정
      // knoAppraisal.setFrstRegisterId((String)loginVO.getUniqId());
      // knoAppraisal.setLastUpdusrId((String)loginVO.getUniqId());
      knoAppraisal.setSpeId((String) loginVO.getUniqId());

      knoAppraisalService.updateKnoAppraisal(knoAppraisal);
      return "forward:/dam/app/EgovComDamAppraisalList.do";
    } else {
      return "forward:/dam/app/EgovComDamAppraisalList.do";
    }
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value =
          "should edit obs with edit reason, complex concept and request which is an instance of multihttpserveletrequest",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void
      saveObs_ShouldEditObsWithEditReasonComplexConceptANdRequestWhichIsAnInstanceOfMultiHTTPServletRequest() {

    MockHttpSession mockSession = new MockHttpSession();
    MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest();
    mockRequest.addParameter("saveObs", "saveObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    ConceptComplex concept = new ConceptComplex();
    ConceptDatatype cdt = new ConceptDatatype();
    cdt.setHl7Abbreviation("ED");
    concept.setDatatype(cdt);
    mockObs.setConcept(concept);
    final String fileName = "test.txt";
    final byte[] content = "Hello World".getBytes();
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile("complexDataFile", fileName, "text/plain", content);

    mockRequest.addFile(mockMultipartFile);

    radiologyObsFormController.saveObs(
        mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved"));
  }
Example #24
0
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  public String processUpdate(
      @Validated ProductForm formProduct, BindingResult result, Model model) {
    if (result.hasErrors()) {
      return "products/edit";
    }

    Product product = (Product) formProduct.getProduct();
    if (product.getId() != null) {
      // product update
      product = productDAO.findById(formProduct.getId());

      product.setName(formProduct.getName());
      product.setShared(formProduct.getShared());
      product.setAmount(formProduct.getAmount());
      product.setMaxPoints(formProduct.getMaxPoints());
      product.setPoints(formProduct.getPoints());
      product.setDescription(formProduct.getDescription());
    }

    //  Unit returned by formProduct contains only the ID in the name property of Unit instance.
    Unit unit = unitDAO.findById(formProduct.getUnitId());
    product.setUnit(unit);

    //  Category returned by formProduct contains only the ID in the name property of Category
    // instance.
    ProductCategory category = this.categoryDAO.findById(formProduct.getCategoryId());
    product.setCategory(category);

    this.productDAO.update(product);
    return "redirect:/products/list";
  }
  @RequestMapping(value = "{project}", method = RequestMethod.POST)
  public ModelAndView postHandler(
      @PathVariable("project") String projectName,
      @ModelAttribute("version") Version version,
      BindingResult result) {

    ModelAndView mav = new ModelAndView();
    mav.addObject("projectName", projectName);
    mav.setViewName("settings/versions");

    // TODO - validate (add hibernate validator)
    if (result.hasErrors()) {
      return mav;
    }

    /* success */
    //        if (pipelineService.addVersion(projectName, version.getNumber())) {
    //            mav.setViewName("redirect:/settings/versions/" + projectName);
    //            return mav;
    //        }

    // TODO - display error on the page
    mav.addObject("error", String.format("Version %s has not been added.", version.getNumber()));
    return mav;
  }
  /**
   * Processes the submit of update contact form.
   *
   * @param dto The form object.
   * @param result The binding result describing whether there is validation errors.
   * @param attributes The redirect attributes used when request is redirected forward.
   * @return A redirect view name to the view contract page.
   * @throws NotFoundException
   */
  @RequestMapping(value = "/contact/update", method = RequestMethod.POST)
  public String updateContact(
      @Valid @ModelAttribute(MODEL_ATTRIBUTE_CONTACT) ContactDTO dto,
      BindingResult result,
      RedirectAttributes attributes)
      throws NotFoundException {
    LOGGER.debug("Updating contact with information: {}", dto);

    if (result.hasErrors()) {
      LOGGER.debug("Form was submitted with validation errors. Rendering form view.");
      return UPDATE_CONTACT_VIEW;
    }

    Contact updated = service.update(dto);
    LOGGER.debug("Updated contact with information: {}", updated);

    attributes.addAttribute(PARAMETER_CONTACT_ID, updated.getId());
    addFeedbackMessage(
        attributes,
        FEEDBACK_MESSAGE_KEY_CONTACT_UPDATED,
        updated.getFirstName(),
        updated.getLastName());

    return createRedirectViewPath(REQUEST_MAPPING_VIEW_CONTACT);
  }
  @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");
  }
  @RequestMapping(value = "/message", method = RequestMethod.POST)
  public String handleMessageSendForm(
      @ModelAttribute("currentUser") CurrentUser currentUser,
      @Valid @ModelAttribute("form") MessageForm form,
      BindingResult bindingResult) {
    LOGGER.debug("Processing message send form={}, bindingResult={}", form, bindingResult);
    if (bindingResult.hasErrors()) {
      // failed validation
      return "message";
    }
    try {
      if (currentUserDetailsService.checkUserRole(form.getRecipient()) == Role.ADMIN) {
        messageService.sendMessageM(form, currentUser);
      } else {
        messageService.sendMessage(form, currentUser);
      }

    } catch (DataIntegrityViolationException e) {
      // probably email already exists - very rare case when multiple admins are adding same user
      // at the same time and form validation has passed for more than one of them.
      //            LOGGER.warn("Exception occurred when trying to save the user, assuming duplicate
      // email", e);
      return "message";
    }
    // ok, redirect
    return "redirect:/message";
  }
  @RequestMapping(
      value = {"curso/{codigo}/estrutura/{id}/editar", "/{id}/editar"},
      method = RequestMethod.POST)
  public String atualizar(
      @Valid EstruturaCurricular estrutura,
      BindingResult result,
      RedirectAttributes redirectAttributes,
      @PathVariable("id") Integer id,
      @PathVariable("codigo") Integer codigo,
      ModelMap modelMap) {
    Curso curso = cursoService.getCursoByCodigo(codigo);

    modelMap.addAttribute("curso", curso);

    EstruturaCurricular oldEstrutura =
        estruturaCurricularService.getOutraEstruturaCurricularByCodigo(
            estrutura.getId(), estrutura.getCodigo());

    if (result.hasErrors()) {
      return "curso/estrutura/editar";
    }

    estrutura.setCurso(oldEstrutura.getCurso());
    estrutura.setCurriculos(oldEstrutura.getCurriculos());
    estrutura.setCurso(curso);
    estruturaCurricularService.update(estrutura);
    redirectAttributes.addFlashAttribute("info", "Estrutura Curricular atualizada com sucesso");
    return "redirect:/curso/" + curso.getCodigo() + "/visualizar";
  }
  @RequestMapping(
      value = {"/add-document-{userId}"},
      method = RequestMethod.POST)
  public String uploadDocument(
      @Valid FileBucket fileBucket, BindingResult result, ModelMap model, @PathVariable int userId)
      throws IOException {

    if (result.hasErrors()) {
      System.out.println("validation errors");
      User user = userService.findById(userId);
      model.addAttribute("user", user);

      List<UserDocument> documents = userDocumentService.findAllByUserId(userId);
      model.addAttribute("documents", documents);

      return "managedocuments";
    } else {

      System.out.println("Fetching file");

      User user = userService.findById(userId);
      model.addAttribute("user", user);

      saveDocument(fileBucket, user);

      return "redirect:/add-document-" + userId;
    }
  }