org.openmrs.Patient - java examples

Here are the examples of the java api org.openmrs.Patient taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

155 Examples 7

19 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.EncounterService#getEncountersNotreplacedignedToAnyVisit(org.openmrs.Patient)
 */
@Override
@Transactional(readOnly = true)
public List<Encounter> getEncountersNotreplacedignedToAnyVisit(Patient patient) throws APIException {
    return Context.getEncounterService().filterEncountersByViewPermissions(dao.getEncountersNotreplacedignedToAnyVisit(patient), null);
}

19 View Complete Implementation : CohortServiceTest.java
Copyright Apache License 2.0
Author : isstac
@Test
public void removePatientFromCohort_shouldSaveCohortAfterRemovingPatient() {
    executeDataSet(COHORT_XML);
    Cohort cohort = service.getCohort(2);
    Integer patientId = cohort.getMemberships().iterator().next().getPatientId();
    Patient patient = Context.getPatientService().getPatient(patientId);
    service.removePatientFromCohort(cohort, patient);
    replacedertFalse(cohort.contains(patientId));
}

19 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.db.PatientDAO#getPatientByUuid(java.lang.String)
 */
@Override
public Patient getPatientByUuid(String uuid) {
    Patient p;
    p = (Patient) sessionFactory.getCurrentSession().createQuery("from Patient p where p.uuid = :uuid").setString("uuid", uuid).uniqueResult();
    return p;
}

19 View Complete Implementation : OrderServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see OrderService#getAllOrdersByPatient(org.openmrs.Patient)
 */
@Override
public List<Order> getAllOrdersByPatient(Patient patient) {
    if (patient == null) {
        throw new IllegalArgumentException("Patient is required");
    }
    return dao.getOrders(patient, null, null, true, true);
}

19 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.db.PatientDAO#getAllergyStatus(org.openmrs.Patient)
 */
// @Override
@Override
public String getAllergyStatus(Patient patient) {
    return (String) sessionFactory.getCurrentSession().createSQLQuery("select allergy_status from patient where patient_id = :patientId").setInteger("patientId", patient.getPatientId()).uniqueResult();
}

19 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.EncounterService#getEncountersByVisitsAndPatientCount(org.openmrs.Patient,
 *      boolean, java.lang.String)
 */
@Override
@Transactional(readOnly = true)
public Integer getEncountersByVisitsAndPatientCount(Patient patient, boolean includeVoided, String query) throws APIException {
    return dao.getEncountersByVisitsAndPatientCount(patient, includeVoided, query);
}

19 View Complete Implementation : EncounterSearchCriteriaBuilder.java
Copyright Apache License 2.0
Author : isstac
/**
 * @param patient the patient the encounter is for
 * @return this builder instance
 */
public EncounterSearchCriteriaBuilder setPatient(Patient patient) {
    this.patient = patient;
    return this;
}

19 View Complete Implementation : CohortServiceTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see CohortService#addPatientToCohort(Cohort,Patient)
 */
@Test
public void addPatientToCohort_shouldAddAPatientAndSaveTheCohort() {
    executeDataSet(COHORT_XML);
    // make a patient, add it using the method
    Patient patientToAdd = Context.getPatientService().getPatient(3);
    service.addPatientToCohort(service.getCohort(2), patientToAdd);
    // proof of "save the cohort": see if the patient is in the cohort
    replacedertTrue(service.getCohort(2).contains(3));
}

19 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.PatientService#deletePatient(org.openmrs.Patient)
 */
@Override
public void deletePatient(Patient patient) throws DAOException {
    HibernatePersonDAO.deletePersonAndAttributes(sessionFactory, patient);
}

19 View Complete Implementation : OrderServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.OrderService#getOrderHistoryByConcept(org.openmrs.Patient,
 *      org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public List<Order> getOrderHistoryByConcept(Patient patient, Concept concept) {
    if (patient == null || concept == null) {
        throw new IllegalArgumentException("patient and concept are required");
    }
    List<Concept> concepts = new ArrayList<>();
    concepts.add(concept);
    List<Patient> patients = new ArrayList<>();
    patients.add(patient);
    return dao.getOrders(null, patients, concepts, new ArrayList<>(), new ArrayList<>());
}

19 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.EncounterService#getEncountersByPatient(org.openmrs.Patient)
 */
@Override
@Transactional(readOnly = true)
public List<Encounter> getEncountersByPatient(Patient patient) throws APIException {
    if (patient == null) {
        throw new IllegalArgumentException("The 'patient' parameter is requred and cannot be null");
    }
    EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder().setPatient(patient).setIncludeVoided(false).createEncounterSearchCriteria();
    return Context.getEncounterService().getEncounters(encounterSearchCriteria);
}

19 View Complete Implementation : HibernateOrderDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see OrderDAO#getOrders(org.openmrs.Patient, org.openmrs.CareSetting, java.util.List,
 *      boolean, boolean)
 */
@Override
public List<Order> getOrders(Patient patient, CareSetting careSetting, List<OrderType> orderTypes, boolean includeVoided, boolean includeDiscontinuationOrders) {
    return createOrderCriteria(patient, careSetting, orderTypes, includeVoided, includeDiscontinuationOrders).list();
}

