/**
   * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String,
   *     String, User, BindingResult)
   */
  @Test
  @Verifies(
      value =
          "do not set the user property forcePassword to false after unsuccessful password change",
      method = "handleSubmission()")
  public void handleSubmission_shouldNotChangeTheUserPropertyForcePasswordChangeToFalse()
      throws Exception {
    User user = Context.getAuthenticatedUser();
    new UserProperties(user.getUserProperties()).setSupposedToChangePassword(true);

    UserService us = Context.getUserService();
    us.saveUser(user, "Openmr5xy");

    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

    controller.handleSubmission(
        new MockHttpSession(),
        "Passw0rd",
        "Pasw0rd",
        "",
        "",
        "",
        Context.getAuthenticatedUser(),
        errors);

    User modifiedUser = us.getUser(user.getId());
    assertTrue(new UserProperties(modifiedUser.getUserProperties()).isSupposedToChangePassword());
  }
  /**
   * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String,
   *     String, User, BindingResult)
   */
  @Test
  @Verifies(value = "set the secret question and answer of the user", method = "handleSubmission()")
  public void handleSubmission_shouldSetTheUserSecretQuestionAndAnswer() throws Exception {
    User user = Context.getAuthenticatedUser();
    new UserProperties(user.getUserProperties()).setSupposedToChangePassword(true);

    UserService us = Context.getUserService();
    us.saveUser(user, "Openmr5xy");

    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

    controller.handleSubmission(
        new MockHttpSession(),
        "Passw0rd",
        "Passw0rd",
        "test_question",
        "test_answer",
        "test_answer",
        Context.getAuthenticatedUser(),
        errors);

    User modifiedUser = us.getUser(user.getId());

    assertTrue(us.isSecretAnswer(modifiedUser, "test_answer"));
  }
  @RequestMapping("/module/report/checkSession.htm")
  public String checkSession(HttpServletRequest request, Model model) {
    if (Context.getAuthenticatedUser() != null && Context.getAuthenticatedUser().getId() != null) {
      model.addAttribute("session", "1");
    } else {
      model.addAttribute("session", "0");
    }

    return "/module/report/session/checkSession";
  }
  @RequestMapping(method = RequestMethod.GET)
  public void inventory(ModelMap model) throws IOException {
    model.addAttribute("modelBase", "openhmis.inventory.institution");

    model.addAttribute(
        "showStockTakeLink",
        Context.getAuthenticatedUser() != null
            && WellKnownOperationTypes.getAdjustment()
                .userCanProcess(Context.getAuthenticatedUser()));
    model.addAttribute("isOperationNumberAutoGenerated", IdgenHelper.isOperationNumberGenerated());
  }
  public static void addBothPersonalAndGlobalNotesToJSON(
      String searchPhrase, Integer patientId, JSONObject json) {
    JSONArray allPersonalNotes =
        GeneratingJson.getAllPersonalNotesOnASearch(searchPhrase, patientId);
    JSONArray allGlobalNotes = GeneratingJson.getAllGlobalNotesOnASearch(searchPhrase, patientId);
    String userName = Context.getAuthenticatedUser().getUsername();
    String systemId = Context.getAuthenticatedUser().getSystemId();

    json.put("personalNotes", allPersonalNotes);
    json.put("globalNotes", allGlobalNotes);
    json.put("currentUser", null == userName ? systemId : userName);
  }
  /** @see RadiologyObsFormController#updateReadingPhysician(Study) */
  @Test
  @Verifies(
      value = "should not update reading physician for given study with reading physician",
      method = "updateReadingPhysician(Study)")
  public void
      updateReadingPhysician_shouldNotUpdateReadingPhysicianForGivenStudyWithReadingPhysician()
          throws Exception {

    User otherMockReadingPhysician = RadiologyTestData.getMockRadiologyReadingPhysician();
    assertThat(mockReadingPhysician, is(not(otherMockReadingPhysician)));

    mockStudy.setReadingPhysician(mockReadingPhysician);
    when(Context.getAuthenticatedUser()).thenReturn(otherMockReadingPhysician);

    Method updateReadingPhysicianMethod =
        radiologyObsFormController
            .getClass()
            .getDeclaredMethod(
                "updateReadingPhysician", new Class[] {org.openmrs.module.radiology.Study.class});
    updateReadingPhysicianMethod.setAccessible(true);

    assertThat(mockStudy.getReadingPhysician(), is(mockReadingPhysician));

    updateReadingPhysicianMethod.invoke(radiologyObsFormController, new Object[] {mockStudy});

    assertThat(mockStudy.getReadingPhysician(), is(mockReadingPhysician));
  }
  public static JSONArray generateAllCategoriesJSON() {
    JSONArray jsonArray = new JSONArray();
    List<ChartSearchCategoryDisplayName> allDisplayNames =
        chartSearchService.getAllCategoryDisplayNames();
    List<CategoryFilter> allCats = chartSearchService.getAllCategoryFilters();

    for (CategoryFilter cat : allCats) {
      JSONObject json = new JSONObject();
      String name = cat.getCategoryName();
      String description = cat.getCategoryDescription();
      String displayName = "";
      String uuid = cat.getCategoryUuid();

      for (ChartSearchCategoryDisplayName catName : allDisplayNames) {

        if (Context.getAuthenticatedUser()
                .getUserId()
                .equals(catName.getPreference().getPreferenceOwner().getUserId())
            && catName.getCategoryFilter().getCategoryName().equals(name)) {
          displayName = catName.getDisplayName();
          uuid = catName.getUuid();
        }
      }

      json.put("name", name);
      json.put("uuid", uuid);
      json.put("displayName", displayName);
      json.put("description", description);

      jsonArray.add(json);
    }

    return jsonArray;
  }
  public static JSONArray getAllPersonalNotesOnASearch(String searchPhrase, Integer patientId) {
    JSONArray jsonArr = new JSONArray();
    List<ChartSearchNote> allNotes = chartSearchService.getAllSearchNotes();
    List<ChartSearchNote> allPersonalNotes = new ArrayList<ChartSearchNote>();

    for (ChartSearchNote note : allNotes) {
      if (note.getPatient().getPatientId().equals(patientId)
          && note.getSearchPhrase().equals(searchPhrase)
          && note.getPriority().equals("LOW")
          && Context.getAuthenticatedUser().getUserId().equals(note.getNoteOwner().getUserId())) {
        allPersonalNotes.add(note);
      }
    }

    if (!allPersonalNotes.isEmpty()) {
      for (ChartSearchNote note : allPersonalNotes) {
        JSONObject json = new JSONObject();
        String userName = note.getNoteOwner().getUsername();
        String systemId = note.getNoteOwner().getSystemId();

        json.put("uuid", note.getUuid());
        json.put("createdOrLastModifiedAt", note.getCreatedOrLastModifiedAt().getTime());
        json.put("backgroundColor", note.getDisplayColor());
        json.put(
            "formatedCreatedOrLastModifiedAt",
            Context.getDateFormat().format(note.getCreatedOrLastModifiedAt()));
        addPhraseAndCommentNotesAttributes(note, json);
        json.put("noteOwner", null == userName ? systemId : userName);

        jsonArr.add(json);
      }
    }
    return jsonArr;
  }
  @RequestMapping("/module/hirifxray/participant.form")
  public String viewParticipant(
      ModelMap model,
      @RequestParam(value = "id", required = true) Integer id,
      @RequestParam(value = "type", required = false) Concept type,
      @RequestParam(value = "xrayId", required = false) Encounter encounter) {

    User currentUser = Context.getAuthenticatedUser();
    if (currentUser == null) {
      return "redirect:/login.htm";
    }

    Xray xray = new Xray(encounter);

    model.addAttribute("type", type);
    model.addAttribute("xray", xray);

    Patient patient = Context.getPatientService().getPatient(id);
    model.addAttribute("patient", patient);

    model.addAttribute("xrayTypes", HirifMetadata.getXrayTypes());
    model.addAttribute("xraysByType", HirifUtil.getXraysByType(patient));

    model.addAttribute("xrayLocations", HirifMetadata.getXrayLocations());

    model.addAttribute("xrayStatuses", HirifMetadata.getXrayStatuses());
    model.addAttribute("notDoneStatus", HirifMetadata.getNotDoneStatus());
    model.addAttribute("completedStatus", HirifMetadata.getCompletedStatus());

    return null;
  }
  /**
   * @see
   *     org.openmrs.api.AdministrationService#mrnGeneratorLog(java.lang.String,java.lang.Integer,java.lang.Integer)
   */
  public void mrnGeneratorLog(String site, Integer start, Integer count) {
    PreparedStatement ps = null;
    try {
      String sql = "insert into `";
      sql += OpenmrsConstants.DATABASE_BUSINESS_NAME + "`.ext_mrn_log ";
      sql += "(date_generated, generated_by, site, mrn_first, mrn_count) values (?, ?, ?, ?, ?)";

      ps = sessionFactory.getCurrentSession().connection().prepareStatement(sql);

      ps.setTimestamp(1, new Timestamp(new Date().getTime()));
      ps.setInt(2, Context.getAuthenticatedUser().getUserId());
      ps.setString(3, site);
      ps.setInt(4, start);
      ps.setInt(5, count);
      ps.execute();
    } catch (Exception e) {
      throw new DAOException("Error generating mrn log", e);
    } finally {
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          log.error("Error generated while closing statement", e);
        }
      }
    }
  }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
   *     java.lang.Object, org.springframework.validation.Errors)
   */
  protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors errs)
      throws Exception {

    Drug drug = (Drug) obj;

    Map<String, Object> map = new HashMap<String, Object>();
    String defaultVerbose = "false";

    if (Context.isAuthenticated()) {
      if (drug.getConcept() != null)
        map.put("conceptName", drug.getConcept().getName(request.getLocale()));
      defaultVerbose =
          Context.getAuthenticatedUser()
              .getUserProperty(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE);
    }

    map.put("defaultVerbose", defaultVerbose.equals("true") ? true : false);

    String editReason = request.getParameter("editReason");
    if (editReason == null) editReason = "";

    map.put("editReason", editReason);

    return map;
  }
  /**
   * Updates reading physician for given study
   *
   * @param study for which the reading physician should be updated
   * @should update reading physician for given study and user authenticated as reading physician
   * @should not update reading physician if user is not authenticated as reading physician
   * @should not update reading physician for given study with reading physician
   */
  private void updateReadingPhysician(Study study) {

    User user = Context.getAuthenticatedUser();
    if (user.hasRole(READING_PHYSICIAN, true) && study.getReadingPhysician() == null)
      study.setReadingPhysician(user);
    radiologyService.saveStudy(study);
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should return redirecting model and view for not authenticated user",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_shouldReturnRedirectingModelAndViewForNotAuthenticatedUser() {

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

    when(Context.getAuthenticatedUser()).thenReturn(null);

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

    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
 /**
  * Creates a new person stub.
  *
  * @param given
  * @param middle
  * @param family
  * @param birthdate
  * @param dateformat
  * @param age
  * @param gender
  * @return PersonListItem person stub created
  */
 public Object createPerson(
     String given,
     String middle,
     String family,
     String birthdate,
     String dateformat,
     String age,
     String gender) {
   log.error(
       given
           + " "
           + middle
           + " "
           + family
           + " "
           + birthdate
           + " "
           + dateformat
           + " "
           + age
           + " "
           + gender);
   User user = Context.getAuthenticatedUser();
   Person p = new Person();
   p.setPersonCreator(user);
   p.setPersonDateCreated(new Date());
   p.setPersonChangedBy(user);
   p.setPersonDateChanged(new Date());
   if (StringUtils.isEmpty(gender)) {
     log.error("Gender cannot be null.");
     return String.valueOf("Gender cannot be null.");
   } else if (gender.toUpperCase().contains("M")) {
     p.setGender("M");
   } else if (gender.toUpperCase().contains("F")) {
     p.setGender("F");
   } else {
     log.error("Gender must be 'M' or 'F'.");
     return new String("Gender must be 'M' or 'F'.");
   }
   if ("".equals(given) || "".equals(family)) {
     log.error("Given name and family name cannot be null.");
     return new String("Given name and family name cannot be null.");
   }
   PersonName name = new PersonName(given, middle, family);
   name.setCreator(user);
   name.setDateCreated(new Date());
   name.setChangedBy(user);
   name.setDateChanged(new Date());
   p.addName(name);
   try {
     Date d = updateAge(birthdate, dateformat, age);
     p.setBirthdate(d);
   } catch (java.text.ParseException pe) {
     log.error(pe);
     return new String("Birthdate cannot be parsed.");
   }
   p.setGender(gender);
   Person person = Context.getPersonService().savePerson(p);
   return PersonListItem.createBestMatch(person);
 }
 /** @see ChangePasswordFormController#formBackingObject() */
 @Test
 @Verifies(value = "return an authenticated User", method = "formBackingObject()")
 public void formBackingObject_shouldReturnAuthenticatedUser() throws Exception {
   ChangePasswordFormController controller = new ChangePasswordFormController();
   User user = controller.formBackingObject();
   assertNotNull(user);
   assertEquals(Context.getAuthenticatedUser(), user);
 }
  /** @see AdministrationSectionExt#getLinks() */
  public Map<String, String> getLinks() {
    User authenticatedUser = Context.getAuthenticatedUser();
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

    Boolean rolePrivilege =
        authenticatedUser.hasPrivilege(org.openmrs.util.PrivilegeConstants.MANAGE_ROLES);
    if (rolePrivilege) {
      map.put(ModuleWebConstants.ROLE_CREATION_PAGE, "openhmis.inventory.admin.role");
    }

    Boolean itemPrivilege =
        PrivilegeUtil.hasPrivileges(authenticatedUser, PrivilegeWebConstants.ITEM_PAGE_PRIVILEGES);
    if (itemPrivilege) {
      map.put(ModuleWebConstants.ITEMS_PAGE, "openhmis.inventory.admin.items");
    }

    if (PrivilegeUtil.hasPrivileges(
        authenticatedUser, PrivilegeWebConstants.ITEM_ATTRIBUTE_TYPE_PAGE_PRIVILEGES)) {
      map.put(
          ModuleWebConstants.ITEM_ATTRIBUTE_TYPES_PAGE,
          "openhmis.inventory.admin.item.attribute.types");
    }

    if (PrivilegeUtil.hasPrivileges(
        authenticatedUser, PrivilegeWebConstants.DEPARTMENT_PAGE_PRIVILEGES)) {
      map.put(ModuleWebConstants.DEPARTMENTS_PAGE, "openhmis.inventory.admin.departments");
    }

    if (PrivilegeUtil.hasPrivileges(
        authenticatedUser, PrivilegeWebConstants.INSTITUTION_PAGE_PRIVILEGES)) {
      map.put(ModuleWebConstants.INSTITUTIONS_PAGE, "openhmis.inventory.admin.institutions");
    }

    Boolean stockroomPrivilege =
        PrivilegeUtil.hasPrivileges(
            authenticatedUser, PrivilegeWebConstants.STOCKROOM_PAGE_PRIVILEGES);
    if (stockroomPrivilege) {
      map.put(ModuleWebConstants.STOCKROOMS_PAGE, "openhmis.inventory.admin.stockrooms");
      map.put(ModuleWebConstants.OPERATION_TYPES_PAGE, "openhmis.inventory.admin.operationTypes");
    }

    // These links are put down here so that the links layout a little nicer
    if (stockroomPrivilege) {
      map.put(ModuleWebConstants.OPERATIONS_PAGE, "openhmis.inventory.admin.operations");
    }
    if (itemPrivilege) {
      map.put(
          ModuleWebConstants.ITEM_CONCEPT_SUGGESTION_PAGE,
          "openhmis.inventory.admin.items.concept.mapping");
    }

    if (PrivilegeUtil.hasPrivileges(
        authenticatedUser, PrivilegeWebConstants.SETTINGS_PAGE_PRIVILEGES)) {
      map.put(ModuleWebConstants.SETTINGS_PAGE, "openhmis.inventory.admin.settings");
    }

    return map;
  }
  public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
      throws Throwable {
    log.debug("Intercepted an Encounter Save");
    if (method.getName().equals("saveEncounter")) {
      User autheticatedUser = Context.getAuthenticatedUser();

      if (autheticatedUser != null) {
        Collection<Role> userRoles = autheticatedUser.getAllRoles();

        if (userRoles != null && userRoles.size() > 0) {
          String prop =
              Context.getAdministrationService()
                  .getGlobalProperty(OncologyPOCConstants.GP_INTERCEPTROLES);

          if (prop != null) {
            String[] interceptRoles = prop.split(",");
            boolean interceptThisOne = false;
            Role interceptedRole = null;

            for (String role : interceptRoles) {
              for (Role userRole : userRoles) {
                if (role.equalsIgnoreCase(userRole.getRole())) {
                  interceptThisOne = true;
                  interceptedRole = userRole;
                  break;
                }
              }
              if (interceptThisOne) break;
            }

            if (interceptThisOne) {
              Encounter encounter = (Encounter) returnValue;
              if (encounter != null
                  && encounter.getPatient() != null
                  && encounter.getForm() != null) {
                OncologyPOCService service =
                    (OncologyPOCService) Context.getService(OncologyPOCService.class);
                SubEncounter subEncounter = service.getSubEncounter(encounter.getEncounterId());

                if (interceptedRole.hasPrivilege(OncologyPOCConstants.PRIV_CLINICIAN)) {
                  log.debug("Deleting subEncounter");
                  service.deleteSubEncounter(subEncounter);
                } else {
                  log.debug("Saving subEncounter");
                  if (subEncounter == null) {
                    subEncounter = new SubEncounter();
                    subEncounter.setEncounterId(encounter.getEncounterId());
                  }
                  service.saveSubEncounter(subEncounter);
                }
              }
            }
          }
        }
      }
    }
  }
 @RequestMapping(value = MODULE_URL + "subscribe", method = RequestMethod.GET)
 public String subscribe(ModelMap model) {
   ImportedPackage dictionary = getService().getSubscribedDictionary();
   if (dictionary == null) {
     model.addAttribute("user", Context.getAuthenticatedUser());
     model.addAttribute("conceptCount", Context.getConceptService().getAllConcepts().size());
     return null;
   } else {
     return "redirect:subscribed.form";
   }
 }
  /** @deprecated see reportingcompatibility module */
  @Deprecated
  public void createReportObject(AbstractReportObject ro) throws DAOException {

    ReportObjectWrapper wrappedReportObject = new ReportObjectWrapper(ro);
    User user = Context.getAuthenticatedUser();
    Date now = new Date();
    wrappedReportObject.setCreator(user);
    wrappedReportObject.setDateCreated(now);
    wrappedReportObject.setVoided(false);
    sessionFactory.getCurrentSession().save(wrappedReportObject);
  }
  /**
   * This method is synchronized to prevent multiple check-ins in a row at the same location and
   * during the same visit. See #579.
   *
   * @see org.openmrs.module.emrapi.adt.AdtService#checkInPatient(org.openmrs.Patient,
   *     org.openmrs.Location, org.openmrs.Provider, java.util.List, java.util.List, boolean)
   */
  @Override
  @Transactional
  public synchronized Encounter checkInPatient(
      Patient patient,
      Location where,
      Provider checkInClerk,
      List<Obs> obsForCheckInEncounter,
      List<Order> ordersForCheckInEncounter,
      boolean newVisit) {
    if (checkInClerk == null) {
      checkInClerk = getProvider(Context.getAuthenticatedUser());
    }

    Visit activeVisit = getActiveVisitHelper(patient, where);

    if (activeVisit != null && newVisit) {
      closeAndSaveVisit(activeVisit);
      activeVisit = null;
    }

    if (activeVisit == null) {
      activeVisit = ensureActiveVisit(patient, where);
    }

    Encounter lastEncounter = getLastEncounter(patient);
    if (lastEncounter != null
        && activeVisit.equals(lastEncounter.getVisit())
        && emrApiProperties.getCheckInEncounterType().equals(lastEncounter.getEncounterType())
        && where.equals(lastEncounter.getLocation())) {
      log.warn(
          "Patient id:{} tried to check-in twice in a row at id:{} during the same visit",
          patient.getId(),
          where.getId());
      return lastEncounter;
    }

    Encounter encounter =
        buildEncounter(
            emrApiProperties.getCheckInEncounterType(),
            patient,
            where,
            null,
            new Date(),
            obsForCheckInEncounter,
            ordersForCheckInEncounter);
    encounter.addProvider(emrApiProperties.getCheckInClerkEncounterRole(), checkInClerk);
    activeVisit.addEncounter(encounter);
    encounterService.saveEncounter(encounter);
    return encounter;
  }
  /** @deprecated see reportingcompatibility module */
  @Deprecated
  public void updateReportObject(AbstractReportObject ro) throws DAOException {
    if (ro.getReportObjectId() == null) createReportObject(ro);
    else {
      sessionFactory.getCurrentSession().clear();
      ReportObjectWrapper wrappedReportObject = new ReportObjectWrapper(ro);
      User user = Context.getAuthenticatedUser();
      Date now = new Date();
      wrappedReportObject.setChangedBy(user);
      wrappedReportObject.setDateChanged(now);

      sessionFactory.getCurrentSession().saveOrUpdate(wrappedReportObject);
    }
  }
  /**
   * This method will be used for remote registration. Registered patient information will be placed
   * into an xml file for the FormEntry processor.
   *
   * @param paramPatient
   * @param paramString1
   * @param paramString2
   * @throws APIException
   */
  public void registerPatient(Patient paramPatient, String paramString1, String paramString2)
      throws APIException {
    File localFile1 = OpenmrsUtil.getDirectoryInApplicationDataDirectory("amrsregistration");
    File localFile2 = new File(localFile1, "registrationTemplate.xml");
    try {
      String str1 = OpenmrsUtil.getFileAsString(localFile2);

      Properties localProperties = new Properties();
      localProperties.setProperty("resource.loader", "class");
      localProperties.setProperty(
          "class.resource.loader.description", "VelocityClasspathResourceLoader");
      localProperties.setProperty(
          "class.resource.loader.class",
          "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
      localProperties.setProperty(
          "runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");

      Velocity.init(localProperties);
      VelocityContext localVelocityContext = new VelocityContext();
      localVelocityContext.put("locale", Context.getLocale());
      localVelocityContext.put(
          "patient", Context.getPatientService().getPatient(paramPatient.getPatientId()));
      localVelocityContext.put("user", Context.getAuthenticatedUser());
      localVelocityContext.put("fn", new DataExportFunctions());
      localVelocityContext.put("dateEntered", new Date());
      localVelocityContext.put("sid", paramString1);
      localVelocityContext.put("uid", paramString2);
      StringWriter localStringWriter = new StringWriter();
      Velocity.evaluate(localVelocityContext, localStringWriter, super.getClass().getName(), str1);

      String str2 =
          Context.getAdministrationService().getGlobalProperty("remoteformentry.pending_queue_dir");
      File localFile3 = OpenmrsUtil.getDirectoryInApplicationDataDirectory(str2);
      Date localDate = new Date();
      String str3 = "amrsregistration_" + localDate.toString();
      File localFile4 = new File(localFile3, str3);
      try {
        FileWriter localFileWriter = new FileWriter(localFile4);
        localFileWriter.write(localStringWriter.toString());
        localFileWriter.flush();
        localFileWriter.close();
      } catch (IOException localIOException) {
        log.error("Unable to write amrsregistration output file.", localIOException);
      }
    } catch (Exception localException) {
      log.error("Unable to create amrsregistration output file", localException);
      throw new APIException(localException);
    }
  }
  /**
   * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String,
   *     String, User, BindingResult) test =
   */
  @Test
  @Verifies(
      value = "display error message when the password is empty",
      method = "handleSubmission()")
  public void handleSubmission_shouldDisplayErrorMessageWhenPasswordIsEmpty() throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

    String result =
        controller.handleSubmission(
            new MockHttpSession(), "", "", "", "", "", Context.getAuthenticatedUser(), errors);

    assertTrue(errors.hasErrors());
    assertEquals("error.password.weak", errors.getGlobalError().getCode());
  }
  @Override
  public CashPoint createEntity(boolean valid) {
    CashPoint cashPoint = new CashPoint();

    if (valid) {
      cashPoint.setName("Test Cash Point");
    }

    cashPoint.setDescription("Test description");
    cashPoint.setLocation(Context.getLocationService().getLocation(1));
    cashPoint.setCreator(Context.getAuthenticatedUser());
    cashPoint.setDateCreated(new Date());

    return cashPoint;
  }
  /**
   * Searches for Person records that have a name similar to the given name, a birthdate that is
   * null or within a few years of the given birthdate, and a gender that matches. Note: this method
   * contains a non-backwards-compatible change between 1.5 and 1.6, since DWR has trouble with
   * method overloading. The String personType parameter was removed, since User no longer extends
   * Person
   *
   * @param name
   * @param birthdate
   * @param age
   * @param gender
   * @return list of people
   */
  public List<?> getSimilarPeople(String name, String birthdate, String age, String gender) {
    Vector<Object> personList;

    Integer userId = Context.getAuthenticatedUser().getUserId();
    log.info(userId + "|" + name + "|" + birthdate + "|" + age + "|" + gender);

    PersonService ps = Context.getPersonService();

    Integer d = null;
    birthdate = birthdate.trim();
    age = age.trim();
    if (birthdate.length() > 0) {
      // extract the year from the given birthdate string
      DateFormat format = Context.getDateFormat();
      Date dateObject = null;
      try {
        dateObject = format.parse(birthdate);
      } catch (Exception e) {
        log.error("Error during parse birthdate", e);
      }

      if (dateObject != null) {
        Calendar c = Calendar.getInstance();
        c.setTime(dateObject);
        d = c.get(Calendar.YEAR);
      }
    } else if (age.length() > 0) {
      // calculate their birth year from the given age string
      Calendar c = Calendar.getInstance();
      c.setTime(new Date());
      d = c.get(Calendar.YEAR);
      d = d - Integer.parseInt(age);
    }

    if (gender.length() < 1) {
      gender = null;
    }

    Set<Person> persons = ps.getSimilarPeople(name, d, gender);

    personList = new Vector<Object>(persons.size());
    for (Person p : persons) {
      personList.add(PersonListItem.createBestMatch(p));
    }

    return personList;
  }
  public static JSONArray getAllSearchHistoriesToSendToTheUI() {
    JSONArray histories = new JSONArray();
    List<ChartSearchHistory> allHistory = chartSearchService.getAllSearchHistory();

    for (ChartSearchHistory history : allHistory) {
      JSONObject json = null;
      if (Context.getAuthenticatedUser().getUserId().equals(history.getHistoryOwner().getUserId())
          && history.getPatient().getPatientId().equals(SearchAPI.getInstance().getPatientId())) {
        json = generateHistoryJSON(history);
      }
      if (json != null) {
        histories.add(json);
      }
    }

    return histories;
  }
  /**
   * Sets a attribute value of this person. If the value is blank then any existing attribute will
   * be voided.
   *
   * @param attrTypeUuid the attribute type UUID
   * @param value the value
   */
  protected void setAsAttribute(String attrTypeUuid, String value) {
    PersonAttribute attr = findFirstAttribute(attrTypeUuid);

    if (StringUtils.isNotBlank(value)) {
      if (attr == null) {
        attr = new PersonAttribute();
        attr.setAttributeType(MetadataUtils.existing(PersonAttributeType.class, attrTypeUuid));
        attr.setValue(value);
        target.addAttribute(attr);
      } else {
        attr.setValue(value);
      }
    } else if (attr != null) {
      attr.setVoided(true);
      attr.setDateVoided(new Date());
      attr.setVoidedBy(Context.getAuthenticatedUser());
    }
  }
  /**
   * @see org.openmrs.api.EncounterService#canEditEncounter(org.openmrs.Encounter, org.openmrs.User)
   */
  @Override
  public boolean canEditEncounter(Encounter encounter, User user) {
    // if passed in encounter is null raise an exception
    if (encounter == null) {
      throw new IllegalArgumentException("The encounter argument can not be null");
    }
    // since we restrict by encounter type, if it does not exist, then anyone is allowed to edit the
    // encounter
    if (encounter.getEncounterType() == null) {
      return Boolean.TRUE;
    }
    // if user is not specified, then use authenticated user from context by default
    if (user == null) {
      user = Context.getAuthenticatedUser();
    }

    return userHasEncounterPrivilege(encounter.getEncounterType().getEditPrivilege(), user);
  }
  public static JSONArray getAllSearchBookmarksToReturnTomanagerUI() {
    JSONArray bookmarks = new JSONArray();
    List<ChartSearchBookmark> allBookmarks = chartSearchService.getAllSearchBookmarks();

    for (ChartSearchBookmark curBookmark : allBookmarks) {
      JSONObject json = null;

      if (Context.getAuthenticatedUser()
          .getUserId()
          .equals(curBookmark.getBookmarkOwner().getUserId())) {
        json = generateBookmarksJSON(curBookmark);
      }

      if (json != null) {
        bookmarks.add(json);
      }
    }
    return bookmarks;
  }
  /**
   * @see org.openmrs.api.EncounterService#voidEncounter(org.openmrs.Encounter, java.lang.String)
   */
  public Encounter voidEncounter(Encounter encounter, String reason) {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          String.format(
              "Privilege %s required to void encounters of this type",
              encounter.getEncounterType().getEditPrivilege()));
    }

    if (reason == null) {
      throw new IllegalArgumentException("The argument 'reason' is required and so cannot be null");
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(false)) {
      if (!o.isVoided()) {
        os.voidObs(o, reason);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (!o.isVoided()) {
        orderService.voidOrder(o, reason);
      }
    }

    encounter.setVoided(true);
    encounter.setVoidedBy(Context.getAuthenticatedUser());
    // we expect the dateVoided to be already set by AOP logic at this point unless this method was
    // called within the API,
    // this ensures that original ParentVoidedDate and the dateVoided of associated objects will
    // always match for the
    // unvoid handler to work
    if (encounter.getDateVoided() == null) {
      encounter.setDateVoided(new Date());
    }
    encounter.setVoidReason(reason);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }