Example usage for org.apache.commons.lang.time DateUtils addDays

List of usage examples for org.apache.commons.lang.time DateUtils addDays

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils addDays.

Prototype

public static Date addDays(Date date, int amount) 

Source Link

Document

Adds a number of days to a date returning a new object.

Usage

From source file:org.openmrs.module.emrapi.adt.AdtServiceTest.java

@Test
public void testOverlappingVisits() throws Exception {
    Patient patient = new Patient();
    VisitType visitType = new VisitType();

    Date now = new Date();
    Date tenDaysAgo = DateUtils.addDays(now, -10);
    Date nineDaysAgo = DateUtils.addDays(now, -9);
    Date eightDaysAgo = DateUtils.addDays(now, -8);
    Date sevenDaysAgo = DateUtils.addDays(now, -7);

    Visit visit1 = buildVisit(patient, visitType, mirebalaisHospital, tenDaysAgo, eightDaysAgo);
    Visit visit2 = buildVisit(patient, visitType, mirebalaisHospital, now, null);
    Visit visit3 = buildVisit(patient, visitType, null, tenDaysAgo, nineDaysAgo);
    Visit visit4 = buildVisit(patient, visitType, mirebalaisHospital, nineDaysAgo, sevenDaysAgo);

    assertThat(service.visitsOverlap(visit1, visit2), is(false));
    assertThat(service.visitsOverlap(visit1, visit3), is(false));
    assertThat(service.visitsOverlap(visit1, visit4), is(true));
}

From source file:org.openmrs.module.emrapi.adt.AdtServiceTest.java

@Test
public void testMergePatientsJoinsOverlappingVisits() throws Exception {
    Patient preferred = new Patient();
    Patient notPreferred = new Patient();

    Date now = new Date();
    Date tenDaysAgo = DateUtils.addDays(now, -10);
    Date nineDaysAgo = DateUtils.addDays(now, -9);
    Date eightDaysAgo = DateUtils.addDays(now, -8);
    Date sevenDaysAgo = DateUtils.addDays(now, -7);

    Visit first = buildVisit(notPreferred, null, mirebalaisHospital, tenDaysAgo, eightDaysAgo);
    Visit last = buildVisit(notPreferred, null, mirebalaisHospital, sevenDaysAgo, null);
    Visit middle = buildVisit(preferred, null, mirebalaisHospital, nineDaysAgo, now);
    Visit unrelated = buildVisit(preferred, null, null, tenDaysAgo, eightDaysAgo);
    Visit voided = buildVisit(notPreferred, null, mirebalaisHospital, tenDaysAgo, sevenDaysAgo);
    voided.setVoided(true);//from w ww. ja  va 2  s  .co  m

    first.addEncounter(buildEncounter(notPreferred, tenDaysAgo));
    middle.addEncounter(buildEncounter(preferred, nineDaysAgo));

    when(mockVisitService.getVisitsByPatient(preferred, true, false))
            .thenReturn(Arrays.asList(middle, unrelated));
    when(mockVisitService.getVisitsByPatient(notPreferred, true, false))
            .thenReturn(Arrays.asList(first, voided, last));

    service.mergePatients(preferred, notPreferred);

    verify(mockVisitService).voidVisit(eq(first), anyString());
    verify(mockVisitService).voidVisit(eq(last), anyString());

    assertThat(middle.getStartDatetime(), is(tenDaysAgo));
    assertNull(middle.getStopDatetime());
    assertThat(middle.getEncounters().size(), is(2));
    for (Encounter e : middle.getEncounters()) {
        assertThat(e.getVisit(), is(middle));
        assertThat(e.getPatient(), is(middle.getPatient()));
    }

    verify(mockVisitService, times(2)).saveVisit(middle); // two visits merged in

    verify(mockVisitService, never()).saveVisit(unrelated);
    verify(mockVisitService, never()).saveVisit(voided);
    verify(mockVisitService, never()).voidVisit(eq(unrelated), anyString());
    verify(mockVisitService, never()).voidVisit(eq(voided), anyString());

    verify(mockPatientService).mergePatients(preferred, notPreferred);
}