19 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.EncounterService#getEncountersByVisitsAndPatient(org.openmrs.Patient,
 *      boolean, java.lang.String, java.lang.Integer, java.lang.Integer)
 */
@Override
@Transactional(readOnly = true)
public List<Encounter> getEncountersByVisitsAndPatient(Patient patient, boolean includeVoided, String query, Integer start, Integer length) throws APIException {
    return Context.getEncounterService().filterEncountersByViewPermissions(dao.getEncountersByVisitsAndPatient(patient, includeVoided, query, start, length), null);
}

19 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
@Override
public Encounter transferEncounter(Encounter encounter, Patient patient) {
    Encounter encounterCopy = encounter.copyAndreplacedignToAnotherPatient(patient);
    voidEncounter(encounter, "transfer to patient: id = " + patient.getId());
    // void visit if voided encounter is the only one
    Visit visit = encounter.getVisit();
    if (visit != null && visit.getEncounters().size() == 1) {
        Context.getVisitService().voidVisit(visit, "Visit does not contain non-voided encounters");
    }
    return saveEncounter(encounterCopy);
}

19 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.EncounterService#getEncountersByPatientIdentifier(java.lang.String)
 */
@Override
@Transactional(readOnly = true)
public List<Encounter> getEncountersByPatientIdentifier(String identifier) throws APIException {
    if (identifier == null) {
        throw new IllegalArgumentException("The 'identifier' parameter is required and cannot be null");
    }
    List<Encounter> encs = new ArrayList<>();
    for (Patient p : Context.getPatientService().getPatients(identifier, null, null, false)) {
        encs.addAll(Context.getEncounterService().getEncountersByPatientId(p.getPatientId()));
    }
    return Context.getEncounterService().filterEncountersByViewPermissions(encs, null);
}

18 View Complete Implementation : VisitServiceTest.java
Copyright Apache License 2.0
Author : isstac
@Test
public void getVisitsByPatient_shouldReturnEmptyListGivenPatientWithNullPatientIdAndFalse() {
    Patient p = new Patient();
    p.setPatientId(null);
    replacedertThat(visitService.getVisitsByPatient(p, false, false), is(empty()));
}

18 View Complete Implementation : VisitServiceTest.java
Copyright Apache License 2.0
Author : isstac
@Test
public void getVisitsByPatient_shouldReturnEmptyListGivenPatientWithNullPatientId() {
    Patient p = new Patient();
    p.setPatientId(null);
    replacedertThat(visitService.getVisitsByPatient(p), is(empty()));
}

18 View Complete Implementation : ProgramWorkflowServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.ProgramWorkflowService#getPatientPrograms(Patient, Program, Date, Date,
 *      Date, Date, boolean)
 */
@Override
@Transactional(readOnly = true)
public List<PatientProgram> getPatientPrograms(Patient patient, Program program, Date minEnrollmentDate, Date maxEnrollmentDate, Date minCompletionDate, Date maxCompletionDate, boolean includeVoided) throws APIException {
    return dao.getPatientPrograms(patient, program, minEnrollmentDate, maxEnrollmentDate, minCompletionDate, maxCompletionDate, includeVoided);
}

18 View Complete Implementation : OrderServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see OrderService#getOrders(org.openmrs.Patient, org.openmrs.CareSetting,
 *      org.openmrs.OrderType, boolean)
 */
@Override
public List<Order> getOrders(Patient patient, CareSetting careSetting, OrderType orderType, boolean includeVoided) {
    if (patient == null) {
        throw new IllegalArgumentException("Patient is required");
    }
    if (careSetting == null) {
        throw new IllegalArgumentException("CareSetting is required");
    }
    List<OrderType> orderTypes = null;
    if (orderType != null) {
        orderTypes = new ArrayList<>();
        orderTypes.add(orderType);
        orderTypes.addAll(getSubtypes(orderType, true));
    }
    return dao.getOrders(patient, careSetting, orderTypes, includeVoided, false);
}

18 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @param patient  patient to be created or updated
 * @return         patient who was created or updated
 * @see org.openmrs.api.db.PatientDAO#savePatient(org.openmrs.Patient)
 */
@Override
public Patient savePatient(Patient patient) throws DAOException {
    if (patient.getPatientId() == null) {
        // if we're saving a new patient, just do the normal thing
        // and rows in the person and patient table will be created by
        // hibernate
        sessionFactory.getCurrentSession().saveOrUpdate(patient);
        return patient;
    } else {
        // if we're updating a patient, its possible that a person
        // row exists but a patient row does not. hibernate does not deal
        // with this correctly right now, so we must create a dummy row
        // in the patient table before saving
        // Check to make sure we have a row in the patient table already.
        // If we don't have a row, create it so Hibernate doesn't bung
        // things up
        insertPatientStubIfNeeded(patient);
        // Note: A merge might be necessary here because hibernate thinks that Patients
        // and Persons are the same objects.  So it sees a Person object in the
        // cache and claims it is a duplicate of this Patient object.
        sessionFactory.getCurrentSession().saveOrUpdate(patient);
        return patient;
    }
}

