Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

In this page you can find the example usage for java.util Date compareTo.

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:com.haulmont.cuba.gui.upload.FileUploading.java

@Override
public void clearTempDirectory() {
    try {/*from   www.  ja v a  2  s. c om*/
        File dir = new File(tempDir);
        File[] files = dir.listFiles();
        if (files == null)
            throw new IllegalStateException("Not a directory: " + tempDir);
        Date currentDate = timeSource.currentTimestamp();
        for (File file : files) {
            Date fileDate = new Date(file.lastModified());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(fileDate);
            calendar.add(Calendar.DAY_OF_YEAR, 2);
            if (currentDate.compareTo(calendar.getTime()) > 0) {
                deleteFileLink(file.getAbsolutePath());
                if (!file.delete()) {
                    log.warn(String.format("Could not remove temp file %s", file.getName()));
                }
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.overlord.dtgov.taskapi.TaskApi.java

/**
 * Returns true if the given task should be included in the result set based on the
 * criteria found in the request./*from w  w w .  j a  va  2 s.c  o m*/
 * @param task
 * @param findTasksRequest
 */
private boolean accepts(TaskSummary task, FindTasksRequest findTasksRequest) {
    Set<Integer> priorities = new HashSet<Integer>(findTasksRequest.getPriority());
    Set<StatusType> statuses = new HashSet<StatusType>(findTasksRequest.getStatus());
    if (!priorities.isEmpty() && !priorities.contains(task.getPriority())) {
        return false;
    }
    if (!statuses.isEmpty() && !statuses.contains(StatusType.fromValue(task.getStatus().toString()))) {
        return false;
    }

    XMLGregorianCalendar from = findTasksRequest.getDueOnFrom();
    if (from != null) {
        Date expirationTime = task.getExpirationTime();
        if (expirationTime == null) {
            return false;
        }
        if (expirationTime.compareTo(from.toGregorianCalendar().getTime()) < 0) {
            return false;
        }
    }
    XMLGregorianCalendar to = findTasksRequest.getDueOnTo();
    if (to != null) {
        Date expirationTime = task.getExpirationTime();
        if (expirationTime == null) {
            return false;
        }
        if (expirationTime.compareTo(to.toGregorianCalendar().getTime()) > 0) {
            return false;
        }
    }
    return true;
}

From source file:com.enonic.cms.itest.content.ContentServiceImpl_createContentTest.java

@Test
public void testCreateContentMaximumNameLength() {
    Date startTime = Calendar.getInstance().getTime();

    CreateContentCommand command = createCreateContentCommand(ContentStatus.DRAFT);
    command.setContentName(StringUtils.repeat("x", ContentNameValidator.CONTENT_NAME_MAX_LENGTH));

    ContentKey contentKey = contentService.createContent(command);

    ContentEntity persistedContent = contentDao.findByKey(contentKey);

    assertNotNull(persistedContent.getTimestamp());
    assertTrue(startTime.compareTo(persistedContent.getTimestamp()) <= 0);
}

From source file:org.mifos.application.meeting.business.MeetingBO.java

public boolean isValidMeetingDate(final Date meetingDate, final int occurrences) throws MeetingException {
    validateMeetingDate(meetingDate);//from   w  ww . j  a v  a  2 s  .co m
    validateOccurences(occurrences);

    DateTime currentScheduleDateTime = findNearestMatchingDate(new DateTime(this.meetingStartDate));

    Date currentScheduleDate = currentScheduleDateTime.toDate();
    Date meetingDateWOTimeStamp = DateUtils.getDateWithoutTimeStamp(meetingDate.getTime());

    for (int currentNumber = 1; currentScheduleDate.compareTo(meetingDateWOTimeStamp) < 0
            && currentNumber < occurrences; currentNumber++) {
        currentScheduleDate = findNextMatchingDate(new DateTime(currentScheduleDate)).toDate();
    }

    boolean isRepaymentIndepOfMeetingEnabled = new ConfigurationPersistence()
            .isRepaymentIndepOfMeetingEnabled();
    if (!isRepaymentIndepOfMeetingEnabled) {
        // If repayment date is dependend on meeting date, then they need to
        // match
        return currentScheduleDate.compareTo(meetingDateWOTimeStamp) == 0;
    }

    return true;
}

From source file:org.mifos.application.meeting.business.MeetingBO.java

public boolean isValidMeetingDate(final Date meetingDate, final Date endDate) throws MeetingException {
    validateMeetingDate(meetingDate);//  w  w w . java2  s  . com
    validateEndDate(endDate);
    DateTime currentScheduleDateTime = findNearestMatchingDate(new DateTime(this.meetingStartDate));

    Date currentScheduleDate = currentScheduleDateTime.toDate();
    Calendar c = Calendar.getInstance();
    c.setTime(currentScheduleDate);
    currentScheduleDate = getNextWorkingDay(c).getTime();

    Date meetingDateWOTimeStamp = DateUtils.getDateWithoutTimeStamp(meetingDate.getTime());
    Date endDateWOTimeStamp = DateUtils.getDateWithoutTimeStamp(endDate.getTime());
    if (meetingDateWOTimeStamp.compareTo(endDateWOTimeStamp) > 0) {
        return false;
    }

    while (currentScheduleDate.compareTo(meetingDateWOTimeStamp) < 0
            && currentScheduleDate.compareTo(endDateWOTimeStamp) < 0) {
        currentScheduleDate = findNextMatchingDate(new DateTime(currentScheduleDate)).toDate();
        c.setTime(currentScheduleDate);
        currentScheduleDate = getNextWorkingDay(c).getTime();
    }

    boolean isRepaymentIndepOfMeetingEnabled = new ConfigurationPersistence()
            .isRepaymentIndepOfMeetingEnabled();
    if (isRepaymentIndepOfMeetingEnabled) {
        return currentScheduleDate.compareTo(endDateWOTimeStamp) <= 0;
    }
    // If repayment date is dependend on meeting date, then they need to
    // match
    return currentScheduleDate.compareTo(endDateWOTimeStamp) <= 0
            && currentScheduleDate.compareTo(meetingDateWOTimeStamp) == 0;
}

From source file:com.qcadoo.mes.assignmentToShift.print.xls.AssignmentToShiftXlsHelper.java

private List<Entity> findCurrentAssignmentsToShiftForCrew(final Date date,
        List<Entity> assignmentsToShiftForCrew) {

    List<Entity> currentAssignments = Lists.newArrayList();
    if (assignmentsToShiftForCrew == null) {
        return currentAssignments;
    }//from   www.j av a  2s .  c o  m
    Date currentDate = date;
    for (Entity assignmentToShift : assignmentsToShiftForCrew) {
        Date assignmentDate = assignmentToShift.getDateField(AssignmentToShiftFields.START_DATE);
        if (assignmentDate.before(currentDate)) {
            if (currentAssignments.isEmpty()) {
                currentAssignments.add(assignmentToShift);
            } else {
                return currentAssignments;
            }
        } else if (assignmentDate.compareTo(currentDate) == 0) {
            currentAssignments.add(assignmentToShift);
        }
        currentDate = assignmentDate;
    }
    return currentAssignments;
}

From source file:org.openvpms.archetype.rules.finance.till.TillRulesTestCase.java

private BigDecimal checkBalance(BigDecimal initialCashFloat, BigDecimal newCashFloat, FinancialAct balance,
        String status) {//from ww w . j  av a 2 s .  c  om
    // make sure the balance is updated
    assertEquals(status, balance.getStatus());
    // end time should be > startTime < now
    Date startTime = balance.getActivityStartTime();
    Date endTime = balance.getActivityEndTime();
    if (TillBalanceStatus.CLEARED.equals(status)) {
        // CLEARED balances have an end time
        assertEquals(1, endTime.compareTo(startTime));
        assertEquals(-1, endTime.compareTo(new Date()));
    } else {
        // IN_PROGRESS balances do not
        assertNull(endTime);
    }

    BigDecimal total = newCashFloat.subtract(initialCashFloat);

    if (initialCashFloat.compareTo(newCashFloat) != 0) {
        // expect a till balance adjustment to have been made
        Set<ActRelationship> rels = balance.getSourceActRelationships();
        assertEquals(1, rels.size());
        ActRelationship r = rels.toArray(new ActRelationship[rels.size()])[0];
        Act target = (Act) get(r.getTarget());
        assertTrue(TypeHelper.isA(target, "act.tillBalanceAdjustment"));
        ActBean adjBean = new ActBean(target);
        BigDecimal amount = adjBean.getBigDecimal("amount");

        boolean credit = (newCashFloat.compareTo(initialCashFloat) < 0);
        BigDecimal adjustmentTotal = total.abs();
        assertTrue(adjustmentTotal.compareTo(amount) == 0);
        assertEquals(credit, adjBean.getBoolean("credit"));
    } else {
        // no till balance adjustment should have been generated
        assertTrue(balance.getSourceActRelationships().isEmpty());
    }

    // check the till balance.
    BigDecimal expectedBalance = total.negate();
    assertTrue(expectedBalance.compareTo(balance.getTotal()) == 0);

    // make sure the till is updated
    Party till = (Party) get(this.till.getObjectReference());
    IMObjectBean bean = new IMObjectBean(till);
    BigDecimal currentFloat = bean.getBigDecimal("tillFloat");
    Date lastCleared = bean.getDate("lastCleared");
    Date now = new Date();

    assertTrue(currentFloat.compareTo(newCashFloat) == 0);
    assertTrue(now.compareTo(lastCleared) == 1); // expect now > lastCleared
    return expectedBalance;
}

From source file:och.comp.billing.standalone.BillingSyncService.java

private List<SyncPayError> syncUserAccs(long userId, Set<ChatAccount> userAccs, Map<Long, Tariff> tariffs,
        Date curMonthStart, Date now) throws ConcurrentUpdateSqlException, Exception {

    List<SyncPayError> errors = new ArrayList<>();
    BigDecimal totalPrice = ZERO;
    Date lastMonthStart = addMonths(curMonthStart, -1);
    Date lastMonthEnd = monthEnd(lastMonthStart);

    ArrayList<ChatAccount> accsToUpdate = new ArrayList<>();
    for (ChatAccount acc : userAccs) {
        if (isNeedToPay(acc, curMonthStart)) {
            Tariff tariff = tariffs.get(acc.tariffId);
            if (tariff == null) {
                errors.add(new SyncPayError(userId, singleton(acc),
                        new IllegalStateException("can't find tariff")));
                continue;
            }/*from   ww w. j a  v  a  2 s  .c om*/

            accsToUpdate.add(acc);

            BigDecimal price = tariff.price;
            if (price.compareTo(ZERO) < 1)
                continue;

            //?  ?? -  ,  ?  
            BigDecimal accAmount;
            Date oldPayDate = acc.tariffLastPay;
            if (oldPayDate.compareTo(lastMonthStart) == 0)
                accAmount = price;
            else
                accAmount = calcForPeriod(price, oldPayDate, lastMonthEnd, ZERO);

            totalPrice = totalPrice.add(accAmount);
        }
    }

    //final amount
    BigDecimal amount = totalPrice;
    boolean hasBill = ZERO.compareTo(amount) != 0;
    BigDecimal[] updatedBalance = { null };
    BigDecimal minActiveBalance = props.getBigDecimalVal(billing_minActiveBalance);
    boolean[] accBlocked = { false };

    //update db
    doInSingleTxMode(() -> {

        boolean isBlocked = findBalance(universal, userId).accsBlocked;

        //bill
        if (!isBlocked && hasBill) {

            long payId = universal.nextSeqFor(payments);
            PaymentExt payment = createSystemBill(payId, userId, amount, now, TARIFF_MONTH_BIll,
                    collectionToStr(accsToUpdate));
            universal.update(new CreatePayment(payment));

            updatedBalance[0] = appendBalance(universal, userId, payment.amount);

            //? ? ?     
            if (updatedBalance[0].compareTo(minActiveBalance) < 0) {
                accBlocked[0] = true;
                universal.update(new UpdateUserAccsBlocked(userId, true));
            }

        }

        //update last pay dates
        if (accsToUpdate.size() > 0) {
            for (ChatAccount acc : accsToUpdate) {
                int result = universal.updateOne(new UpdateChatAccountByUid(acc.uid, acc.tariffLastPay,
                        new TariffLastPay(curMonthStart)));
                //concurrent check
                if (result == 0)
                    throw new ConcurrentUpdateSqlException("UpdateChatAccountByUid: uid=" + acc.uid);
            }
        }

    });

    //update cache
    if (updatedBalance[0] != null) {
        cache.tryPutCache(getBalanceCacheKey(userId), updatedBalance[0].toString());
    }

    //update chat servers
    if (accBlocked[0]) {
        sendAccsBlocked(props, db, cache, userId, true);
    }

    return errors;

}

From source file:org.apache.oozie.command.coord.CoordPushDependencyCheckXCommand.java

protected void onAllPushDependenciesAvailable(boolean isPullDependencyMeet) throws CommandException {
    Services.get().get(PartitionDependencyManagerService.class)
            .removeCoordActionWithDependenciesAvailable(coordAction.getId());
    if (isPullDependencyMeet) {
        Date nominalTime = coordAction.getNominalTime();
        Date currentTime = new Date();
        // The action should become READY only if current time > nominal time;
        // CoordActionInputCheckXCommand will take care of moving it to READY when it is nominal time.
        if (nominalTime.compareTo(currentTime) > 0) {
            LOG.info("[" + actionId + "]::ActionInputCheck:: nominal Time is newer than current time. Current="
                    + DateUtils.formatDateOozieTZ(currentTime) + ", nominal="
                    + DateUtils.formatDateOozieTZ(nominalTime));
        } else {/*w w  w  . ja va  2s  .c  o  m*/
            String actionXml = resolveCoordConfiguration();
            coordAction.setActionXml(actionXml);
            coordAction.setStatus(CoordinatorAction.Status.READY);
            // pass jobID to the CoordActionReadyXCommand
            queue(new CoordActionReadyXCommand(coordAction.getJobId()), 100);
        }
    } else if (isTimeout()) {
        // If it is timeout and all push dependencies are available but still some unresolved
        // missing dependencies queue CoordActionInputCheckXCommand now. Else it will have to
        // wait till RecoveryService kicks in
        queue(new CoordActionInputCheckXCommand(coordAction.getId(), coordAction.getJobId()));
    }
    coordAction.getPushInputDependencies().setDependencyMet(true);

}

From source file:org.openmrs.web.taglib.ObsTableWidget.java

public int doStartTag() {
    Locale loc = Context.getLocale();
    DateFormat df = Context.getDateFormat();
    //DateFormat.getDateInstance(DateFormat.SHORT, loc);

    // determine which concepts we care about
    List<Concept> conceptList = new ArrayList<Concept>();
    Set<Integer> conceptIds = new HashSet<Integer>();
    ConceptService cs = Context.getConceptService();
    for (StringTokenizer st = new StringTokenizer(concepts, "|"); st.hasMoreTokens();) {
        String s = st.nextToken().trim();
        log.debug("looking at " + s);
        boolean isSet = s.startsWith("set:");
        if (isSet) {
            s = s.substring(4).trim();//from   w w w.j  av  a  2s .  c  o  m
        }
        Concept c = null;
        if (s.startsWith("name:")) {
            String name = s.substring(5).trim();
            c = cs.getConceptByName(name);
        } else {
            try {
                c = cs.getConcept(Integer.valueOf(s.trim()));
            } catch (Exception ex) {
                log.error("Error during concept c getConcept", ex);
            }
        }
        if (c != null) {
            if (isSet) {
                List<Concept> inSet = cs.getConceptsByConceptSet(c);
                for (Concept con : inSet) {
                    if (!conceptIds.contains(con.getConceptId())) {
                        conceptList.add(con);
                        conceptIds.add(con.getConceptId());
                    }
                }
            } else {
                if (!conceptIds.contains(c.getConceptId())) {
                    conceptList.add(c);
                    conceptIds.add(c.getConceptId());
                }
            }
        }
        log.debug("conceptList == " + conceptList);
    }

    // organize obs of those concepts by Date and Concept
    Set<Integer> conceptsWithObs = new HashSet<Integer>();
    SortedSet<Date> dates = new TreeSet<Date>();
    Map<String, List<Obs>> groupedObs = new HashMap<String, List<Obs>>(); // key is conceptId + "." + date
    for (Obs o : observations) {
        Integer conceptId = o.getConcept().getConceptId();
        if (conceptIds.contains(conceptId)) {
            Date thisDate = o.getObsDatetime();
            // TODO: allow grouping by day/week/month/etc
            if ((fromDate != null && thisDate.compareTo(fromDate) < 0)
                    || (toDate != null && thisDate.compareTo(toDate) > 0)) {
                continue;
            }
            dates.add(thisDate);
            String key = conceptId + "." + thisDate;
            List<Obs> group = groupedObs.get(key);
            if (group == null) {
                group = new ArrayList<Obs>();
                groupedObs.put(key, group);
            }
            group.add(o);
            conceptsWithObs.add(conceptId);
        }
    }

    if (!showEmptyConcepts) {
        for (Iterator<Concept> i = conceptList.iterator(); i.hasNext();) {
            if (!conceptsWithObs.contains(i.next().getConceptId())) {
                i.remove();
            }
        }
    }

    List<Date> dateOrder = new ArrayList<Date>(dates);
    if (sortDescending) {
        Collections.reverse(dateOrder);
    }

    if (limit > 0 && limit < dateOrder.size()) {
        if (!sortDescending) {
            dateOrder = dateOrder.subList(dateOrder.size() - limit, dateOrder.size());
        } else {
            dateOrder = dateOrder.subList(0, limit);
        }
    }

    StringBuilder ret = new StringBuilder();
    ret.append("<table");
    if (id != null) {
        ret.append(" id=\"" + id + "\"");
    }
    if (cssClass != null) {
        ret.append(" class=\"" + cssClass + "\"");
    }
    ret.append(">");

    if (orientVertical) {
        if (showConceptHeader) {
            ret.append("<tr>");
            ret.append("<th></th>");
            for (Concept c : conceptList) {
                showConceptHeader(loc, ret, c);
            }
            ret.append("</tr>");
        }
        for (Date date : dateOrder) {
            ret.append("<tr>");
            if (showDateHeader) {
                ret.append("<th>" + df.format(date) + "</th>");
            }
            for (Concept c : conceptList) {
                showConcept(loc, groupedObs, ret, date, c);
            }
            ret.append("</tr>");
        }

    } else { // horizontal
        if (showDateHeader) {
            ret.append("<tr>");
            ret.append("<th></th>");
            for (Date date : dateOrder) {
                ret.append("<th>" + df.format(date) + "</th>");
            }
        }
        for (Concept c : conceptList) {
            ret.append("<tr>");
            if (showConceptHeader) {
                showConceptHeader(loc, ret, c);
            }
            for (Date date : dateOrder) {
                showConcept(loc, groupedObs, ret, date, c);
            }
            ret.append("</tr>");
        }
    }
    ret.append("</table>");

    try {
        JspWriter w = pageContext.getOut();
        w.println(ret);
    } catch (IOException ex) {
        log.error("Error while starting ObsTableWidget tag", ex);
    }
    return SKIP_BODY;
}