/** @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */
 public int compare(FormField formField, FormField other) {
   int temp =
       OpenmrsUtil.compareWithNullAsGreatest(formField.getPageNumber(), other.getPageNumber());
   if (temp == 0) {
     temp =
         OpenmrsUtil.compareWithNullAsGreatest(
             formField.getFieldNumber(), other.getFieldNumber());
   }
   if (temp == 0) {
     temp =
         OpenmrsUtil.compareWithNullAsGreatest(formField.getFieldPart(), other.getFieldPart());
   }
   if (temp == 0
       && formField.getPageNumber() == null
       && formField.getFieldNumber() == null
       && formField.getFieldPart() == null) {
     temp =
         OpenmrsUtil.compareWithNullAsGreatest(formField.getSortWeight(), other.getSortWeight());
   }
   if (temp == 0) {
     // to prevent ties
     temp =
         OpenmrsUtil.compareWithNullAsGreatest(
             formField.getFormFieldId(), other.getFormFieldId());
   }
   return temp;
 }
  public Visit mergeVisits(Visit preferred, Visit nonPreferred) {
    // extend date range of winning
    if (OpenmrsUtil.compareWithNullAsEarliest(
            nonPreferred.getStartDatetime(), preferred.getStartDatetime())
        < 0) {
      preferred.setStartDatetime(nonPreferred.getStartDatetime());
    }
    if (preferred.getStopDatetime() != null
        && OpenmrsUtil.compareWithNullAsLatest(
                preferred.getStopDatetime(), nonPreferred.getStopDatetime())
            < 0) {
      preferred.setStopDatetime(nonPreferred.getStopDatetime());
    }

    // move encounters from losing into winning
    if (nonPreferred.getEncounters() != null) {
      for (Encounter e : nonPreferred.getEncounters()) {
        e.setPatient(preferred.getPatient());
        preferred.addEncounter(e);
        encounterService.saveEncounter(e);
      }
    }
    nonPreferred.setEncounters(
        null); // we need to manually the encounters from the non-preferred visit before voiding or
               // all the encounters we just moved will also get voided!

    visitService.voidVisit(
        nonPreferred, "EMR - Merge Patients: merged into visit " + preferred.getVisitId());
    visitService.saveVisit(preferred);
    return preferred;
  }
Example #3
0
  /**
   * Add the <code>inputStream</code> as a file in the modules repository
   *
   * @param inputStream <code>InputStream</code> to load
   * @return filename String of the file's name of the stream
   */
  public static File insertModuleFile(InputStream inputStream, String filename) {
    File folder = getModuleRepository();

    // check if module filename is already loaded
    if (OpenmrsUtil.folderContains(folder, filename))
      throw new ModuleException(filename + " is already associated with a loaded module.");

    File file = new File(folder.getAbsolutePath(), filename);

    FileOutputStream outputStream = null;
    try {
      outputStream = new FileOutputStream(file);
      OpenmrsUtil.copyFile(inputStream, outputStream);
    } catch (FileNotFoundException e) {
      throw new ModuleException("Can't create module file for " + filename, e);
    } catch (IOException e) {
      throw new ModuleException("Can't create module file for " + filename, e);
    } finally {
      try {
        inputStream.close();
      } catch (Exception e) {
        /* pass */
      }
      try {
        outputStream.close();
      } catch (Exception e) {
        /* pass */
      }
    }

    return file;
  }
 /**
  * @param visit
  * @param location
  * @param when
  * @return true if when falls in the visits timespan AND location is within visit.location
  */
 @Override
 public boolean isSuitableVisit(Visit visit, Location location, Date when) {
   if (OpenmrsUtil.compare(when, visit.getStartDatetime()) < 0) {
     return false;
   }
   if (OpenmrsUtil.compareWithNullAsLatest(when, visit.getStopDatetime()) > 0) {
     return false;
   }
   return isSameOrAncestor(visit.getLocation(), location);
 }
 @Override
 public boolean equals(Object o) {
   if (o == null || !(o instanceof Diagnosis)) {
     return false;
   }
   Diagnosis other = (Diagnosis) o;
   return OpenmrsUtil.nullSafeEquals(diagnosis, other.getDiagnosis())
       && OpenmrsUtil.nullSafeEquals(order, other.getOrder())
       && OpenmrsUtil.nullSafeEquals(certainty, other.getCertainty());
 }
  public QueueItem saveQueueItem(QueueItem queueItem) {
    log.debug("saveQueueItem(). Entering");
    boolean isNew = false;
    Date newDate = queueItem.getEncounter().getEncounterDatetime();
    log.debug("Encounter date: " + newDate);
    Date originalDate = null;

    if (queueItem.getQueueItemId() == null) {
      isNew = true;
      log.debug("Got a  new queue item");
    }

    // Not new we update some of the Encounter info
    if (!isNew) {
      log.info("Updating previously queued encounter!");
      Encounter encounter = queueItem.getEncounter();
      Patient p = encounter.getPatient();
      originalDate = encounter.getEncounterDatetime();
      if (OpenmrsUtil.compare(originalDate, newDate) != 0) {

        // if the obs datetime is the same as the
        // original encounter datetime, fix it
        if (OpenmrsUtil.compare(queueItem.getDateCreated(), originalDate) == 0) {
          encounter.setEncounterDatetime(newDate);
        }
      }

      // if the Person in the encounter doesn't match the Patient in the ,
      // fix it
      if (!encounter.getPatient().getPersonId().equals(p.getPatientId())) {
        encounter.setPatient(p);
      }

      for (Obs obs : encounter.getAllObs(true)) {
        // if the date was changed
        if (OpenmrsUtil.compare(originalDate, newDate) != 0) {

          // if the obs datetime is the same as the
          // original encounter datetime, fix it
          if (OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0) {
            obs.setObsDatetime(newDate);
          }
        }

        // if the Person in the obs doesn't match the Patient in the
        // encounter, fix it
        if (!obs.getPerson().getPersonId().equals(p.getPatientId())) {
          obs.setPerson(p);
        }
      }
    }
    log.debug("Saving queu item.");
    dao.saveQueueItem(queueItem);
    return queueItem;
  }
  @RequestMapping(value = SETTINGS_PATH, method = RequestMethod.POST)
  public void updateSettings(
      @ModelAttribute(SETTINGS_FORM) SettingsForm settingsForm,
      Errors errors,
      HttpServletRequest request,
      HttpSession session) {

    List<GlobalProperty> toSave = new ArrayList<GlobalProperty>();
    try {
      for (int i = 0; i < settingsForm.getSettings().size(); ++i) {
        SettingsProperty property = settingsForm.getSettings().get(i);
        if (StringUtils.isNotEmpty(property.getGlobalProperty().getDatatypeClassname())) {
          // we need to handle the submitted value with the appropriate widget
          CustomDatatype dt = CustomDatatypeUtil.getDatatypeOrDefault(property.getGlobalProperty());
          CustomDatatypeHandler handler =
              CustomDatatypeUtil.getHandler(property.getGlobalProperty());
          if (handler != null) {
            try {
              Object value =
                  WebAttributeUtil.getValue(
                      request, dt, handler, "settings[" + i + "].globalProperty.propertyValue");
              property.getGlobalProperty().setValue(value);
            } catch (Exception ex) {
              String originalValue = request.getParameter("originalValue[" + i + "]");
              property.getGlobalProperty().setPropertyValue(originalValue);
              errors.rejectValue(
                  "settings[" + i + "].globalProperty.propertyValue", "general.invalid");
            }
          }
        }
        toSave.add(property.getGlobalProperty());
      }
    } catch (Exception e) {
      log.error("Error saving global property", e);
      errors.reject("GlobalProperty.not.saved");
      session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
    }

    if (errors.hasErrors()) {
      session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "GlobalProperty.not.saved");

    } else {
      for (GlobalProperty gp : toSave) {
        getService().saveGlobalProperty(gp);
      }
      session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "GlobalProperty.saved");

      // TODO: move this to a GlobalPropertyListener
      // refresh log level from global property(ies)
      OpenmrsUtil.applyLogLevels();

      OpenmrsUtil.setupLogAppenders();
    }
  }
  /**
   * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String obsId = request.getParameter("obsId");
    String view = request.getParameter("view");
    String viewType = request.getParameter("viewType");

    HttpSession session = request.getSession();

    if (obsId == null || obsId.length() == 0) {
      session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null");
      return;
    }
    if (!Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_OBS)) {
      session.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + OpenmrsConstants.PRIV_VIEW_OBS);
      session.setAttribute(
          WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR,
          request.getRequestURI() + "?" + request.getQueryString());
      response.sendRedirect(request.getContextPath() + "/login.htm");
      return;
    }

    Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view);
    ComplexData cd = complexObs.getComplexData();
    Object data = cd.getData();

    if ("download".equals(viewType)) {
      response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle());
      response.setHeader("Pragma", "no-cache");
    }

    if (data instanceof byte[]) {
      ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data);
      OpenmrsUtil.copyFile(stream, response.getOutputStream());
    } else if (RenderedImage.class.isAssignableFrom(data.getClass())) {
      RenderedImage img = (RenderedImage) data;
      String[] parts = cd.getTitle().split(".");
      String extension = "jpg"; // default extension
      if (parts.length > 0) {
        extension = parts[parts.length - 1];
      }

      ImageIO.write(img, extension, response.getOutputStream());
    } else if (InputStream.class.isAssignableFrom(data.getClass())) {
      InputStream stream = (InputStream) data;
      OpenmrsUtil.copyFile(stream, response.getOutputStream());
      stream.close();
    } else {
      throw new ServletException(
          "Couldn't serialize complex obs data for obsId=" + obsId + " of type " + data.getClass());
    }
  }
 private static boolean regimenComponentIsTheSameAsDrugOrderExcludingDates(
     DrugOrder rc, DrugOrder doTmp) {
   if (rc.getDrug() != null
       && doTmp.getDrug() != null
       && rc.getDrug().getDrugId().intValue() != doTmp.getDrug().getDrugId().intValue())
     return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getConcept(), doTmp.getConcept())) return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getDose(), doTmp.getDose())) return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getFrequency(), doTmp.getFrequency())) return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getUnits(), doTmp.getUnits())) return false;
   return true;
 }
 /**
  * @see
  *     org.openmrs.messagesource.MutableMessageSource#addPresentation(org.openmrs.messagesource.PresentationMessage)
  */
 public void addPresentation(PresentationMessage message) {
   File propertyFile = findPropertiesFileFor(message.getCode());
   if (propertyFile != null) {
     Properties props = new Properties();
     try {
       OpenmrsUtil.loadProperties(props, propertyFile);
       props.setProperty(message.getCode(), message.getMessage());
       OpenmrsUtil.storeProperties(props, propertyFile, "OpenMRS Application Messages");
     } catch (Exception e) {
       log.error("Error generated", e);
     }
   }
 }
 /**
  * @see
  *     org.openmrs.messagesource.MutableMessageSource#removePresentation(org.openmrs.messagesource.PresentationMessage)
  */
 public void removePresentation(PresentationMessage message) {
   File propertyFile = findPropertiesFileFor(message.getCode());
   if (propertyFile != null) {
     Properties props = new Properties();
     try {
       OpenmrsUtil.loadProperties(props, propertyFile);
       props.remove(message.getCode());
       OpenmrsUtil.storeProperties(props, propertyFile, PROPERTIES_FILE_COMMENT);
     } catch (Exception e) {
       log.error("Error generated", e);
     }
   }
 }
 @Override
 public boolean visitsOverlap(Visit v1, Visit v2) {
   Location where1 = v1.getLocation();
   Location where2 = v2.getLocation();
   if ((where1 == null && where2 == null)
       || isSameOrAncestor(where1, where2)
       || isSameOrAncestor(where2, where1)) {
     // "same" location, so check if date ranges overlap (assuming startDatetime is never null)
     return (OpenmrsUtil.compareWithNullAsLatest(v1.getStartDatetime(), v2.getStopDatetime()) <= 0)
         && (OpenmrsUtil.compareWithNullAsLatest(v2.getStartDatetime(), v1.getStopDatetime())
             <= 0);
   }
   return false;
 }