18 View Complete Implementation : CohortServiceTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see CohortService#addPatientToCohort(Cohort,Patient)
 */
@Test
public void addPatientToCohort_shouldNotFailIfCohortAlreadyContainsPatient() {
    executeDataSet(COHORT_XML);
    // make a patient, add it using the method
    Patient patientToAdd = Context.getPatientService().getPatient(3);
    service.addPatientToCohort(service.getCohort(2), patientToAdd);
    replacedertTrue(service.getCohort(2).contains(3));
    // do it again to see if it fails
    try {
        service.addPatientToCohort(service.getCohort(2), patientToAdd);
    } catch (Exception e) {
        replacedert.fail("addPatientToCohort(Cohort,Patient) fails when cohort already contains patient.");
    }
}

17 View Complete Implementation : PatientServiceImplTest.java
Copyright Apache License 2.0
Author : isstac
@Test
public void checkPatientIdentifiers_shouldIgnoreAbsenceOfActiveIdentifiersGivenPatientIsVoided() throws Exception {
    // given
    Patient patient = new Patient();
    patient.setVoided(true);
    patient.addIdentifier(createVoidedPatientIdentifier());
    // when
    patientService.checkPatientIdentifiers(patient);
// no exception
}

17 View Complete Implementation : OrderServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.OrderService#getActiveOrders(org.openmrs.Patient, org.openmrs.OrderType,
 *      org.openmrs.CareSetting, java.util.Date)
 */
@Override
@Transactional(readOnly = true)
public List<Order> getActiveOrders(Patient patient, OrderType orderType, CareSetting careSetting, Date asOfDate) {
    if (patient == null) {
        throw new IllegalArgumentException("Patient is required when fetching active orders");
    }
    if (asOfDate == null) {
        asOfDate = new Date();
    }
    List<OrderType> orderTypes = null;
    if (orderType != null) {
        orderTypes = new ArrayList<>();
        orderTypes.add(orderType);
        orderTypes.addAll(getSubtypes(orderType, true));
    }
    return dao.getActiveOrders(patient, orderTypes, careSetting, asOfDate);
}

17 View Complete Implementation : PatientServiceImplTest.java
Copyright Apache License 2.0
Author : isstac
@Test(expected = InsufficientIdentifiersException.clreplaced)
public void checkPatientIdentifiers_shouldThrowInsufficientIdentifiersErrorGivenPatientHasNoActiveIdentifiers() throws Exception {
    // given
    Patient patient = new Patient();
    patient.setVoided(false);
    patient.addIdentifier(createVoidedPatientIdentifier());
    // when
    patientService.checkPatientIdentifiers(patient);
// this patient only has a voided identifier, so saving is not allowed > exception
}

17 View Complete Implementation : HibernateOrderDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * Creates and returns a Criteria Object filtering on the specified parameters
 *
 * @param patient
 * @param careSetting
 * @param orderTypes
 * @param includeVoided
 * @param includeDiscontinuationOrders
 * @return
 */
private Criteria createOrderCriteria(Patient patient, CareSetting careSetting, List<OrderType> orderTypes, boolean includeVoided, boolean includeDiscontinuationOrders) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Order.clreplaced);
    if (patient != null) {
        criteria.add(Restrictions.eq("patient", patient));
    }
    if (careSetting != null) {
        criteria.add(Restrictions.eq("careSetting", careSetting));
    }
    if (orderTypes != null && !orderTypes.isEmpty()) {
        criteria.add(Restrictions.in("orderType", orderTypes));
    }
    if (!includeVoided) {
        criteria.add(Restrictions.eq("voided", false));
    }
    if (!includeDiscontinuationOrders) {
        criteria.add(Restrictions.ne("action", Order.Action.DISCONTINUE));
    }
    return criteria;
}

17 View Complete Implementation : ADTA28Handler.java
Copyright Apache License 2.0
Author : isstac
private Message processADT_A28(ADT_A05 adt) throws HL7Exception {
    // validate HL7 version
    validate(adt);
    // extract segments for convenient use below
    MSH msh = getMSH(adt);
    PID pid = getPID(adt);
    // Obtain message control id (unique ID for message from sending
    // application). Eventually avoid replaying the same message.
    String messageControlId = msh.getMessageControlID().getValue();
    log.debug("Found HL7 message in inbound queue with control id = " + messageControlId);
    // Add creator of the patient to application
    String sendingApp = msh.getSendingApplication().getComponent(0).toString();
    log.debug("SendingApplication = " + sendingApp);
    // Search for the patient
    Integer patientId = findPatientId(pid);
    // Create new patient if the patient id doesn't exist yet
    if (patientId == null) {
        log.info("Creating new patient in response to ADT_A28 " + messageControlId);
        Patient patient = createPatient(pid, sendingApp);
        if (patient == null) {
            throw new HL7Exception("Couldn't create Patient object from PID");
        }
        Context.getPatientService().savePatient(patient);
    } else {
        log.info("Ignoring ADT_A28 message because patient (" + patientId + ") already exists.");
    }
    // replacedumption: all observations (OBX) messages will be in the R01
    return adt;
}