From source file:org.openmrs.module.emrapi.adt.AdtServiceTest.java

@Test
public void testMergePatientsDoesNotResultInOverlappingVisits() throws Exception {
    Patient preferred = new Patient();
    Patient notPreferred = new Patient();

    Date now = new Date();
    Date twelveDaysAgo = DateUtils.addDays(now, -12);
    Date elevenDaysAgo = DateUtils.addDays(now, -11);
    Date tenDaysAgo = DateUtils.addDays(now, -10);
    Date nineDaysAgo = DateUtils.addDays(now, -9);
    Date eightDaysAgo = DateUtils.addDays(now, -8);
    Date sevenDaysAgo = DateUtils.addDays(now, -7);

    //           ___nonPreferredVisit______________
    //           |                                |
    //  |                      |       |                      |
    //  |_firstPreferredVisit__|.......|_secondPreferredVisit_|
    ///*  w w  w.j  a  va  2s  . c  o  m*/
    // 12       11            10       9          8           7

    Visit nonPreferredVisit = buildVisit(notPreferred, null, mirebalaisHospital, elevenDaysAgo, eightDaysAgo);
    nonPreferredVisit.addEncounter(buildEncounter(notPreferred, tenDaysAgo));

    Visit firstPreferredVisit = buildVisit(preferred, null, mirebalaisHospital, twelveDaysAgo, tenDaysAgo);
    firstPreferredVisit.addEncounter(buildEncounter(notPreferred, elevenDaysAgo));

    Visit secondPreferredVisit = buildVisit(preferred, null, mirebalaisHospital, nineDaysAgo, sevenDaysAgo);
    secondPreferredVisit.addEncounter(buildEncounter(notPreferred, eightDaysAgo));

    when(mockVisitService.getVisitsByPatient(notPreferred, true, false))
            .thenReturn(Arrays.asList(nonPreferredVisit));
    when(mockVisitService.getVisitsByPatient(preferred, true, false))
            .thenReturn(Arrays.asList(firstPreferredVisit, secondPreferredVisit));

    service.mergePatients(preferred, notPreferred);

    assertThat(firstPreferredVisit.getStartDatetime(), is(twelveDaysAgo));
    assertThat(firstPreferredVisit.getStopDatetime(), is(sevenDaysAgo));

    verify(mockVisitService).voidVisit(eq(nonPreferredVisit), anyString());
    verify(mockVisitService).voidVisit(eq(secondPreferredVisit), anyString());
    verify(mockVisitService, times(2)).saveVisit(firstPreferredVisit); // two visits merged in

    verify(mockPatientService).mergePatients(preferred, notPreferred);
}

From source file:org.openmrs.module.emrapi.adt.EmrApiVisitAssignmentHandlerTest.java

@Ignore("TEMP HACK: disable this while we decide whether or not we want this functionality")
@Test(expected = IllegalStateException.class)
public void testThrowsExceptionIfNoSuitableVisitExists() throws Exception {
    Patient patient = new Patient();
    Location location = new Location();

    Visit notSuitable = new Visit();
    notSuitable.setPatient(patient);/* w  ww .j  a v  a2  s .com*/
    notSuitable.setStartDatetime(DateUtils.addDays(new Date(), -7));
    notSuitable.setStopDatetime(DateUtils.addDays(new Date(), -6));
    notSuitable.setLocation(location);

    when(visitService.getVisits(any(Collection.class), any(Collection.class), any(Collection.class),
            any(Collection.class), any(Date.class), any(Date.class), any(Date.class), any(Date.class),
            any(Map.class), anyBoolean(), anyBoolean())).thenReturn(Collections.singletonList(notSuitable));

    Encounter encounter = new Encounter();
    encounter.setPatient(patient);
    encounter.setLocation(location);

    handler.beforeCreateEncounter(encounter);
}

From source file:org.openmrs.module.emrapi.adt.EmrApiVisitAssignmentHandlerTest.java