Example #13
0
  /**
   * Mimics org.openmrs.web.Listener.getRuntimeProperties()
   *
   * @param webappName name to use when looking up the runtime properties env var or filename
   * @return Properties runtime
   */
  public static Properties getRuntimeProperties(String webappName) {

    Properties props = new Properties();

    try {
      FileInputStream propertyStream = null;

      // Look for environment variable
      // {WEBAPP.NAME}_RUNTIME_PROPERTIES_FILE
      String env = webappName.toUpperCase() + "_RUNTIME_PROPERTIES_FILE";

      String filepath = System.getenv(env);

      if (filepath != null) {
        try {
          propertyStream = new FileInputStream(filepath);
        } catch (IOException e) {
        }
      }

      // env is the name of the file to look for in the directories
      String filename = webappName + "-runtime.properties";

      if (propertyStream == null) {
        filepath = OpenmrsUtil.getApplicationDataDirectory() + filename;
        try {
          propertyStream = new FileInputStream(filepath);
        } catch (IOException e) {
        }
      }

      // look in current directory last
      if (propertyStream == null) {
        filepath = filename;
        try {
          propertyStream = new FileInputStream(filepath);
        } catch (IOException e) {
        }
      }

      if (propertyStream == null)
        throw new IOException("Could not open '" + filename + "' in user or local directory.");
      OpenmrsUtil.loadProperties(props, propertyStream);
      propertyStream.close();

    } catch (IOException e) {
    }

    return props;
  }
  /**
   * 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);
    }
  }
  /**
   * Checks that a given concept map type object is valid.
   *
   * @see org.springframework.validation.Validator#validate(java.lang.Object,
   *     org.springframework.validation.Errors)
   * @should fail if the concept map type object is null
   * @should fail if the name is null
   * @should fail if the name is an empty string
   * @should fail if the name is a white space character
   * @should fail if the concept map type name is a duplicate
   * @should pass if the name is unique amongst all concept map type names
   * @should pass validation if field lengths are correct
   * @should fail validation if field lengths are not correct
   */
  public void validate(Object obj, Errors errors) {

    if (obj == null || !(obj instanceof ConceptMapType)) {
      throw new IllegalArgumentException(
          "The parameter obj should not be null and must be of type" + ConceptMapType.class);
    }

    ConceptMapType conceptMapType = (ConceptMapType) obj;
    String name = conceptMapType.getName();
    if (!StringUtils.hasText(name)) {
      errors.rejectValue(
          "name",
          "ConceptMapType.error.nameRequired",
          "The name property is required for a concept map type");
      return;
    }

    name = name.trim();
    ConceptMapType duplicate = Context.getConceptService().getConceptMapTypeByName(name);
    if (duplicate != null
        && !OpenmrsUtil.nullSafeEquals(duplicate.getUuid(), conceptMapType.getUuid())) {
      errors.rejectValue(
          "name", "ConceptMapType.duplicate.name", "Duplicate concept map type name: " + name);
    }
    ValidateUtil.validateFieldLengths(
        errors, obj.getClass(), "name", "description", "retireReason");
  }