17 View Complete Implementation : EncounterServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.EncounterService#getEncounters(org.openmrs.Patient,
 *      org.openmrs.Location, java.util.Date, java.util.Date, java.util.Collection,
 *      java.util.Collection, java.util.Collection, java.util.Collection, java.util.Collection,
 *      boolean)
 * @deprecated As of 2.0, replaced by {@link #getEncounters(EncounterSearchCriteria)}
 */
@Deprecated
@Override
@Transactional(readOnly = true)
public List<Encounter> getEncounters(Patient who, Location loc, Date fromDate, Date toDate, Collection<Form> enteredViaForms, Collection<EncounterType> encounterTypes, Collection<Provider> providers, Collection<VisitType> visitTypes, Collection<Visit> visits, boolean includeVoided) {
    EncounterSearchCriteriaBuilder encounterSearchCriteriaBuilder = new EncounterSearchCriteriaBuilder().setPatient(who).setLocation(loc).setFromDate(fromDate).setToDate(toDate).setEnteredViaForms(enteredViaForms).setEncounterTypes(encounterTypes).setProviders(providers).setVisitTypes(visitTypes).setVisits(visits).setIncludeVoided(includeVoided);
    return getEncounters(encounterSearchCriteriaBuilder.createEncounterSearchCriteria());
}

17 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
@Override
public int compare(Patient patient1, Patient patient2) {
    Integer patPos1 = sortOrder.get(patient1.getPatientId());
    if (patPos1 == null) {
        throw new IllegalArgumentException("Bad patient encountered: " + patient1.getPatientId());
    }
    Integer patPos2 = sortOrder.get(patient2.getPatientId());
    if (patPos2 == null) {
        throw new IllegalArgumentException("Bad patient encountered: " + patient2.getPatientId());
    }
    return patPos1.compareTo(patPos2);
}

17 View Complete Implementation : ORUR01Handler.java
Copyright Apache License 2.0
Author : isstac
/**
 * process an NK1 segment and add relationships if needed
 *
 * @param patient
 * @param nk1
 * @throws HL7Exception
 * @should create a relationship from a NK1 segment
 * @should not create a relationship if one exists
 * @should create a person if the relative is not found
 * @should fail if the coding system is not 99REL
 * @should fail if the relationship identifier is formatted improperly
 * @should fail if the relationship type is not found
 */
protected void processNK1(Patient patient, NK1 nk1) throws HL7Exception {
    // guarantee we are working with our custom coding system
    String relCodingSystem = nk1.getRelationship().getNameOfCodingSystem().getValue();
    if (!relCodingSystem.equals(HL7Constants.HL7_LOCAL_RELATIONSHIP)) {
        throw new HL7Exception(Context.getMessageSourceService().getMessage("ORUR01.error.relationshipCoding", new Object[] { relCodingSystem }, null));
    }
    // get the relationship type identifier
    String relIdentifier = nk1.getRelationship().getIdentifier().getValue();
    // validate the format of the relationship identifier
    if (!Pattern.matches("[0-9]+[AB]", relIdentifier)) {
        throw new HL7Exception(Context.getMessageSourceService().getMessage("ORUR01.error.relationshipType", new Object[] { relIdentifier }, null));
    }
    // get the type ID
    Integer relTypeId;
    try {
        relTypeId = Integer.parseInt(relIdentifier.substring(0, relIdentifier.length() - 1));
    } catch (NumberFormatException e) {
        throw new HL7Exception(Context.getMessageSourceService().getMessage("ORUR01.error.relationshipType", new Object[] { relIdentifier }, null));
    }
    // find the relationship type
    RelationshipType relType = Context.getPersonService().getRelationshipType(relTypeId);
    if (relType == null) {
        throw new HL7Exception(Context.getMessageSourceService().getMessage("ORUR01.error.relationshipTypeNotFound", new Object[] { relTypeId }, null));
    }
    // find the relative
    Person relative = getRelative(nk1);
    // determine if the patient is person A or B; the relIdentifier indicates
    // the relative's side of the relationship, so the patient is the inverse
    boolean patientIsPersonA = relIdentifier.endsWith("B");
    boolean patientCanBeEitherPerson = relType.getbIsToA().equals(relType.getaIsToB());
    // look at existing relationships to determine if a new one is needed
    Set<Relationship> rels = new HashSet<>();
    if (relative != null) {
        if (patientCanBeEitherPerson || patientIsPersonA) {
            rels.addAll(Context.getPersonService().getRelationships(patient, relative, relType));
        }
        if (patientCanBeEitherPerson || !patientIsPersonA) {
            rels.addAll(Context.getPersonService().getRelationships(relative, patient, relType));
        }
    }
    // create a relationship if none is found
    if (rels.isEmpty()) {
        // check the relative's existence
        if (relative == null) {
            // create one based on NK1 information
            relative = Context.getHL7Service().createPersonFromNK1(nk1);
            if (relative == null) {
                throw new HL7Exception(Context.getMessageSourceService().getMessage("ORUR01.error.relativeNotCreated"));
            }
        }
        // create the relationship
        Relationship relation = new Relationship();
        if (patientCanBeEitherPerson || patientIsPersonA) {
            relation.setPersonA(patient);
            relation.setPersonB(relative);
        } else {
            relation.setPersonA(relative);
            relation.setPersonB(patient);
        }
        relation.setRelationshipType(relType);
        Context.getPersonService().saveRelationship(relation);
    }
}

17 View Complete Implementation : ConditionServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * Gets a patient's active conditions
 *
 * @param patient - the patient to retrieve conditions for
 *
 * @return a list of the patient's active conditions
 */
@Override
@Transactional(readOnly = true)
public List<Condition> getActiveConditions(Patient patient) {
    return conditionDAO.getActiveConditions(patient);
}

17 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs..api.db.PatientDAO#getAllergies(org.openmrs.Patient)
 */
// @Override
@Override
public List<Allergy> getAllergies(Patient patient) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Allergy.clreplaced);
    criteria.add(Restrictions.eq("patient", patient));
    criteria.add(Restrictions.eq("voided", false));
    return criteria.list();
}