@Test
public void testAssigningASuitableVisitWhenOneExists() throws Exception {
    Patient patient = new Patient();
    Location location = new Location();

    Visit notSuitable = new Visit();
    notSuitable.setPatient(patient);/*from  www .j  a  va2  s .c  o  m*/
    notSuitable.setStartDatetime(DateUtils.addDays(new Date(), -7));
    notSuitable.setStopDatetime(DateUtils.addDays(new Date(), -6));
    notSuitable.setLocation(location);

    Visit suitable = new Visit();
    suitable.setPatient(patient);
    suitable.setStartDatetime(DateUtils.addDays(new Date(), -1));
    suitable.setLocation(location);

    when(visitService.getVisits(any(Collection.class), any(Collection.class), any(Collection.class),
            any(Collection.class), any(Date.class), any(Date.class), any(Date.class), any(Date.class),
            any(Map.class), anyBoolean(), anyBoolean())).thenReturn(Arrays.asList(notSuitable, suitable));

    Encounter encounter = new Encounter();
    encounter.setPatient(patient);
    encounter.setLocation(location);

    handler.beforeCreateEncounter(encounter);

    Assert.assertThat(encounter.getVisit(), is(suitable));
    Assert.assertThat(suitable.getEncounters(), contains(encounter));
}

From source file:org.openmrs.module.mirebalaisreports.dataset.definition.evaluator.NonCodedDiagnosisDataSetEvaluator.java

@Override
public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context)
        throws EvaluationException {
    Long startTime = new Date().getTime();
    NonCodedDiagnosisDataSetDefinition dsd = (NonCodedDiagnosisDataSetDefinition) dataSetDefinition;

    Date fromDate = ObjectUtil.nvl(dsd.getFromDate(), DateUtils.addDays(new Date(), -7));
    Date toDate = ObjectUtil.nvl(dsd.getToDate(), new Date());
    fromDate = DateUtil.getStartOfDay(fromDate);
    toDate = DateUtil.getEndOfDay(toDate);
    String nonCoded = ObjectUtil.nvl(dsd.getNonCoded(), null);
    Provider provider = ObjectUtil.nvl(dsd.getProvider(), null);
    Integer userId = null;//from   w  ww  . j  ava  2  s. com
    if (provider != null) {
        List<User> users = userService.getUsersByPerson(provider.getPerson(), true);
        if (users != null && users.size() > 0) {
            userId = users.get(0).getId();
        }
    }

    PatientIdentifierType primaryIdentifierType = emrApiProperties.getPrimaryIdentifierType();
    Concept nonCodedConcept = emrApiProperties.getDiagnosisMetadata().getNonCodedDiagnosisConcept();

    StringBuilder sqlQuery = new StringBuilder(
            "select " + "    o.value_text as 'nonCodedDiagnosis', " + "    o.creator as 'creatorId', "
                    + "    n.given_name as 'creatorFirstName', " + "    n.family_name as 'creatorLastName', "
                    + "    o.date_created as 'dateCreated', " + "    o.person_id as 'patientId', "
                    + "    id1.identifier as 'patientIdentifier', " + "    o.obs_id as 'obsId', "
                    + "    e.visit_id as 'visitId', " + "    e.encounter_datetime as 'encounterDateTime', "
                    + "    n1.given_name as 'patientFirstName', " + "    n1.family_name as 'patientLastName'");
    sqlQuery.append(" from obs o ");
    sqlQuery.append(
            " inner join patient_identifier as id1 on (o.person_id = id1.patient_id and id1.identifier_type = :primaryIdentifierType ) ");
    sqlQuery.append(" inner join encounter as e on (o.encounter_id = e.encounter_id) ");
    sqlQuery.append(" inner join users as u on (o.creator = u.user_id) ");
    sqlQuery.append(" inner join person_name as n on (u.person_id = n.person_id and n.voided=0) ");
    sqlQuery.append(" inner join person_name as n1 on (o.person_id = n1.person_id and n1.voided=0) ");
    sqlQuery.append(" ");
    sqlQuery.append(" where o.voided = 0  ");
    sqlQuery.append(" and o.concept_id = :nonCodedConcept ");
    if (fromDate != null) {
        sqlQuery.append(" and o.date_created > :startDate ");
    }
    if (toDate != null) {
        sqlQuery.append(" and o.date_created < :endDate ");
    }
    if (userId != null) {
        sqlQuery.append(" and o.creator = :userId ");
    }
    if (StringUtils.isNotBlank(nonCoded)) {
        sqlQuery.append(" and o.value_text like '%").append(nonCoded).append("%'");
    }

    SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery.toString());
    query.setInteger("primaryIdentifierType", primaryIdentifierType.getId());
    query.setInteger("nonCodedConcept", nonCodedConcept.getId());
    if (fromDate != null) {
        query.setTimestamp("startDate", fromDate);
    }
    if (toDate != null) {
        query.setTimestamp("endDate", toDate);
    }
    if (userId != null) {
        query.setInteger("userId", userId);
    }
    List<Object[]> list = query.list();
    SimpleDataSet dataSet = new SimpleDataSet(dataSetDefinition, context);
    for (Object[] o : list) {
        DataSetRow row = new DataSetRow();
        row.addColumnValue(new DataSetColumn("nonCodedDiagnosis", "nonCodedDiagnosis", String.class), o[0]);
        row.addColumnValue(new DataSetColumn("creatorId", "creatorId", String.class), o[1]);
        row.addColumnValue(new DataSetColumn("creatorFirstName", "creatorFirstName", String.class), o[2]);
        row.addColumnValue(new DataSetColumn("creatorLastName", "creatorLastName", String.class), o[3]);
        row.addColumnValue(new DataSetColumn("dateCreated", "dateCreated", String.class), o[4]);
        row.addColumnValue(new DataSetColumn("patientId", "patientId", String.class), o[5]);
        row.addColumnValue(new DataSetColumn("patientIdentifier", "patientIdentifier", String.class), o[6]);
        row.addColumnValue(new DataSetColumn("obsId", "obsId", String.class), o[7]);
        row.addColumnValue(new DataSetColumn("visitId", "visitId", String.class), o[8]);
        row.addColumnValue(new DataSetColumn("encounterDateTime", "encounterDateTime", String.class), o[9]);
        row.addColumnValue(new DataSetColumn("patientFirstName", "patientFirstName", String.class), o[10]);
        row.addColumnValue(new DataSetColumn("patientLastName", "patientLastName", String.class), o[11]);
        dataSet.addRow(row);
    }
    return dataSet;
}