Example #16
0
  public void addAttribute(HrStaffAttribute newAttribute) {
    newAttribute.setHrStaff(this);
    boolean newIsNull = !StringUtils.hasText(newAttribute.getValue());

    for (HrStaffAttribute currentAttribute : getActiveAttributes()) {
      if (currentAttribute.equals(newAttribute))
        return; // if we have the same HrStaffAttributeId, don't add the new attribute
      else if (currentAttribute
          .getHrStaffAttributeType()
          .equals(newAttribute.getHrStaffAttributeType())) {
        if (currentAttribute.getValue() != null
            && currentAttribute.getValue().equals(newAttribute.getValue()))
          // this staff already has this attribute
          return;

        // if the to-be-added attribute isn't already voided itself
        // and if we have the same type, different value
        if (newAttribute.isVoided() == false || newIsNull) {
          if (currentAttribute.getCreator() != null)
            currentAttribute.voidAttribute("New value: " + newAttribute.getValue());
          else
            // remove the attribute if it was just temporary (didn't have a creator
            // attached to it yet)
            removeAttribute(currentAttribute);
        }
      }
    }
    if (!OpenmrsUtil.collectionContains(hrStaffAttributes, newAttribute) && !newIsNull)
      hrStaffAttributes.add(newAttribute);
  }