17 View Complete Implementation : HibernateEncounterDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.db.EncounterDAO#getEncountersByVisitsAndPatientCount(org.openmrs.Patient,
 *      boolean, java.lang.String)
 */
@Override
public Integer getEncountersByVisitsAndPatientCount(Patient patient, boolean includeVoided, String query) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Visit.clreplaced);
    addEmptyVisitsByPatientCriteria(criteria, patient, includeVoided, query);
    criteria.setProjection(Projections.rowCount());
    Integer count = ((Number) criteria.uniqueResult()).intValue();
    criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.clreplaced);
    addEncountersByPatientCriteria(criteria, patient, includeVoided, query);
    criteria.setProjection(Projections.rowCount());
    count = count + ((Number) criteria.uniqueResult()).intValue();
    return count;
}

17 View Complete Implementation : RequireVoidReasonVoidHandlerTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see RequireVoidReasonVoidHandler#handle(Voidable,User,Date,String)
 */
@Test(expected = IllegalArgumentException.clreplaced)
public void handle_shouldThrowIllegalArgumentExceptionIfPatientVoidReasonIsNull() {
    Patient p = Context.getPatientService().getPatient(2);
    Context.getPatientService().voidPatient(p, null);
}

17 View Complete Implementation : CohortServiceTest.java
Copyright Apache License 2.0
Author : isstac
@Test
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() {
    executeDataSet(COHORT_XML);
    // make a patient
    Patient notInCohort = new Patient(4);
    // verify that the patient is not already in the Cohort
    replacedertFalse(service.getCohort(2).contains(notInCohort.getPatientId()));
    // try to remove it from the cohort without failing
    try {
        service.removePatientFromCohort(service.getCohort(2), notInCohort);
    } catch (Exception e) {
        replacedert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient");
    }
}

16 View Complete Implementation : CohortServiceTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see CohortService#getCohortsContainingPatient(Patient)
 */
@Test
public void getCohortsContainingPatient_shouldNotReturnVoidedCohorts() {
    executeDataSet(COHORT_XML);
    // make sure we have two cohorts, the first of which is voided
    replacedertTrue(service.getCohort(1).getVoided());
    replacedertFalse(service.getCohort(2).getVoided());
    // add a patient to both cohorts
    Patient patientToAdd = new Patient(7);
    service.addPatientToCohort(service.getCohort(1), patientToAdd);
    service.addPatientToCohort(service.getCohort(2), patientToAdd);
    replacedertTrue(service.getCohort(1).contains(patientToAdd.getPatientId()));
    replacedertTrue(service.getCohort(2).contains(patientToAdd.getPatientId()));
    // call the method and it should not return the voided cohort
    List<Cohort> cohortsWithPatientAdded = service.getCohortsContainingPatientId(patientToAdd.getId());
    replacedertNotNull(cohortsWithPatientAdded);
    replacedertFalse(cohortsWithPatientAdded.contains(service.getCohort(1)));
}

16 View Complete Implementation : VisitValidatorTest.java
Copyright Apache License 2.0
Author : isstac
private boolean patientHasVoidedVisit(Patient patient, long startInMillis, long stopInMillis) {
    // To get voided visit from the past, both inactive AND voided visits are queried.
    // 
    List<Visit> visitList = Context.getVisitService().getVisitsByPatient(patient, true, true);
    for (Visit visit : visitList) {
        if (visit.getStartDatetime() != null && visit.getStartDatetime().getTime() == startInMillis && visit.getStopDatetime() != null && visit.getStopDatetime().getTime() == stopInMillis && visit.getVoided()) {
            return true;
        }
    }
    return false;
}

16 View Complete Implementation : CohortServiceTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see CohortService#getCohortsContainingPatient(Patient)
 */
@Test
public void getCohortsContainingPatient_shouldReturnCohortsThatHaveGivenPatient() {
    executeDataSet(COHORT_XML);
    Patient patientToAdd = new Patient(7);
    service.addPatientToCohort(service.getCohort(2), patientToAdd);
    replacedertTrue(service.getCohort(2).contains(patientToAdd.getPatientId()));
    List<Cohort> cohortsWithGivenPatient = service.getCohortsContainingPatientId(patientToAdd.getId());
    replacedertTrue(cohortsWithGivenPatient.contains(service.getCohort(2)));
}