From source file:org.openmrs.module.mirebalaisreports.page.controller.NonCodedDiagnosesPageController.java

public void get(@SpringBean NonCodedDiagnosesReportManager reportManager,
        @SpringBean MirebalaisReportsProperties mrp,
        @RequestParam(required = false, value = "fromDate") Date fromDate,
        @RequestParam(required = false, value = "toDate") Date toDate, PageModel model)
        throws EvaluationException, IOException {

    if (fromDate == null) {
        fromDate = DateUtils.addDays(new Date(), -21);
    }//from w  ww.  j av  a  2  s .c o  m
    if (toDate == null) {
        toDate = new Date();
    }
    fromDate = DateUtil.getStartOfDay(fromDate);
    toDate = DateUtil.getEndOfDay(toDate);

    model.addAttribute("nonCodedRows", null);
    model.addAttribute("providers", mrp.getAllProviders());
    model.addAttribute("reportManager", reportManager);
    model.addAttribute("fromDate", null);
    model.addAttribute("toDate", null);
    model.addAttribute("nonCoded", "");
    model.addAttribute("providerId", null);
}

From source file:org.openmrs.module.mirebalaisreports.page.controller.NonCodedDiagnosesPageController.java

public void post(@SpringBean NonCodedDiagnosesReportManager reportManager,
        @SpringBean MirebalaisReportsProperties mrp,
        @SpringBean ReportDefinitionService reportDefinitionService,
        @SpringBean CoreAppsProperties coreAppsProperties,
        @RequestParam(required = false, value = "fromDate") Date fromDate,
        @RequestParam(required = false, value = "toDate") Date toDate,
        @RequestParam(required = false, value = "nonCoded") String nonCoded,
        @RequestParam(required = false, value = "provider") Provider provider, PageModel model)
        throws EvaluationException, IOException {

    if (fromDate == null) {
        fromDate = DateUtils.addDays(new Date(), -21);
    }//from   www .j  av  a  2s .c  o  m
    if (toDate == null) {
        toDate = new Date();
    }
    fromDate = DateUtil.getStartOfDay(fromDate);
    toDate = DateUtil.getEndOfDay(toDate);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("fromDate", fromDate);
    params.put("toDate", toDate);
    if (StringUtils.isBlank(nonCoded)) {
        nonCoded = "";
    }
    params.put("nonCoded", nonCoded);
    model.addAttribute("nonCoded", nonCoded);

    Integer providerId = null;
    if (provider != null) {
        params.put("provider", provider);
        providerId = provider.getId();
    } else {
        params.put("provider", null);
    }
    model.addAttribute("providerId", providerId);

    EvaluationContext context = reportManager.initializeContext(params);
    ReportDefinition reportDefinition = reportManager.constructReportDefinition();
    ReportData reportData = reportDefinitionService.evaluate(reportDefinition, context);
    model.addAttribute("nonCodedRows",
            reportData.getDataSets().get(NonCodedDiagnosesReportManager.DATA_SET_NAME));

    model.addAttribute("reportManager", reportManager);
    model.addAttribute("fromDate", fromDate);
    model.addAttribute("toDate", DateUtil.getStartOfDay(toDate));
    model.addAttribute("providers", mrp.getAllProviders());
    model.addAttribute("dashboardUrl", coreAppsProperties.getDashboardUrl());

}