Example #17
0
  /**
   * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
   *
   * @param url
   * @return String contents of the URL
   * @should return an update rdf page for old https dev urls
   * @should return an update rdf page for old https module urls
   * @should return an update rdf page for module urls
   */
  public static String getURL(URL url) {
    InputStream in = null;
    OutputStream out = null;
    String output = "";
    try {
      in = getURLStream(url);
      if (in == null) // skip this module if updateURL is not defined
      return "";

      out = new ByteArrayOutputStream();
      OpenmrsUtil.copyFile(in, out);
      output = out.toString();
    } catch (IOException io) {
      log.warn("io while reading: " + url, io);
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        /* pass */
      }
      try {
        out.close();
      } catch (Exception e) {
        /* pass */
      }
    }

    return output;
  }
  @SuppressWarnings("deprecation")
  public String getTestDatasetFilename(String testDatasetName) throws Exception {

    InputStream propertiesFileStream = null;

    // try to load the file if its a straight up path to the file or
    // if its a classpath path to the file
    if (new File(TEST_DATASETS_PROPERTIES_FILE).exists()) {
      propertiesFileStream = new FileInputStream(TEST_DATASETS_PROPERTIES_FILE);
    } else {
      propertiesFileStream =
          getClass().getClassLoader().getResourceAsStream(TEST_DATASETS_PROPERTIES_FILE);
      if (propertiesFileStream == null)
        throw new FileNotFoundException(
            "Unable to find '" + TEST_DATASETS_PROPERTIES_FILE + "' in the classpath");
    }

    Properties props = new Properties();

    OpenmrsUtil.loadProperties(props, propertiesFileStream);

    if (props.getProperty(testDatasetName) == null) {
      throw new Exception(
          "Test dataset named " + testDatasetName + " not found in properties file");
    }

    return props.getProperty(testDatasetName);
  }
  public PatientDataResult evaluate(RowPerPatientData patientData, EvaluationContext context) {

    DateResult par = new DateResult(patientData, context);
    DateOfFirstDrugOrderStartedRestrictedByConceptSet pd =
        (DateOfFirstDrugOrderStartedRestrictedByConceptSet) patientData;

    par.setFormat(pd.getDateFormat());

    List<DrugOrder> orders = Context.getOrderService().getDrugOrdersByPatient(pd.getPatient());

    if (orders != null) {
      if (pd.getDrugConceptSetConcept() != null) {
        List<Concept> drugConcepts =
            Context.getConceptService().getConceptsByConceptSet(pd.getDrugConceptSetConcept());
        if (drugConcepts != null) {
          DrugOrder startDrugOrder = null;
          for (DrugOrder order : orders) {
            Concept drug = null;
            try {
              drug = order.getDrug().getConcept();
            } catch (Exception e) {
              log.error("Unable to retrieve a drug from the drug order: " + e.getMessage());
            }
            if (drug != null) {
              if (drugConcepts.contains(drug)) {
                if (order.getStartDate() != null
                    && (pd.getStartDate() == null
                        || OpenmrsUtil.compare(order.getStartDate(), pd.getStartDate()) >= 0)
                    && (pd.getEndDate() == null
                        || OpenmrsUtil.compare(order.getStartDate(), pd.getEndDate()) <= 0)) {
                  if (startDrugOrder == null
                      || order.getStartDate().before(startDrugOrder.getStartDate())) {
                    startDrugOrder = order;
                  }
                }
              }
            }
          }
          if (startDrugOrder != null) {
            par.setValue(startDrugOrder.getStartDate());
          }
        }
      }
    }

    return par;
  }
 @PropertyGetter("concept")
 public Object getConcept(PersonAttributeType delegate) {
   if (OpenmrsUtil.nullSafeEquals(delegate.getFormat(), Concept.class.getCanonicalName())) {
     Concept concept = Context.getConceptService().getConcept(delegate.getForeignKey());
     return ConversionUtil.convertToRepresentation(concept, Representation.FULL);
   }
   return null;
 }
 /**
  * Add a period cohort indicator to the report definition with dimension categories.
  *
  * @param CohortIndicator
  */
 public void addIndicator(
     String uniqueName,
     String displayName,
     CohortIndicator indicator,
     String dimensionCategories) {
   addIndicator(
       uniqueName, displayName, indicator, OpenmrsUtil.parseParameterList(dimensionCategories));
 }
 public synchronized void addSearchItem(PatientSearch ps) {
   checkArrayLengths();
   searchHistory.add(ps);
   cachedFilters.add(OpenmrsUtil.toPatientFilter(ps, this));
   // the potentially-expensive query should be done lazily
   cachedResults.add(null);
   cachedResultDates.add(null);
 }
  // public SessionFactory newSessionFactory(Configuration config) throws HibernateException {
  public Configuration newConfiguration() throws HibernateException {
    Configuration config = super.newConfiguration();

    log.debug("Configuring hibernate sessionFactory properties");

    Properties moduleProperties = Context.getConfigProperties();

    // override or initialize config properties with module-provided ones
    for (Object key : moduleProperties.keySet()) {
      String prop = (String) key;
      String value = (String) moduleProperties.get(key);
      log.trace("Setting module property: " + prop + ":" + value);
      config.setProperty(prop, value);
      if (!prop.startsWith("hibernate")) config.setProperty("hibernate." + prop, value);
    }

    Properties properties = Context.getRuntimeProperties();

    // loop over runtime properties and override each in the configuration
    for (Object key : properties.keySet()) {
      String prop = (String) key;
      String value = (String) properties.get(key);
      log.trace("Setting property: " + prop + ":" + value);
      config.setProperty(prop, value);
      if (!prop.startsWith("hibernate")) config.setProperty("hibernate." + prop, value);
    }

    // load in the default hibernate properties
    try {
      InputStream propertyStream =
          ConfigHelper.getResourceAsStream("/hibernate.default.properties");
      Properties props = new Properties();
      OpenmrsUtil.loadProperties(props, propertyStream);
      propertyStream.close();

      // Only load in the default properties if they don't exist
      config.mergeProperties(props);
    } catch (IOException e) {
      log.fatal("Unable to load default hibernate properties", e);
    }

    log.debug(
        "Setting global Hibernate Session Interceptor for SessionFactory, Interceptor: "
            + chainingInterceptor);

    // make sure all autowired interceptors are put onto our chaining interceptor
    // sort on the keys so that the devs/modules have some sort of control over the order of the
    // interceptors
    List<String> keys = new ArrayList<String>(interceptors.keySet());
    Collections.sort(keys);
    for (String key : keys) {
      chainingInterceptor.addInterceptor(interceptors.get(key));
    }

    config.setInterceptor(chainingInterceptor);

    return config;
  }
    public boolean matches(Obs obs) {

      if (!obs.getConcept().getConceptId().equals(conceptId)) {
        return false;
      }

      return OpenmrsUtil.nullSafeEquals(
          TestUtil.valueAsStringHelper(value), obs.getValueAsString(Context.getLocale()));
    }