16 View Complete Implementation : HibernatePatientDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.db.PatientDAO#saveAllergies(org.openmrs.Patient,
 *      org.openmrsallergyapi.Allergies)
 */
@Override
public Allergies saveAllergies(Patient patient, Allergies allergies) {
    sessionFactory.getCurrentSession().createSQLQuery("update patient set allergy_status = :allergyStatus where patient_id = :patientId").setInteger("patientId", patient.getPatientId()).setString("allergyStatus", allergies.getAllergyStatus()).executeUpdate();
    for (Allergy allergy : allergies) {
        sessionFactory.getCurrentSession().save(allergy);
    }
    return allergies;
}

16 View Complete Implementation : CohortServiceImpl.java
Copyright Apache License 2.0
Author : isstac
@Override
@Transactional(readOnly = true)
public List<Cohort> getCohortsContainingPatient(Patient patient) {
    return getCohortsContainingPatientId(patient.getPatientId());
}

16 View Complete Implementation : VisitServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.VisitService#getActiveVisitsByPatient(org.openmrs.Patient)
 */
@Override
@Transactional(readOnly = true)
public List<Visit> getActiveVisitsByPatient(Patient patient) throws APIException {
    return Context.getVisitService().getVisitsByPatient(patient, false, false);
}

16 View Complete Implementation : EncounterSearchCriteria.java
Copyright Apache License 2.0
Author : isstac
/**
 * The search parameter object for encounters. A convenience interface for building
 * instances is provided by {@link EncounterSearchCriteriaBuilder}.
 *
 * @since 1.12
 * @see EncounterSearchCriteriaBuilder
 */
public clreplaced EncounterSearchCriteria {

    private Patient patient;

    private Location location;

    private Date fromDate;

    private Date toDate;

    private Date dateChanged;

    private Collection<Form> enteredViaForms;

    private Collection<EncounterType> encounterTypes;

    private Collection<Provider> providers;

    private Collection<VisitType> visitTypes;

    private Collection<Visit> visits;

    private boolean includeVoided;

    /**
     * Instead of calling this constructor directly, it is recommended to use {@link EncounterSearchCriteriaBuilder}.
     * @param patient the patient the encounter is for
     * @param location the location this encounter took place
     * @param fromDate the minimum date (inclusive) the encounter took place
     * @param toDate the maximum date (exclusive) the encounter took place
     * @param dateChanged the minimum date the encounter was changed
     * @param enteredViaForms the form that entered this encounter must be in this collection
     * @param encounterTypes the type of the encounter must be in this collection
     * @param providers the provider of the encounter must be in this collection
     * @param visitTypes the visit types of the encounter must be in this collection
     * @param visits the visits of the encounter must be in this collection
     * @param includeVoided whether to include the voided encounters or not
     */
    public EncounterSearchCriteria(Patient patient, Location location, Date fromDate, Date toDate, Date dateChanged, Collection<Form> enteredViaForms, Collection<EncounterType> encounterTypes, Collection<Provider> providers, Collection<VisitType> visitTypes, Collection<Visit> visits, boolean includeVoided) {
        this.patient = patient;
        this.location = location;
        this.fromDate = fromDate;
        this.toDate = toDate;
        this.dateChanged = dateChanged;
        this.enteredViaForms = enteredViaForms;
        this.encounterTypes = encounterTypes;
        this.providers = providers;
        this.visitTypes = visitTypes;
        this.visits = visits;
        this.includeVoided = includeVoided;
    }

    /**
     * @return the patient the encounter is for
     */
    public Patient getPatient() {
        return patient;
    }

    /**
     * @return the location this encounter took place
     */
    public Location getLocation() {
        return location;
    }

    /**
     * @return the minimum date (inclusive) this encounter took place
     */
    public Date getFromDate() {
        return fromDate;
    }

    /**
     * @return the maximum date (exclusive) this encounter took place
     */
    public Date getToDate() {
        return toDate;
    }

    /**
     * @return the minimum date this encounter was changed
     */
    public Date getDateChanged() {
        return dateChanged;
    }

    /**
     * @return the form that entered this encounter must be in this collection
     */
    public Collection<Form> getEnteredViaForms() {
        return enteredViaForms;
    }

    /**
     * @return the type of encounter must be in this list
     */
    public Collection<EncounterType> getEncounterTypes() {
        return encounterTypes;
    }

    /**
     * @return the provider of this encounter must be in this list
     */
    public Collection<Provider> getProviders() {
        return providers;
    }

    /**
     * @return the visit types of this encounter must be in this list
     */
    public Collection<VisitType> getVisitTypes() {
        return visitTypes;
    }

    /**
     * @return the visits of this encounter must be in this list
     */
    public Collection<Visit> getVisits() {
        return visits;
    }

    /**
     * @return whether to include the voided encounters or not
     */
    public boolean getIncludeVoided() {
        return includeVoided;
    }
}

16 View Complete Implementation : EncounterSearchCriteriaBuilder.java
Copyright Apache License 2.0
Author : isstac
/**
 * A convenience builder for {@link EncounterSearchCriteria}. Create a builder, set
 * its properties to desired values and finally call {@link #createEncounterSearchCriteria()}
 * to create the actual search criteria instance.
 * @see EncounterSearchCriteria
 */