From source file:org.openmrs.module.reporting.evaluation.EvaluationUtil.java

/**
 * This method will parse the passed expression and return a value based on the following
 * criteria:<br/>// w  w w.j a v a2  s . c  om
 * <ul>
 * <li>Any string that matches a passed parameter will be replaced by the value of that parameter
 * <li>If this date is followed by an expression, it will attempt to evaluate this by
 * incrementing/decrementing days/weeks/months/years as specified</li>
 * <li>Examples: Given 2 parameters:
 * <ul>
 * <li>report.startDate = java.util.Date with value of [2007-01-10]
 * <li>report.gender = "male"
 * </ul>
 * The following should result:<br/>
 * <br/>
 * <pre>
 * evaluateParameterExpression("report.startDate") -> "2007-01-10" as Date
 * <pre>
 * </ul>
 * 
 * @param expression
 * @return value for given expression, as an <code>Object</code>
 * @throws org.openmrs.module.reporting.evaluation.parameter.ParameterException
 */
public static Object evaluateParameterExpression(String expression, Map<String, Object> parameters)
        throws ParameterException {

    log.debug("evaluateParameterExpression(): " + expression);

    log.debug("Starting expression: " + expression);
    String[] paramAndFormat = expression.split(FORMAT_SEPARATOR, 2);
    Object paramValueToFormat = null;

    try {
        Matcher matcher = expressionPattern.matcher(paramAndFormat[0]);
        if (matcher.matches()) {
            String parameterName = matcher.group(1);
            paramValueToFormat = parameters.get(parameterName);
            if (paramValueToFormat == null) {
                log.debug("Looked like an expression but the parameter value is null");
            } else {
                String operations = matcher.group(2);
                Matcher opMatcher = operationPattern.matcher(operations);
                while (opMatcher.find()) {
                    String op = opMatcher.group(1);
                    String number = opMatcher.group(2);
                    String unit = opMatcher.group(3).toLowerCase();
                    if (paramValueToFormat instanceof Date) {
                        if (!op.matches("[+-]")) {
                            throw new IllegalArgumentException("Dates only support the + and - operators");
                        }
                        Integer numAsInt;
                        try {
                            numAsInt = Integer.parseInt(number);
                        } catch (NumberFormatException ex) {
                            throw new IllegalArgumentException(
                                    "Dates do not support arithmetic with floating-point values");
                        }

                        if ("-".equals(op)) {
                            numAsInt = -numAsInt;
                        }
                        if ("w".equals(unit)) {
                            unit = "d";
                            numAsInt *= 7;
                        }
                        if ("ms".equals(unit)) {
                            paramValueToFormat = DateUtils.addMilliseconds((Date) paramValueToFormat, numAsInt);
                        } else if ("s".equals(unit)) {
                            paramValueToFormat = DateUtils.addSeconds((Date) paramValueToFormat, numAsInt);
                        } else if ("h".equals(unit)) {
                            paramValueToFormat = DateUtils.addHours((Date) paramValueToFormat, numAsInt);
                        } else if ("m".equals(unit)) {
                            paramValueToFormat = DateUtils.addMonths((Date) paramValueToFormat, numAsInt);
                        } else if ("y".equals(unit)) {
                            paramValueToFormat = DateUtils.addYears((Date) paramValueToFormat, numAsInt);
                        } else if ("".equals(unit) || "d".equals(unit)) {
                            paramValueToFormat = DateUtils.addDays((Date) paramValueToFormat, numAsInt);
                        } else {
                            throw new IllegalArgumentException("Unknown unit: " + unit);
                        }
                    } else { // assume it's a number
                        if (!"".equals(unit)) {
                            throw new IllegalArgumentException("Can't specify units in a non-date expression");
                        }
                        if (paramValueToFormat instanceof Integer && number.matches("\\d+")) {
                            Integer parsed = Integer.parseInt(number);
                            if ("+".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) + parsed;
                            } else if ("-".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) - parsed;
                            } else if ("*".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) * parsed;
                            } else if ("/".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) / parsed;
                            } else {
                                throw new IllegalArgumentException("Unknown operator " + op);
                            }
                        } else {
                            // since one or both are decimal values, do double arithmetic
                            Double parsed = Double.parseDouble(number);
                            if ("+".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() + parsed;
                            } else if ("-".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() - parsed;
                            } else if ("*".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() * parsed;
                            } else if ("/".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() / parsed;
                            } else {
                                throw new IllegalArgumentException("Unknown operator " + op);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        log.debug(e.getMessage());
        throw new ParameterException("Error handling expression: " + paramAndFormat[0], e);
    }

    paramValueToFormat = ObjectUtil.nvl(paramValueToFormat, parameters.get(paramAndFormat[0]));
    if (ObjectUtil.isNull(paramValueToFormat)) {
        if (parameters.containsKey(paramAndFormat[0])) {
            return paramValueToFormat;
        } else {
            return expression;
        }
    }
    log.debug("Evaluated to: " + paramValueToFormat);

    // Attempt to format the evaluated value if appropriate
    if (paramAndFormat.length == 2) {
        paramValueToFormat = ObjectUtil.format(paramValueToFormat, paramAndFormat[1]);
    }

    return paramValueToFormat;
}

From source file:org.opentides.dao.impl.AuditLogDaoImpl.java

@Override
protected String appendClauseToExample(AuditLog example, boolean exactMatch) {
    StringBuilder append = new StringBuilder("");
    if (!StringUtil.isEmpty(append.toString())) {
        append.append(" and ");
    }/*from   w  w  w.  j a v a  2 s  .c o m*/
    append.append(" obj.message is not null ");
    //append.append(" and ");
    //append.append(" obj.message <> '' ");
    if (example.getStartDate() != null) {
        if (!StringUtil.isEmpty(append.toString())) {
            append.append(" and ");
        }
        Date startDateNoTime = DateUtil.removeTime(example.getStartDate());
        example.setStartDateForSearch(startDateNoTime);
        append.append(" obj.createDate >= :startDateForSearch ");
    }

    if (example.getEndDate() != null) {
        if (!StringUtil.isEmpty(append.toString())) {
            append.append(" and ");
        }
        Date endDateNoTime = DateUtil.removeTime(DateUtils.addDays(example.getEndDate(), 1));
        example.setEndDateForSearch(endDateNoTime);
        append.append(" obj.createDate <= :endDateForSearch ");
    }

    if (!StringUtil.isEmpty(example.getLogAction())) {
        if (!StringUtil.isEmpty(append.toString())) {
            append.append(" and ");
        }
        append.append(" obj.message like '%").append(example.getLogAction()).append("%' ");
    }
    return append.toString();
}