Example #25
0
  /** @see java.lang.Comparable#compareTo(java.lang.Object) */
  public int compareTo(PersonAddress other) {
    int retValue = 0;
    if (other != null) {
      retValue = isVoided().compareTo(other.isVoided());
      if (retValue == 0) retValue = other.isPreferred().compareTo(isPreferred());
      if (retValue == 0 && getDateCreated() != null)
        retValue = OpenmrsUtil.compareWithNullAsLatest(getDateCreated(), other.getDateCreated());
      if (retValue == 0)
        retValue =
            OpenmrsUtil.compareWithNullAsGreatest(getPersonAddressId(), other.getPersonAddressId());

      // if we've gotten this far, just check all address values. If they are
      // equal, leave the objects at 0. If not, arbitrarily pick retValue=1
      // and return that (they are not equal).
      if (retValue == 0 && !equalsContent(other)) retValue = 1;
    }
    return retValue;
  }
Example #26
0
  /**
   * The web.xml file sets this {@link StartupFilter} to be the first filter for all requests.
   *
   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
   *     javax.servlet.FilterChain)
   */
  public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (skipFilter((HttpServletRequest) request)) {
      chain.doFilter(request, response);
    } else {

      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;

      String servletPath = httpRequest.getServletPath();
      // for all /images and /initfilter/scripts files, write the path
      // (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file
      // doesn't
      //  get instantiated early, before the locale messages are all set up)
      if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
        servletPath =
            servletPath.replaceFirst(
                "/initfilter", "/WEB-INF/view"); // strip out the /initfilter part
        // writes the actual image file path to the response
        File file = new File(filterConfig.getServletContext().getRealPath(servletPath));
        if (httpRequest.getPathInfo() != null) file = new File(file, httpRequest.getPathInfo());

        try {
          InputStream imageFileInputStream = new FileInputStream(file);
          OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
          imageFileInputStream.close();
        } catch (FileNotFoundException e) {
          log.error("Unable to find file: " + file.getAbsolutePath());
        }
      } else if (servletPath.startsWith("/scripts")) {
        log.error(
            "Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup.  Use '/initfilter"
                + servletPath
                + "' instead.");
      }
      // for anything but /initialsetup
      else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) {
        // send the user to the setup page
        httpResponse.sendRedirect(
            "/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
      } else {

        if (httpRequest.getMethod().equals("GET")) {
          doGet(httpRequest, httpResponse);
        } else if (httpRequest.getMethod().equals("POST")) {
          // only clear errors before POSTS so that redirects can show errors too.
          errors.clear();
          doPost(httpRequest, httpResponse);
        }
      }
      // Don't continue down the filter chain otherwise Spring complains
      // that it hasn't been set up yet.
      // The jsp and servlet filter are also on this chain, so writing to
      // the response directly here is the only option
    }
  }
 /**
  * Extracts patients from a calculation result map with date results in the given range
  *
  * @param results the calculation result map
  * @param minDateInclusive the minimum date (inclusive)
  * @param maxDateInclusive the maximum date (inclusive)
  * @return the extracted patient ids
  */
 protected static Set<Integer> datesWithinRange(
     CalculationResultMap results, Date minDateInclusive, Date maxDateInclusive) {
   Set<Integer> ret = new HashSet<Integer>();
   for (Map.Entry<Integer, CalculationResult> e : results.entrySet()) {
     Date result = null;
     try {
       result = e.getValue().asType(Date.class);
     } catch (Exception ex) {
       // pass
     }
     if (result != null) {
       if (OpenmrsUtil.compareWithNullAsEarliest(result, minDateInclusive) >= 0
           && OpenmrsUtil.compareWithNullAsLatest(result, maxDateInclusive) <= 0) {
         ret.add(e.getKey());
       }
     }
   }
   return ret;
 }