public clreplaced EncounterSearchCriteriaBuilder {

    private Patient patient;

    private Location location;

    private Date fromDate;

    private Date toDate;

    private Date dateChanged;

    private Collection<Form> enteredViaForms;

    private Collection<EncounterType> encounterTypes;

    private Collection<Provider> providers;

    private Collection<VisitType> visitTypes;

    private Collection<Visit> visits;

    private boolean includeVoided;

    /**
     * @param patient the patient the encounter is for
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setPatient(Patient patient) {
        this.patient = patient;
        return this;
    }

    /**
     * @param location the location the encounter took place
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setLocation(Location location) {
        this.location = location;
        return this;
    }

    /**
     * @param fromDate the minimum date (inclusive) the encounter took place
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setFromDate(Date fromDate) {
        this.fromDate = fromDate;
        return this;
    }

    /**
     * @param toDate the maximum date (exclusive) the encounter took place
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setToDate(Date toDate) {
        this.toDate = toDate;
        return this;
    }

    /**
     * @param dateChanged the minimum date the encounter was changed
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setDateChanged(Date dateChanged) {
        this.dateChanged = dateChanged;
        return this;
    }

    /**
     * @param enteredViaForms the form that entered the encounter must be in this collection.
     *                           This search parameter is omitted if the set is null or empty.
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setEnteredViaForms(Collection<Form> enteredViaForms) {
        this.enteredViaForms = enteredViaForms;
        return this;
    }

    /**
     * @param encounterTypes the type of the encounter must be in this collection.
     *                           This search parameter is omitted if the set is null or empty.
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setEncounterTypes(Collection<EncounterType> encounterTypes) {
        this.encounterTypes = encounterTypes;
        return this;
    }

    /**
     * @param providers the provider of the encounter must be in this collection.
     *                           This search parameter is omitted if the set is null or empty.
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setProviders(Collection<Provider> providers) {
        this.providers = providers;
        return this;
    }

    /**
     * @param visitTypes the visit types of the encounter must be in this collection.
     *                           This search parameter is omitted if the set is null or empty.
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setVisitTypes(Collection<VisitType> visitTypes) {
        this.visitTypes = visitTypes;
        return this;
    }

    /**
     * @param visits the visits of the encounter must be in this collection.
     *                           This search parameter is omitted if the set is null or empty.
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setVisits(Collection<Visit> visits) {
        this.visits = visits;
        return this;
    }

    /**
     * @param includeVoided whether to include the voided encounters or not
     * @return this builder instance
     */
    public EncounterSearchCriteriaBuilder setIncludeVoided(boolean includeVoided) {
        this.includeVoided = includeVoided;
        return this;
    }

    /**
     * Create an {@link EncounterSearchCriteria} with the properties of this builder instance.
     * @return a new search criteria instance
     */
    public EncounterSearchCriteria createEncounterSearchCriteria() {
        return new EncounterSearchCriteria(patient, location, fromDate, toDate, dateChanged, enteredViaForms, encounterTypes, providers, visitTypes, visits, includeVoided);
    }
}

16 View Complete Implementation : ValidateUtilTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see ValidateUtil#validate(Object,Errors)
 */
@Test
public void validate_shouldReturnImmediatelyIfValidationIsDisabledAndHaveNoErrors() {
    Boolean prevVal = ValidateUtil.getDisableValidation();
    ValidateUtil.setDisableValidation(true);
    try {
        Patient patient = new Patient();
        Errors errors = new BindException(patient, "patient");
        ValidateUtil.validate(patient, errors);
        replacedertFalse(errors.hasErrors());
    } catch (Exception e) {
        ValidateUtil.setDisableValidation(prevVal);
        e.printStackTrace();
        fail("An unexpected exception occurred");
    }
    ValidateUtil.setDisableValidation(prevVal);
}

16 View Complete Implementation : HibernateEncounterDAO.java
Copyright Apache License 2.0
Author : isstac
@SuppressWarnings("unchecked")
@Override
public List<Encounter> getEncountersNotreplacedignedToAnyVisit(Patient patient) throws DAOException {
    return sessionFactory.getCurrentSession().createCriteria(Encounter.clreplaced).add(Restrictions.eq("patient", patient)).add(Restrictions.isNull("visit")).add(Restrictions.eq("voided", false)).addOrder(Order.desc("encounterDatetime")).setMaxResults(100).list();
}

