/**
   * @verifies log error if rouding item id is set but item cannot be found (and hence is null)
   * @see CashierOptionsServiceGpImpl#getOptions()
   */
  @Test
  public void getOptions_shouldLogErrorIfRoundingItemIsNullDespiteIdGiven() throws Exception {

    when(adminService.getGlobalProperty(ModuleSettings.RECEIPT_REPORT_ID_PROPERTY))
        .thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_MODE_PROPERTY))
        .thenReturn(CashierOptions.RoundingMode.FLOOR.toString());
    when(adminService.getGlobalProperty(ModuleSettings.ROUND_TO_NEAREST_PROPERTY)).thenReturn("5");
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_ITEM_ID)).thenReturn("273423");
    when(adminService.getGlobalProperty(ModuleSettings.TIMESHEET_REQUIRED_PROPERTY))
        .thenReturn(null);

    Logger logger = Logger.getLogger(CashierOptionsServiceGpImpl.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Layout layout = new SimpleLayout();
    Appender appender = new WriterAppender(layout, out);
    logger.addAppender(appender);

    try {
      optionsService.getOptions();
      String logMsg = out.toString();
      assertNotNull(logMsg);
      assertFalse((logMsg.trim()).equals(""));
    } finally {
      logger.removeAppender(appender);
    }
  }
  public void get(PageModel model) {

    AdministrationService administrationService = Context.getAdministrationService();
    List<GlobalProperty> globalProps = administrationService.getAllGlobalProperties();
    // TODO Remove module global properties
    model.addAttribute("globalProperties", globalProps);
  }
 private static void setStringProperty(String propertyName, String value) {
   if (value != null) {
     administrationService.setGlobalProperty(propertyName, value);
   } else {
     administrationService.setGlobalProperty(propertyName, "");
   }
 }
 /**
  * gets globalProperty value by giving globalProperty Key
  *
  * @param propertyName
  * @return propertyValue
  */
 public int getGlobalProperty(String propertyName) {
   AdministrationService administrationService = Context.getAdministrationService();
   int propertyValue = 0;
   if (propertyName != null && !propertyName.equals(""))
     propertyValue = Integer.parseInt(administrationService.getGlobalProperty(propertyName));
   return propertyValue;
 }
 private static void setBoolProperty(String propertyName, Boolean value) {
   if (Boolean.TRUE.equals(value)) {
     administrationService.setGlobalProperty(propertyName, Boolean.TRUE.toString());
   } else {
     administrationService.setGlobalProperty(propertyName, Boolean.FALSE.toString());
   }
 }
 private static void setIntProperty(String propertyName, Integer value) {
   if (value != null) {
     administrationService.setGlobalProperty(propertyName, value.toString());
   } else {
     administrationService.setGlobalProperty(propertyName, "");
   }
 }
 public static boolean isTimesheetRequired() {
   AdministrationService adminService = Context.getAdministrationService();
   boolean timesheetRequired;
   try {
     timesheetRequired =
         Boolean.parseBoolean(
             adminService.getGlobalProperty(CashierWebConstants.TIMESHEET_REQUIRED_PROPERTY));
   } catch (Exception e2) {
     timesheetRequired = false;
   }
   return timesheetRequired;
 }
  /**
   * @verifies not throw exception if numeric options are null
   * @see CashierOptionsServiceGpImpl#getOptions()
   */
  @Test
  public void getOptions_shouldNotThrowExceptionIfNumericOptionsAreNull() throws Exception {
    when(adminService.getGlobalProperty(ModuleSettings.RECEIPT_REPORT_ID_PROPERTY))
        .thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_MODE_PROPERTY)).thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUND_TO_NEAREST_PROPERTY)).thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_ITEM_ID)).thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.TIMESHEET_REQUIRED_PROPERTY))
        .thenReturn(null);

    CashierOptions options = optionsService.getOptions();

    Assert.assertNotNull(options);
  }
  /**
   * @verifies default to false if timesheet required is not specified
   * @see CashierOptionsServiceGpImpl#getOptions()
   */
  @Test
  public void getOptions_shouldDefaultToFalseIfTimesheetRequiredIsNotSpecified() throws Exception {
    when(adminService.getGlobalProperty(ModuleSettings.RECEIPT_REPORT_ID_PROPERTY))
        .thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_MODE_PROPERTY)).thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUND_TO_NEAREST_PROPERTY)).thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_ITEM_ID)).thenReturn(null);
    when(adminService.getGlobalProperty(ModuleSettings.TIMESHEET_REQUIRED_PROPERTY))
        .thenReturn(null);

    CashierOptions options = optionsService.getOptions();

    Assert.assertNotNull(options);
    Assert.assertEquals(false, options.isTimesheetRequired());
  }
  // TODO: These functions should be moved to a commons-level base class for module settings classes
  private static Boolean getBoolProperty(String propertyName) {
    Boolean result = null;
    String property = administrationService.getGlobalProperty(propertyName);
    if (!StringUtils.isEmpty(property)) {
      result = Boolean.parseBoolean(property);
    }

    return result;
  }
 private static void getIntProperty(
     String propertyName, Integer defaultValue, Action1<Integer> action) {
   String property = administrationService.getGlobalProperty(propertyName);
   if (!StringUtils.isEmpty(property) && NumberUtils.isNumber(property)) {
     action.apply(Integer.parseInt(property));
   } else if (defaultValue != null) {
     action.apply(defaultValue);
   }
 }
  private static Integer getIntProperty(String propertyName) {
    Integer result = null;
    String property = administrationService.getGlobalProperty(propertyName);
    if (!StringUtils.isEmpty(property) && NumberUtils.isNumber(property)) {
      result = Integer.parseInt(property);
    }

    return result;
  }
 private static void getBoolProperty(
     String propertyName, Boolean defaultValue, Action1<Boolean> action) {
   String property = administrationService.getGlobalProperty(propertyName);
   if (!StringUtils.isEmpty(property)) {
     action.apply(Boolean.parseBoolean(property));
   } else if (defaultValue != null) {
     action.apply(defaultValue);
   }
 }
  void submitProposedConcept(final ProposedConceptPackage conceptPackage) {

    checkNotNull(submissionRestTemplate);

    //
    // Could not figure out how to get Spring to send a basic authentication request using the
    // "proper" object approach
    // see: https://github.com/johnsyweb/openmrs-cpm/wiki/Gotchas
    //

    AdministrationService service = Context.getAdministrationService();
    SubmissionDto submission = submissionDtoFactory.create(conceptPackage);

    HttpHeaders headers =
        httpHeaderFactory.create(
            service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
            service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    // headers = createHeaders(service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
    //        service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    final HttpEntity requestEntity = new HttpEntity<SubmissionDto>(submission, headers);

    final String url =
        service.getGlobalProperty(CpmConstants.SETTINGS_URL_PROPERTY)
            + "/ws/cpm/dictionarymanager/proposals";
    ResponseEntity responseEntity =
        submissionRestTemplate.exchange(
            url, HttpMethod.POST, requestEntity, SubmissionResponseDto.class);

    //		final SubmissionResponseDto result =
    // submissionRestTemplate.postForObject("http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals", submission, SubmissionResponseDto.class);
    //
    //        TODO: Find out how to determine success/failure for the submission returned by
    // dictionarymanagercontroller
    if (responseEntity == null || !responseEntity.getStatusCode().equals(HttpStatus.SC_OK)) {
      //            throw new ConceptProposalSubmissionException("Error in submitting proposed
      // concept");
      log.error("REsponseEntity status code is " + responseEntity.getStatusCode());
    }
    conceptPackage.setStatus(PackageStatus.SUBMITTED);
    Context.getService(ProposedConceptService.class).saveProposedConceptPackage(conceptPackage);
  }
  /**
   * @verifies load cashier options from the database
   * @see CashierOptionsServiceGpImpl#getOptions()
   */
  @Test
  public void getOptions_shouldLoadCashierOptionsFromTheDatabase() throws Exception {
    when(adminService.getGlobalProperty(ModuleSettings.RECEIPT_REPORT_ID_PROPERTY)).thenReturn("1");
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_MODE_PROPERTY))
        .thenReturn(CashierOptions.RoundingMode.MID.toString());
    when(adminService.getGlobalProperty(ModuleSettings.ROUND_TO_NEAREST_PROPERTY)).thenReturn("5");
    when(adminService.getGlobalProperty(ModuleSettings.ROUNDING_ITEM_ID)).thenReturn("1");
    when(adminService.getGlobalProperty(ModuleSettings.TIMESHEET_REQUIRED_PROPERTY))
        .thenReturn("true");

    Item item = new Item();
    when(itemService.getById(1)).thenReturn(item);

    CashierOptions options = optionsService.getOptions();

    Assert.assertNotNull(options);
    Assert.assertEquals(1, options.getDefaultReceiptReportId());
    Assert.assertEquals(CashierOptions.RoundingMode.MID, options.getRoundingMode());
    Assert.assertEquals(new BigDecimal(5), options.getRoundToNearest());
    Assert.assertEquals(item.getUuid(), options.getRoundingItemUuid());
    Assert.assertEquals(true, options.isTimesheetRequired());
  }
  /** @see {@link org.openmrs.module.ModuleUtil#getMandatoryModules()} */
  @Test
  @Verifies(value = "should return mandatory module ids", method = "getMandatoryModules()")
  public void getMandatoryModules_shouldReturnMandatoryModuleIds() throws Exception {
    // given
    GlobalProperty gp1 = new GlobalProperty("firstmodule.mandatory", "true");
    GlobalProperty gp2 = new GlobalProperty("secondmodule.mandatory", "false");

    when(administrationService.getGlobalPropertiesBySuffix(".mandatory"))
        .thenReturn(Arrays.asList(gp1, gp2));

    // when
    // then
    assertThat(ModuleUtil.getMandatoryModules(), contains("firstmodule"));
  }
  /**
   * Gets the folder where modules are stored. ModuleExceptions are thrown on errors
   *
   * @return folder containing modules
   * @should use the runtime property as the first choice if specified
   * @should return the correct file if the runtime property is an absolute path
   */
  public static File getModuleRepository() {

    String folderName =
        Context.getRuntimeProperties()
            .getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY);
    if (StringUtils.isBlank(folderName)) {
      AdministrationService as = Context.getAdministrationService();
      folderName =
          as.getGlobalProperty(
              ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
              ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
    }
    // try to load the repository folder straight away.
    File folder = new File(folderName);

    // if the property wasn't a full path already, assume it was intended to be a folder in the
    // application directory
    if (!folder.exists()) {
      folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
    }

    // now create the modules folder if it doesn't exist
    if (!folder.exists()) {
      log.warn(
          "Module repository "
              + folder.getAbsolutePath()
              + " doesn't exist.  Creating directories now.");
      folder.mkdirs();
    }

    if (!folder.isDirectory())
      throw new ModuleException(
          "Module repository is not a directory at: " + folder.getAbsolutePath());

    return folder;
  }
  private void addModelAttributes(
      PageModel model,
      Patient patient,
      NavigableFormStructure formStructure,
      AdministrationService adminService,
      String returnUrl)
      throws Exception {

    model.addAttribute("returnUrl", returnUrl);
    model.put("uiUtils", new RegistrationAppUiUtils());
    model.addAttribute("patient", patient);
    model.addAttribute("addressTemplate", AddressSupport.getInstance().getAddressTemplate().get(0));
    model.addAttribute("formStructure", formStructure);
    model.addAttribute(
        "enableOverrideOfAddressPortlet",
        adminService.getGlobalProperty("addresshierarchy.enableOverrideOfAddressPortlet", "false"));
  }
  /** @see {@link org.openmrs.module.ModuleUtil#checkMandatoryModulesStarted()} */
  @Test(expected = MandatoryModuleException.class)
  @Verifies(
      value = "should throw ModuleException if a mandatory module is not started",
      method = "checkMandatoryModulesStarted()")
  public void
      checkMandatoryModulesStarted_shouldThrowModuleExceptionIfAMandatoryModuleIsNotStarted()
          throws Exception {
    // given
    assertThat(ModuleFactory.getStartedModules(), empty());

    GlobalProperty gp1 = new GlobalProperty("module1.mandatory", "true");
    when(administrationService.getGlobalPropertiesBySuffix(".mandatory"))
        .thenReturn(Arrays.asList(gp1));

    // when
    ModuleUtil.checkMandatoryModulesStarted();
    // then exception
  }
 /**
  * @see
  *     org.openmrs.module.kenyacore.metadata.handler.ObjectDeployHandler#findAlternateMatch(org.openmrs.OpenmrsObject)
  */
 @Override
 public GlobalProperty findAlternateMatch(GlobalProperty incoming) {
   return adminService.getGlobalPropertyByUuid(incoming.getUuid());
 }
  public static CashierSettings loadSettings() {
    final CashierSettings cashierSettings = new CashierSettings();

    getBoolProperty(
        ADJUSTMENT_REASEON_FIELD,
        Boolean.FALSE,
        new Action1<Boolean>() {
          @Override
          public void apply(Boolean parameter) {
            cashierSettings.setAdjustmentReasonField(parameter);
          }
        });

    getBoolProperty(
        ALLOW_BILL_ADJUSTMENT,
        Boolean.FALSE,
        new Action1<Boolean>() {
          @Override
          public void apply(Boolean parameter) {
            cashierSettings.setAllowBillAdjustment(parameter);
          }
        });

    getBoolProperty(
        AUTOFILL_PAYMENT_AMOUNT,
        Boolean.FALSE,
        new Action1<Boolean>() {
          @Override
          public void apply(Boolean parameter) {
            cashierSettings.setAutoFillPaymentAmount(parameter);
          }
        });

    getIntProperty(
        ROUND_TO_NEAREST_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setCashierRoundingToNearest(parameter);
          }
        });

    getIntProperty(
        CASHIER_SHIFT_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setDefaultShiftReportId(parameter);
          }
        });

    getIntProperty(
        RECEIPT_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setDefaultReceiptReportId(parameter);
          }
        });

    String property = administrationService.getGlobalProperty(ROUNDING_MODE_PROPERTY);
    if (!StringUtils.isEmpty(property)) {
      cashierSettings.setCashierRoundingMode(property);
    }

    getBoolProperty(
        TIMESHEET_REQUIRED_PROPERTY,
        new Action1<Boolean>() {
          @Override
          public void apply(Boolean parameter) {
            cashierSettings.setCashierTimesheetRequired(parameter);
          }
        });

    getIntProperty(
        PATIENT_DASHBOARD_2_BILL_COUNT,
        DEFAULT_PATIENT_DASHBOARD_2_BILL_COUNT,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setPatientDashboard2BillCount(parameter);
          }
        });

    getIntProperty(
        DEPARTMENT_COLLECTIONS_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setDepartmentCollectionsReportId(parameter);
          }
        });

    getIntProperty(
        DEPARTMENT_REVENUE_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setDepartmentRevenueReportId(parameter);
          }
        });

    getIntProperty(
        SHIFT_SUMMARY_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setShiftSummaryReportId(parameter);
          }
        });

    getIntProperty(
        DAILY_SHIFT_SUMMARY_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setDailyShiftSummaryReportId(parameter);
          }
        });

    getIntProperty(
        PAYMENTS_BY_PAYMENT_MODE_REPORT_ID_PROPERTY,
        new Action1<Integer>() {
          @Override
          public void apply(Integer parameter) {
            cashierSettings.setPaymentsByPaymentModeReportId(parameter);
          }
        });

    return cashierSettings;
  }
