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

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

Introduction

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

Prototype

public static Date addHours(Date date, int amount) 

Source Link

Document

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

Usage

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

@Test
public void shouldCloseInactiveVisitWithStartDateIfNoEncounters() {
    Visit visit = new Visit(1);
    Date startDatetime = DateUtils.addHours(new Date(), -14);
    visit.setStartDatetime(startDatetime);

    when(mockVisitService.getVisits(null, null, null, null, null, null, null, null, null, false, false))
            .thenReturn(Collections.singletonList(visit));

    service.closeInactiveVisits();/* ww w .  ja  va2 s.  co  m*/

    assertThat(visit.getStopDatetime(), is(startDatetime));
}

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

@Test
public void shouldCloseAnyInactiveButOpenVisits() {
    Visit old1 = new Visit(1);
    old1.setStartDatetime(DateUtils.addDays(new Date(), -2));

    Encounter oldEncounter = new Encounter();
    oldEncounter.setEncounterType(checkInEncounterType);
    oldEncounter.setEncounterDatetime(DateUtils.addHours(DateUtils.addDays(new Date(), -2), 6));

    Visit old2 = new Visit(2);
    old2.setStartDatetime(DateUtils.addDays(new Date(), -2));
    old2.addEncounter(oldEncounter);//  w ww .j  a v  a 2 s  . c o m

    Visit new1 = new Visit(3);
    new1.setStartDatetime(DateUtils.addHours(new Date(), -2));

    when(mockVisitService.getVisits(anyCollection(), anyCollection(), anyCollection(), anyCollection(),
            any(Date.class), any(Date.class), any(Date.class), any(Date.class), anyMap(), anyBoolean(),
            anyBoolean())).thenReturn(Arrays.asList(old1, old2, new1));

    service.closeInactiveVisits();

    verify(mockVisitService).saveVisit(old1);
    verify(mockVisitService).saveVisit(old2);
    verify(mockVisitService, never()).saveVisit(new1);
    assertNull(new1.getStopDatetime());
    assertNotNull(old1.getStopDatetime());
    assertNotNull(old2.getStopDatetime());
}

From source file:org.openmrs.module.paperrecord.CloseStalePullRequestsTaskComponentTest.java

@Test
public void shouldClosePullRequestsOverTwelveHoursOld() {
    // some data from standard test dataset
    Person person = personService.getPerson(3);
    Location recordLocation = locationService.getLocation(1);
    Location requestLocation = locationService.getLocation(2);

    // from the custom data set
    PatientIdentifier identifier = patientService.getPatientIdentifier(2001);

    Date now = new Date();

    PaperRecord paperRecord = new PaperRecord();
    paperRecord.setPatientIdentifier(identifier);
    paperRecord.setRecordLocation(recordLocation);
    paperRecord.updateStatus(PaperRecord.Status.ACTIVE);
    paperRecordService.savePaperRecord(paperRecord);

    PaperRecordRequest beforeExpireDate = new PaperRecordRequest();
    beforeExpireDate.setPaperRecord(paperRecord);
    beforeExpireDate.setRequestLocation(requestLocation);
    beforeExpireDate.setAssignee(person);
    beforeExpireDate.updateStatus(PaperRecordRequest.Status.ASSIGNED);
    paperRecordService.savePaperRecordRequest(beforeExpireDate);

    // change the date created (which we can't do when we first persist it since it is set automatically)
    beforeExpireDate.setDateCreated(DateUtils.addHours(now, -13));
    paperRecordService.savePaperRecordRequest(beforeExpireDate);

    PaperRecordRequest afterExpireDate = new PaperRecordRequest();
    afterExpireDate.setPaperRecord(paperRecord);
    afterExpireDate.setRequestLocation(requestLocation);
    afterExpireDate.setAssignee(person);
    afterExpireDate.updateStatus(PaperRecordRequest.Status.ASSIGNED);
    paperRecordService.savePaperRecordRequest(afterExpireDate);

    // change the date created (which we can't do when we first persist it since it is set automatically)
    afterExpireDate.setDateCreated(DateUtils.addHours(now, -11));
    paperRecordService.savePaperRecordRequest(afterExpireDate);

    // sanity check
    assertThat(paperRecordService.getAssignedPaperRecordRequestsToPull().size(), is(2));

    // now test the scheduler
    CloseStalePullRequestsTask closeStalePullRequestsTask = new CloseStalePullRequestsTask();
    closeStalePullRequestsTask.initialize(new TaskDefinition());
    closeStalePullRequestsTask.execute();

    List<PaperRecordRequest> requests = paperRecordService.getAssignedPaperRecordRequestsToPull();
    assertThat(requests.size(), is(1));//from  w  ww . j a v a  2s  .  c om
    assertThat(requests.get(0), is(afterExpireDate));
}