15 View Complete Implementation : HibernateEncounterDAO.java
Copyright Apache License 2.0
Author : isstac
private void addEncountersByPatientCriteria(Criteria criteria, Patient patient, boolean includeVoided, String query) {
    criteria.add(Restrictions.eq("patient", patient));
    criteria.createAlias("visit", "visit", JoinType.LEFT_OUTER_JOIN);
    if (!includeVoided) {
        criteria.add(Restrictions.eq("voided", includeVoided));
    }
    if (query != null && !StringUtils.isBlank(query)) {
        criteria.createAlias("visit.visitType", "visitType", JoinType.LEFT_OUTER_JOIN);
        criteria.createAlias("visit.location", "visitLocation", JoinType.LEFT_OUTER_JOIN);
        criteria.createAlias("location", "location", JoinType.LEFT_OUTER_JOIN);
        criteria.createAlias("encounterType", "encounterType", JoinType.LEFT_OUTER_JOIN);
        Disjunction or = Restrictions.disjunction();
        criteria.add(or);
        or.add(Restrictions.ilike("visitType.name", query, MatchMode.ANYWHERE));
        or.add(Restrictions.ilike("visitLocation.name", query, MatchMode.ANYWHERE));
        or.add(Restrictions.ilike("location.name", query, MatchMode.ANYWHERE));
        or.add(Restrictions.ilike("encounterType.name", query, MatchMode.ANYWHERE));
    }
    criteria.addOrder(Order.desc("visit.startDatetime"));
    criteria.addOrder(Order.desc("visit.visitId"));
    criteria.addOrder(Order.desc("encounterDatetime"));
    criteria.addOrder(Order.desc("encounterId"));
}

15 View Complete Implementation : PatientSaveHandler.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.handler.SaveHandler#handle(org.openmrs.OpenmrsObject, org.openmrs.User,
 *      java.util.Date, java.lang.String)
 */
@Override
public void handle(Patient patient, User creator, Date dateCreated, String other) {
    if (patient.getIdentifiers() != null) {
        for (PatientIdentifier pIdentifier : patient.getIdentifiers()) {
            // make sure the identifier is replacedociated with the current patient
            if (pIdentifier.getPatient() == null) {
                pIdentifier.setPatient(patient);
            }
        }
    }
}

15 View Complete Implementation : HibernateOrderDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.db.OrderDAO#getActiveOrders(org.openmrs.Patient, java.util.List,
 *      org.openmrs.CareSetting, java.util.Date)
 */
@Override
@SuppressWarnings("unchecked")
public List<Order> getActiveOrders(Patient patient, List<OrderType> orderTypes, CareSetting careSetting, Date asOfDate) {
    Criteria crit = createOrderCriteria(patient, careSetting, orderTypes, false, false);
    crit.add(Restrictions.le("dateActivated", asOfDate));
    Disjunction dateStoppedAndAutoExpDateDisjunction = Restrictions.disjunction();
    Criterion stopAndAutoExpDateAreBothNull = Restrictions.and(Restrictions.isNull("dateStopped"), Restrictions.isNull("autoExpireDate"));
    dateStoppedAndAutoExpDateDisjunction.add(stopAndAutoExpDateAreBothNull);
    Criterion autoExpireDateEqualToOrAfterAsOfDate = Restrictions.and(Restrictions.isNull("dateStopped"), Restrictions.ge("autoExpireDate", asOfDate));
    dateStoppedAndAutoExpDateDisjunction.add(autoExpireDateEqualToOrAfterAsOfDate);
    dateStoppedAndAutoExpDateDisjunction.add(Restrictions.ge("dateStopped", asOfDate));
    crit.add(dateStoppedAndAutoExpDateDisjunction);
    return crit.list();
}

15 View Complete Implementation : RequiredReasonVoidSaveHandlerTest.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see RequireVoidReasonSaveHandler#handle(Voidable,User,Date,String)
 */
@Test(expected = APIException.clreplaced)
public void handle_shouldThrowAPIExceptionIfPatientVoidReasonIsNull() {
    Patient p = Context.getPatientService().getPatient(2);
    p.setVoided(true);
    p.setVoidReason(null);
    Context.getPatientService().savePatient(p);
}

15 View Complete Implementation : HibernateEncounterDAO.java
Copyright Apache License 2.0
Author : isstac
private void addEmptyVisitsByPatientCriteria(Criteria criteria, Patient patient, boolean includeVoided, String query) {
    criteria.add(Restrictions.eq("patient", patient));
    criteria.add(Restrictions.isEmpty("encounters"));
    if (!includeVoided) {
        criteria.add(Restrictions.eq("voided", includeVoided));
    }
    if (query != null && !StringUtils.isBlank(query)) {
        criteria.createAlias("visitType", "visitType", JoinType.LEFT_OUTER_JOIN);
        criteria.createAlias("location", "location", JoinType.LEFT_OUTER_JOIN);
        Disjunction or = Restrictions.disjunction();
        criteria.add(or);
        or.add(Restrictions.ilike("visitType.name", query, MatchMode.ANYWHERE));
        or.add(Restrictions.ilike("location.name", query, MatchMode.ANYWHERE));
    }
    criteria.addOrder(Order.desc("startDatetime"));
    criteria.addOrder(Order.desc("visitId"));
}

15 View Complete Implementation : DiagnosisServiceImpl.java
Copyright Apache License 2.0
Author : isstac
/**
 * Gets diagnoses since date, sorted in reverse chronological order
 *
 * @param patient  the patient whose diagnosis we are to get
 * @param fromDate the date used to filter diagnosis which happened from this date and later
 * @return the list of diagnoses for the given patient and starting from the given date
 */
@Override
@Transactional(readOnly = true)
public List<Diagnosis> getDiagnoses(Patient patient, Date fromDate) {
    return diagnosisDAO.getActiveDiagnoses(patient, fromDate);
}