Beispiel #22
0
  /**
   * This method produces a model containing the following mappings:
   *
   * <pre>
   *     (always)
   *          (java.util.Date) now
   *          (String) size
   *          (Locale) locale
   *          (String) portletUUID // unique for each instance of any portlet
   *          (other parameters)
   *     (if there's currently an authenticated user)
   *          (User) authenticatedUser
   *     (if the request has a patientId attribute)
   *          (Integer) patientId
   *          (Patient) patient
   *          (List<Obs>) patientObs
   *          (List<Encounter>) patientEncounters
   *          (List<DrugOrder>) patientDrugOrders
   *          (List<DrugOrder>) currentDrugOrders
   *          (List<DrugOrder>) completedDrugOrders
   *          (Obs) patientWeight // most recent weight obs
   *          (Obs) patientHeight // most recent height obs
   *          (Double) patientBmi // BMI derived from most recent weight and most recent height
   *          (String) patientBmiAsString // BMI rounded to one decimal place, or "?" if unknown
   *          (Integer) personId
   *          (if the patient has any obs for the concept in the global property 'concept.reasonExitedCare')
   *              (Obs) patientReasonForExit
   *     (if the request has a personId or patientId attribute)
   *          (Person) person
   *          (List<Relationship>) personRelationships
   *          (Map<RelationshipType, List<Relationship>>) personRelationshipsByType
   *     (if the request has an encounterId attribute)
   *          (Integer) encounterId
   *          (Encounter) encounter
   *          (Set<Obs>) encounterObs
   *     (if the request has a userId attribute)
   *          (Integer) userId
   *          (User) user
   *     (if the request has a patientIds attribute, which should be a (String) comma-separated list of patientIds)
   *          (PatientSet) patientSet
   *          (String) patientIds
   *     (if the request has a conceptIds attribute, which should be a (String) commas-separated list of conceptIds)
   *          (Map<Integer, Concept>) conceptMap
   *          (Map<String, Concept>) conceptMapByStringIds
   * </pre>
   *
   * @should calculate bmi into patientBmiAsString
   * @should not fail with empty height and weight properties
   */
  @SuppressWarnings("unchecked")
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    AdministrationService as = Context.getAdministrationService();
    ConceptService cs = Context.getConceptService();

    // find the portlet that was identified in the openmrs:portlet taglib
    Object uri = request.getAttribute("javax.servlet.include.servlet_path");
    String portletPath = "";
    Map<String, Object> model = null;
    {
      HttpSession session = request.getSession();
      String uniqueRequestId = (String) request.getAttribute(WebConstants.INIT_REQ_UNIQUE_ID);
      String lastRequestId =
          (String) session.getAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID);
      if (uniqueRequestId.equals(lastRequestId)) {
        model =
            (Map<String, Object>) session.getAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL);

        // remove cached parameters
        List<String> parameterKeys = (List<String>) model.get("parameterKeys");
        for (String key : parameterKeys) {
          model.remove(key);
        }
      }
      if (model == null) {
        log.debug("creating new portlet model");
        model = new HashMap<String, Object>();
        session.setAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID, uniqueRequestId);
        session.setAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL, model);
      }
    }

    if (uri != null) {
      long timeAtStart = System.currentTimeMillis();
      portletPath = uri.toString();

      // Allowable extensions are '' (no extension) and '.portlet'
      if (portletPath.endsWith("portlet")) portletPath = portletPath.replace(".portlet", "");
      else if (portletPath.endsWith("jsp"))
        throw new ServletException(
            "Illegal extension used for portlet: '.jsp'. Allowable extensions are '' (no extension) and '.portlet'");

      log.debug("Loading portlet: " + portletPath);

      String id = (String) request.getAttribute("org.openmrs.portlet.id");
      String size = (String) request.getAttribute("org.openmrs.portlet.size");
      Map<String, Object> params =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameters");
      Map<String, Object> moreParams =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameterMap");

      model.put("now", new Date());
      model.put("id", id);
      model.put("size", size);
      model.put("locale", Context.getLocale());
      model.put("portletUUID", UUID.randomUUID().toString().replace("-", ""));
      List<String> parameterKeys = new ArrayList<String>(params.keySet());
      model.putAll(params);
      if (moreParams != null) {
        model.putAll(moreParams);
        parameterKeys.addAll(moreParams.keySet());
      }
      model.put("parameterKeys", parameterKeys); // so we can clean these up in the next request

      // if there's an authenticated user, put them, and their patient set, in the model
      if (Context.getAuthenticatedUser() != null) {
        model.put("authenticatedUser", Context.getAuthenticatedUser());
      }

      Integer personId = null;

      // if a patient id is available, put patient data documented above in the model
      Object o = request.getAttribute("org.openmrs.portlet.patientId");
      if (o != null) {
        String patientVariation = "";
        Integer patientId = (Integer) o;
        if (!model.containsKey("patient")) {
          // we can't continue if the user can't view patients
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENTS)) {
            Patient p = Context.getPatientService().getPatient(patientId);
            model.put("patient", p);

            // add encounters if this user can view them
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS))
              model.put(
                  "patientEncounters", Context.getEncounterService().getEncountersByPatient(p));

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) {
              List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
              model.put("patientObs", patientObs);
              Obs latestWeight = null;
              Obs latestHeight = null;
              String bmiAsString = "?";
              try {
                String weightString = as.getGlobalProperty("concept.weight");
                ConceptNumeric weightConcept = null;
                if (StringUtils.hasLength(weightString))
                  weightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(weightString)).getConceptId());
                String heightString = as.getGlobalProperty("concept.height");
                ConceptNumeric heightConcept = null;
                if (StringUtils.hasLength(heightString))
                  heightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(heightString)).getConceptId());
                for (Obs obs : patientObs) {
                  if (obs.getConcept().equals(weightConcept)) {
                    if (latestWeight == null
                        || obs.getObsDatetime().compareTo(latestWeight.getObsDatetime()) > 0)
                      latestWeight = obs;
                  } else if (obs.getConcept().equals(heightConcept)) {
                    if (latestHeight == null
                        || obs.getObsDatetime().compareTo(latestHeight.getObsDatetime()) > 0)
                      latestHeight = obs;
                  }
                }
                if (latestWeight != null) model.put("patientWeight", latestWeight);
                if (latestHeight != null) model.put("patientHeight", latestHeight);
                if (latestWeight != null && latestHeight != null) {
                  double weightInKg;
                  double heightInM;
                  if (weightConcept.getUnits().equals("kg"))
                    weightInKg = latestWeight.getValueNumeric();
                  else if (weightConcept.getUnits().equals("lb"))
                    weightInKg = latestWeight.getValueNumeric() * 0.45359237;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of weight concept: " + weightConcept.getUnits());
                  if (heightConcept.getUnits().equals("cm"))
                    heightInM = latestHeight.getValueNumeric() / 100;
                  else if (heightConcept.getUnits().equals("m"))
                    heightInM = latestHeight.getValueNumeric();
                  else if (heightConcept.getUnits().equals("in"))
                    heightInM = latestHeight.getValueNumeric() * 0.0254;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of height concept: " + heightConcept.getUnits());
                  double bmi = weightInKg / (heightInM * heightInM);
                  model.put("patientBmi", bmi);
                  String temp = "" + bmi;
                  bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
                }
              } catch (Exception ex) {
                if (latestWeight != null && latestHeight != null)
                  log.error(
                      "Failed to calculate BMI even though a weight and height were found", ex);
              }
              model.put("patientBmiAsString", bmiAsString);
            } else {
              model.put("patientObs", new HashSet<Obs>());
            }

            // information about whether or not the patient has exited care
            Obs reasonForExitObs = null;
            String reasonForExitConceptString = as.getGlobalProperty("concept.reasonExitedCare");
            if (StringUtils.hasLength(reasonForExitConceptString)) {
              Concept reasonForExitConcept = cs.getConcept(reasonForExitConceptString);
              if (reasonForExitConcept != null) {
                List<Obs> patientExitObs =
                    Context.getObsService()
                        .getObservationsByPersonAndConcept(p, reasonForExitConcept);
                if (patientExitObs != null) {
                  log.debug("Exit obs is size " + patientExitObs.size());
                  if (patientExitObs.size() == 1) {
                    reasonForExitObs = patientExitObs.iterator().next();
                    Concept exitReason = reasonForExitObs.getValueCoded();
                    Date exitDate = reasonForExitObs.getObsDatetime();
                    if (exitReason != null && exitDate != null) {
                      patientVariation = "Exited";
                    }
                  } else {
                    if (patientExitObs.size() == 0) {
                      log.debug("Patient has no reason for exit");
                    } else {
                      log.error("Too many reasons for exit - not putting data into model");
                    }
                  }
                }
              }
            }
            model.put("patientReasonForExit", reasonForExitObs);

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ORDERS)) {
              List<DrugOrder> drugOrderList = Context.getOrderService().getDrugOrdersByPatient(p);
              model.put("patientDrugOrders", drugOrderList);
              List<DrugOrder> currentDrugOrders = new ArrayList<DrugOrder>();
              List<DrugOrder> discontinuedDrugOrders = new ArrayList<DrugOrder>();
              Date rightNow = new Date();
              for (Iterator<DrugOrder> iter = drugOrderList.iterator(); iter.hasNext(); ) {
                DrugOrder next = iter.next();
                if (next.isCurrent() || next.isFuture()) currentDrugOrders.add(next);
                if (next.isDiscontinued(rightNow)) discontinuedDrugOrders.add(next);
              }
              model.put("currentDrugOrders", currentDrugOrders);
              model.put("completedDrugOrders", discontinuedDrugOrders);

              List<RegimenSuggestion> standardRegimens =
                  Context.getOrderService().getStandardRegimens();
              if (standardRegimens != null) model.put("standardRegimens", standardRegimens);
            }

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_PROGRAMS)
                && Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENT_PROGRAMS)) {
              model.put(
                  "patientPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, null, null, null, false));
              model.put(
                  "patientCurrentPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, new Date(), new Date(), null, false));
            }

            model.put("patientId", patientId);
            if (p != null) {
              personId = p.getPatientId();
              model.put("personId", personId);
            }

            model.put("patientVariation", patientVariation);
          }
        }
      }

      // if a person id is available, put person and relationships in the model
      if (personId == null) {
        o = request.getAttribute("org.openmrs.portlet.personId");
        if (o != null) {
          personId = (Integer) o;
          model.put("personId", personId);
        }
      }
      if (personId != null) {
        if (!model.containsKey("person")) {
          Person p = (Person) model.get("patient");
          if (p == null) p = Context.getPersonService().getPerson(personId);
          model.put("person", p);

          if (Context.hasPrivilege(PrivilegeConstants.VIEW_RELATIONSHIPS)) {
            List<Relationship> relationships = new ArrayList<Relationship>();
            relationships.addAll(Context.getPersonService().getRelationshipsByPerson(p));
            Map<RelationshipType, List<Relationship>> relationshipsByType =
                new HashMap<RelationshipType, List<Relationship>>();
            for (Relationship rel : relationships) {
              List<Relationship> list = relationshipsByType.get(rel.getRelationshipType());
              if (list == null) {
                list = new ArrayList<Relationship>();
                relationshipsByType.put(rel.getRelationshipType(), list);
              }
              list.add(rel);
            }

            model.put("personRelationships", relationships);
            model.put("personRelationshipsByType", relationshipsByType);
          }
        }
      }

      // if an encounter id is available, put "encounter" and "encounterObs" in the model
      o = request.getAttribute("org.openmrs.portlet.encounterId");
      if (o != null && !model.containsKey("encounterId")) {
        if (!model.containsKey("encounter")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS)) {
            Encounter e = Context.getEncounterService().getEncounter((Integer) o);
            model.put("encounter", e);
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS))
              model.put("encounterObs", e.getObs());
          }
          model.put("encounterId", (Integer) o);
        }
      }

      // if a user id is available, put "user" in the model
      o = request.getAttribute("org.openmrs.portlet.userId");
      if (o != null) {
        if (!model.containsKey("user")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_USERS)) {
            User u = Context.getUserService().getUser((Integer) o);
            model.put("user", u);
          }
          model.put("userId", (Integer) o);
        }
      }

      // if a list of patient ids is available, make a patientset out of it
      o = request.getAttribute("org.openmrs.portlet.patientIds");
      if (o != null && !"".equals(o) && !model.containsKey("patientIds")) {
        if (!model.containsKey("patientSet")) {
          Cohort ps = new Cohort((String) o);
          model.put("patientSet", ps);
          model.put("patientIds", (String) o);
        }
      }

      o = model.get("conceptIds");
      if (o != null && !"".equals(o)) {
        if (!model.containsKey("conceptMap")) {
          log.debug("Found conceptIds parameter: " + o);
          Map<Integer, Concept> concepts = new HashMap<Integer, Concept>();
          Map<String, Concept> conceptsByStringIds = new HashMap<String, Concept>();
          String conceptIds = (String) o;
          String[] ids = conceptIds.split(",");
          for (String cId : ids) {
            try {
              Integer i = Integer.valueOf(cId);
              Concept c = cs.getConcept(i);
              concepts.put(i, c);
              conceptsByStringIds.put(i.toString(), c);
            } catch (Exception ex) {
            }
          }
          model.put("conceptMap", concepts);
          model.put("conceptMapByStringIds", conceptsByStringIds);
        }
      }

      populateModel(request, model);
      log.debug(portletPath + " took " + (System.currentTimeMillis() - timeAtStart) + " ms");
    }

    return new ModelAndView(portletPath, "model", model);
  }
 /** @see org.openmrs.module.kenyacore.metadata.handler.ObjectDeployHandler#fetch(String) */
 @Override
 public GlobalProperty fetch(String identifier) {
   return adminService.getGlobalPropertyObject(identifier);
 }
 /**
  * @see
  *     org.openmrs.module.kenyacore.metadata.handler.ObjectDeployHandler#save(org.openmrs.OpenmrsObject)
  */
 @Override
 public GlobalProperty save(GlobalProperty obj) {
   return adminService.saveGlobalProperty(obj);
 }
 /**
  * @see
  *     org.openmrs.module.kenyacore.metadata.handler.ObjectDeployHandler#remove(org.openmrs.OpenmrsObject,
  *     String)
  * @param obj the object to remove
  */
 @Override
 public void remove(GlobalProperty obj, String reason) {
   adminService.purgeGlobalProperty(obj);
 }