From source file:org.openmrs.module.paperrecord.CloseStalePullRequestsTaskComponentTest.java

@Test
public void shouldClosePullRequestsBasedOnCustomExpireHours() {

    // some data from standard test dataset
    Person person = personService.getPerson(3);
    Location recordLocation = locationService.getLocation(1);
    Location requestLocation = locationService.getLocation(2);

    // from the custom data set
    PatientIdentifier identifier = patientService.getPatientIdentifier(2001);

    Date now = new Date();

    PaperRecord paperRecord = new PaperRecord();
    paperRecord.setPatientIdentifier(identifier);
    paperRecord.setRecordLocation(recordLocation);
    paperRecord.updateStatus(PaperRecord.Status.ACTIVE);
    paperRecordService.savePaperRecord(paperRecord);

    PaperRecordRequest beforeExpireDate = new PaperRecordRequest();
    beforeExpireDate.setPaperRecord(paperRecord);
    beforeExpireDate.setRequestLocation(requestLocation);
    beforeExpireDate.setAssignee(person);
    beforeExpireDate.updateStatus(PaperRecordRequest.Status.ASSIGNED);
    paperRecordService.savePaperRecordRequest(beforeExpireDate);

    // change the date created (which we can't do when we first persist it since it is set automatically)
    beforeExpireDate.setDateCreated(DateUtils.addHours(now, -8));
    paperRecordService.savePaperRecordRequest(beforeExpireDate);

    PaperRecordRequest afterExpireDate = new PaperRecordRequest();
    afterExpireDate.setPaperRecord(paperRecord);
    afterExpireDate.setRequestLocation(requestLocation);
    afterExpireDate.setAssignee(person);
    afterExpireDate.updateStatus(PaperRecordRequest.Status.ASSIGNED);
    paperRecordService.savePaperRecordRequest(afterExpireDate);

    // change the date created (which we can't do when we first persist it since it is set automatically)
    afterExpireDate.setDateCreated(DateUtils.addHours(now, -6));
    paperRecordService.savePaperRecordRequest(afterExpireDate);

    // sanity check
    assertThat(paperRecordService.getAssignedPaperRecordRequestsToPull().size(), is(2));

    // now test the scheduler
    CloseStalePullRequestsTask closeStalePullRequestsTask = new CloseStalePullRequestsTask();

    TaskDefinition taskDefinition = new TaskDefinition();
    taskDefinition.setProperty("pullRecordExpireHours", "7");
    closeStalePullRequestsTask.initialize(taskDefinition);

    closeStalePullRequestsTask.execute();

    List<PaperRecordRequest> requests = paperRecordService.getAssignedPaperRecordRequestsToPull();
    assertThat(requests.size(), is(1));/*from   ww w. java2  s  .  com*/
    assertThat(requests.get(0), is(afterExpireDate));
}

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/>/*  ww w. java  2s . com*/
 * <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.service.impl.NotificationServiceImpl.java