Example #28
0
  /**
   * Get the values of the parameters passed in and set them to the local variables on this class.
   *
   * @see liquibase.change.custom.CustomChange#setUp()
   */
  @Override
  public void setUp() throws SetupException {

    tableNamesArray = StringUtils.split(tableNames);
    idExceptionsMap = OpenmrsUtil.parseParameterList(idExceptions);

    genericIdSql = "select tablename_id from tablename where columnName is null";
    genericIdSql = genericIdSql.replace("columnName", columnName);

    genericUpdateSql = "update tablename set columnName = ? where tablename_id = ?";
    genericUpdateSql = genericUpdateSql.replace("columnName", columnName);
  }
 /**
  * Discontinues an order given a date and a reason, and saves it to the database if anything has
  * changed.
  *
  * @param order
  * @param effectiveDate
  * @param reason
  * @should change discontinued metadata if order is set to be discontinued after date
  * @should have no effect if order is discontinued before date
  */
 public static void discontinueOrder(Order order, Date date, Concept reason) {
   if (!order.isDiscontinuedRightNow()) {
     order.setDiscontinued(true);
     order.setDiscontinuedDate(date);
     order.setDiscontinuedReason(reason);
     Context.getOrderService().saveOrder(order);
   } else if (OpenmrsUtil.compareWithNullAsLatest(date, order.getDiscontinuedDate()) < 0) {
     order.setDiscontinued(true); // should already be true
     order.setDiscontinuedDate(date);
     order.setDiscontinuedReason(reason);
     Context.getOrderService().saveOrder(order);
   }
 }
  private boolean shouldBeClosed(Visit visit) {

    if (visit.getStopDatetime() != null) {
      return false; // already closed
    }

    VisitDomainWrapper visitDomainWrapper = domainWrapperFactory.newVisitDomainWrapper(visit);

    if (visitDomainWrapper.isAdmitted() || visitDomainWrapper.isAwaitingAdmission()) {
      return false; // don't close the visit if patient is admitted or waiting admission
    }

    Disposition mostRecentDisposition = visitDomainWrapper.getMostRecentDisposition();
    if (mostRecentDisposition != null
        && mostRecentDisposition.getKeepsVisitOpen() != null
        && mostRecentDisposition.getKeepsVisitOpen()) {
      return false; // don't close the visit if the most recent disposition is one that keeps visit
                    // opens
    }

    Date now = new Date();
    Date mustHaveSomethingAfter = DateUtils.addHours(now, -emrApiProperties.getVisitExpireHours());

    if (OpenmrsUtil.compare(visit.getStartDatetime(), mustHaveSomethingAfter) >= 0) {
      return false;
    }

    if (visit.getEncounters() != null) {
      for (Encounter candidate : visit.getEncounters()) {
        if (OpenmrsUtil.compare(candidate.getEncounterDatetime(), mustHaveSomethingAfter) >= 0) {
          return false;
        }
      }
    }

    return true;
  }