private Map<String, Object> buildNotification(Long userId, int timezoneDiff, String mode) {
    // Let's manually build the json
    List<Notification> notifs = null;
    long count = 0;
    notifs = this.findMostRecentPopup(userId);
    count = this.countNewPopup(userId);
    Map<String, Object> result = new HashMap<String, Object>();

    result.put("notifyCount", count);
    List<JSONNotification> notifications = new ArrayList<JSONNotification>();
    Date adjusted = DateUtils.addHours(new Date(), timezoneDiff);
    PrettyTime pt = new PrettyTime(adjusted);
    for (Notification n : notifs) {
        JSONNotification jn = new JSONNotification();
        jn.setTimeWhen(pt.format(n.getNotifyDate()));
        jn.setEntityClass(n.getEntityClass().getSimpleName());
        jn.setEntityId(n.getEntityId());
        jn.setMedium(n.getMedium());/*from   www  . j av a  2  s  .  c o  m*/
        jn.setMessage(n.getMessage());
        notifications.add(jn);
    }
    result.put("notifications", notifications);
    result.put("mode", mode);
    return result;
}

From source file:org.opentides.util.SecurityUtil.java

/**
 * Returns Now adjusted based on user's timezone
 * //from  www  .j  av  a2 s .  com
 * @return
 */
public static Date userNow() {
    Integer tzDiff = SecurityUtil.userTimeZone();
    return DateUtils.addHours(new Date(), tzDiff);
}

From source file:org.orcid.core.manager.impl.ClientDetailsManagerImpl.java

/**
 * Removes all non primary client secret keys
 * //from  ww w.  j ava 2 s .c  o m
 * @param clientId
 * */
@Override
@Transactional
public void cleanOldClientKeys() {
    LOGGER.info("Starting cron to delete non primary client keys");
    Date currentDate = new Date();
    List<ClientDetailsEntity> allClientDetails = this.getAll();
    if (allClientDetails != null && allClientDetails != null) {
        for (ClientDetailsEntity clientDetails : allClientDetails) {
            String clientId = clientDetails.getClientId();
            LOGGER.info("Deleting non primary keys for client: {}", clientId);
            Set<ClientSecretEntity> clientSecrets = clientDetails.getClientSecrets();
            for (ClientSecretEntity clientSecret : clientSecrets) {
                if (!clientSecret.isPrimary()) {
                    Date dateRevoked = clientSecret.getLastModified();
                    Date timeToDeleteMe = DateUtils.addHours(dateRevoked, 24);
                    // If the key have been revokend more than 24 hours ago
                    if (timeToDeleteMe.before(currentDate)) {
                        LOGGER.info("Deleting key for client {}", clientId);
                        clientSecretDao.removeClientSecret(clientId, clientSecret.getClientSecret());
                    }
                }
            }
        }
    }
    LOGGER.info("Cron done");
}

From source file:org.sonar.core.computation.dbcleaner.period.Filters.java

static Date getDateFromHours(Settings settings, String propertyKey) {
    int hours = settings.getInt(propertyKey);
    return DateUtils.addHours(new Date(), -hours);
}

From source file:org.sonar.plugins.dbcleaner.purges.PurgeEntities.java

public void purge(PurgeContext context) {
    int minimumPeriodInHours = PurgeUtils.getMinimumPeriodInHours(configuration);
    final Date beforeDate = DateUtils.addHours(new Date(), -minimumPeriodInHours);
    Logs.INFO.info("Deleting files data before " + beforeDate);

    Query query = getSession().createQuery("SELECT s.id FROM " + Snapshot.class.getSimpleName()
            + " s WHERE s.last=false AND scope=:scope AND s.createdAt<:date");
    query.setParameter("scope", Resource.SCOPE_ENTITY);
    query.setParameter("date", beforeDate);
    List<Integer> snapshotIds = query.getResultList();

    PurgeUtils.deleteSnapshotsData(getSession(), snapshotIds);
}