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.pr7.logging.CustomDailyRollingFileAppender.java

private void customCleanUp() {
    // Check to see if there are already 5 files
    File file = new File(fileName);
    Calendar cal = Calendar.getInstance();
    int maxDays = 30;
    try {//  ww w.  j  a v a2 s  .  c o  m
        maxDays = Integer.parseInt(archiveMaxDays);
    } catch (Exception e) {
        // just leave it at 30.
    }
    cal.add(Calendar.DATE, -maxDays);
    Date cutoffDate = cal.getTime();

    Date timeBackup = DateUtil.parse(DateUtil.format(new Date(), "dd/MM/yyyy ") + archiveTiming,
            "dd/MM/yyyy HH:mm:ss");

    //This make sure only backup once per day
    //System.out.println("cleanupAndRollOver checked:: cutoffDate = " + cutoffDate + ", timeBackup = " + timeBackup + ", lastBackup = " + lastBackup + ", file.getParentFile().exists() = " + file.getParentFile().exists());
    if ((lastBackup == null || timeBackup.after(lastBackup)) && timeBackup.compareTo(new Date()) <= 0
            && file.getParentFile().exists()) {
        System.out.println("cleanupAndRollOver executed:: cutoffDate = " + cutoffDate + ", timeBackup = "
                + timeBackup + ", lastBackup = " + lastBackup);

        File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));

        System.out.println("cleanupAndRollOver executed:: files size = " + files.length + ", file.getName() = "
                + file.getName());

        int nameLength = file.getName().length();
        for (int i = 0; i < files.length; i++) {
            String datePart = null;
            try {
                if (!file.getName().equals(files[i].getName())) {
                    datePart = files[i].getName().substring(nameLength);
                    Date date = sdf.parse(datePart);
                    //System.out.println("date = " + date + " vs cutoffDate " + cutoffDate);
                    if (date.before(cutoffDate)) {
                        if (archiveCompress.equalsIgnoreCase("TRUE")) {
                            zipAndDelete(files[i]);
                        } else {
                            System.out.println("delete file = " + files[i].getName());
                            files[i].delete();
                        }
                    }
                }
            } catch (Exception e) {
                //               e.printStackTrace();
                // This isn't a file we should touch (it isn't named
                // correctly)
            }
        }
        lastBackup = new Date();
    }
}

From source file:org.apache.ivory.workflow.engine.OozieWorkflowEngine.java

private void updateCoords(String cluster, String bundleId, int concurrency, Date endTime,
        Job.Status oldBundleStatus) throws IvoryException {
    if (endTime.compareTo(now()) <= 0)
        throw new IvoryException("End time " + SchemaHelper.formatDateUTC(endTime) + " can't be in the past");

    BundleJob bundle = getBundleInfo(cluster, bundleId);
    if (oldBundleStatus == null)
        oldBundleStatus = bundle.getStatus();

    suspend(cluster, bundle);//w  w  w .  j ava 2  s .c o m

    //change coords
    for (CoordinatorJob coord : bundle.getCoordinators()) {
        LOG.debug("Updating endtime of coord " + coord.getId() + " to " + SchemaHelper.formatDateUTC(endTime)
                + " on cluster " + cluster);
        Date lastActionTime = getCoordLastActionTime(coord);
        if (lastActionTime == null) { // nothing is materialized
            if (endTime.compareTo(coord.getStartTime()) <= 0)
                change(cluster, coord.getId(), concurrency, coord.getStartTime(), null);
            else
                change(cluster, coord.getId(), concurrency, endTime, null);
        } else {
            if (!endTime.after(lastActionTime)) {
                Date pauseTime = getPreviousMin(endTime);
                // set pause time which deletes future actions
                change(cluster, coord.getId(), concurrency, null, SchemaHelper.formatDateUTC(pauseTime));
            }
            change(cluster, coord.getId(), concurrency, endTime, "");
        }
    }

    if (oldBundleStatus != Job.Status.SUSPENDED && oldBundleStatus != Job.Status.PREPSUSPENDED) {
        resume(cluster, bundle);
    }
}

From source file:org.apache.ivory.workflow.engine.OozieWorkflowEngine.java

protected void sortCoordsByStartTime(List<CoordinatorJob> consideredCoords) {
    Collections.sort(consideredCoords, new Comparator<CoordinatorJob>() {
        @Override//from   w ww  .  j  a  v a  2 s . com
        public int compare(CoordinatorJob left, CoordinatorJob right) {
            Date leftStart = left.getStartTime();
            Date rightStart = right.getStartTime();
            return leftStart.compareTo(rightStart);
        }
    });
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogServiceIT.java

@Test(groups = "largeTests")
public void listMessagesWithArrivalOrder() throws Exception {

    final String ORDERING_ORGNO = "7682982461";

    // s1 will have an EARLIER arrivalTimeStamp than s2
    ShsMessageEntry s1 = messageLogService.saveMessage(make(a(ShsMessage, with(ShsMessage.label, a(ShsLabel,
            with(to, a(To, with(To.value, ORDERING_ORGNO))), with(transferType, TransferType.ASYNCH))))));

    Thread.sleep(100);/*from   w w w.  j a va2s  .c o  m*/
    ShsMessageEntry s2 = messageLogService.saveMessage(make(a(ShsMessage, with(ShsMessage.label, a(ShsLabel,
            with(to, a(To, with(To.value, ORDERING_ORGNO))), with(transferType, TransferType.ASYNCH))))));

    // s1 will have a LATER stateTimeStamp than s2
    messageLogService.messageReceived(s2);
    Thread.sleep(100);
    messageLogService.messageReceived(s1);

    // Test ASCENDING which is the default order
    MessageLogService.Filter filter = new MessageLogService.Filter();
    Iterable<ShsMessageEntry> iter = messageLogService.listMessages(ORDERING_ORGNO, filter);

    Date lastLabelDateTime = null;

    for (Iterator<ShsMessageEntry> i = iter.iterator(); i.hasNext();) {
        ShsMessageEntry item = i.next();
        Date arrivalTimeStamp = item.getArrivalTimeStamp();

        if (lastLabelDateTime != null) {
            boolean isAscending = arrivalTimeStamp.compareTo(lastLabelDateTime) >= 0;
            Assert.assertTrue(isAscending, "default sort order should be ascending");
        }

        lastLabelDateTime = arrivalTimeStamp;
    }

    // Test ASCENDING with specifically specifying sort order
    filter = new MessageLogService.Filter();
    filter.setArrivalOrder("ascending");
    iter = messageLogService.listMessages(ORDERING_ORGNO, filter);

    lastLabelDateTime = null;

    for (Iterator<ShsMessageEntry> i = iter.iterator(); i.hasNext();) {
        ShsMessageEntry item = i.next();
        Date arrivalTimeStamp = item.getArrivalTimeStamp();

        if (lastLabelDateTime != null) {
            boolean isAscending = arrivalTimeStamp.compareTo(lastLabelDateTime) >= 0;
            Assert.assertTrue(isAscending, "sort order expected to be ascending");
        }

        lastLabelDateTime = arrivalTimeStamp;
    }

    // Test DESCENDING
    filter = new MessageLogService.Filter();
    filter.setArrivalOrder("descending");
    iter = messageLogService.listMessages(ORDERING_ORGNO, filter);

    lastLabelDateTime = null;

    for (Iterator<ShsMessageEntry> i = iter.iterator(); i.hasNext();) {
        ShsMessageEntry item = i.next();
        Date arrivalTimeStamp = item.getArrivalTimeStamp();
        if (lastLabelDateTime != null) {
            boolean isAscending = arrivalTimeStamp.compareTo(lastLabelDateTime) >= 0;
            Assert.assertFalse(isAscending, "sort order expected to be descending");
        }

        lastLabelDateTime = arrivalTimeStamp;
    }
}

From source file:au.org.theark.study.web.component.subject.SearchResultListPanel.java

/**
 * Check is the parent age is to be consider for the validation.
 * //from   w w  w.j av a 2s  .co  m
 * @param parentSubject
 * @return
 */
private boolean isConsiderParentAge(SubjectVO parentSubject) {
    boolean check = false;
    Long sessionStudyId = (Long) SecurityUtils.getSubject().getSession()
            .getAttribute(au.org.theark.core.Constants.STUDY_CONTEXT_ID);
    Study study = iArkCommonService.getStudy(sessionStudyId);
    String subjectUID = (String) SecurityUtils.getSubject().getSession()
            .getAttribute(au.org.theark.core.Constants.SUBJECTUID);
    SubjectVO criteriaSubjectVo = new SubjectVO();
    criteriaSubjectVo.getLinkSubjectStudy().setStudy(study);
    criteriaSubjectVo.getLinkSubjectStudy().setSubjectUID(subjectUID);
    Collection<SubjectVO> subjects = iArkCommonService.getSubject(criteriaSubjectVo);
    SubjectVO subjectVo = subjects.iterator().next();

    Date parentDOB = parentSubject.getLinkSubjectStudy().getPerson().getDateOfBirth();
    Date subjectDOB = subjectVo.getLinkSubjectStudy().getPerson().getDateOfBirth();

    if (parentDOB != null && subjectDOB != null && parentDOB.compareTo(subjectDOB) >= 0) {
        check = true;
    }
    return check;
}

From source file:ch.algotrader.esper.EngineImpl.java

@Override
public void addTimerCallback(Date dateTime, String name, Consumer<Date> consumer) {

    // execute callback immediately if dateTime is in the past
    if (dateTime.compareTo(getCurrentTime()) < 0) {
        consumer.accept(getCurrentTime());
    } else {//from  w w w  .  j av  a 2 s .  co m
        String alias = "ON_TIMER_"
                + DateTimeUtil.formatAsGMT(dateTime.toInstant()).replace(" ", "_").replace(":", "-")
                + (name != null ? "_" + name : "");

        Calendar cal = Calendar.getInstance();
        cal.setTime(dateTime);

        Object[] params = { alias, cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.SECOND),
                cal.get(Calendar.YEAR) };

        deployStatement("prepared", "ON_TIMER", alias, params, new TimerCallback(this, alias, consumer), true);
    }
}

From source file:org.apereo.portal.io.xml.portlet.ExternalPortletDefinitionUnmarshaller.java

void unmarshallLifecycle(final Lifecycle lifecycle,
        final IPortletDefinition portletDefinition) {

    /*// w  ww  .  j av  a2s .  c o  m
     * If this is an existing portletDefinition, it may (probably does) already contain
     * lifecycle entries.  We need to remove those, because the lifecycle of a portlet after
     * import should reflect what the document says exactly.
     */
    portletDefinition.clearLifecycle();

    if (lifecycle == null) {
        /*
         * For backwards-compatibility, a complete absence of
         * lifecycle information means the portlet is published.
         */
        portletDefinition.updateLifecycleState(PortletLifecycleState.PUBLISHED, systemUser);
    } else if (lifecycle.getEntries().isEmpty()) {
        /*
         * According to the comments for 4.3, we're supposed
         * to leave the portlet in CREATED state.
         */
        portletDefinition.updateLifecycleState(PortletLifecycleState.CREATED, systemUser);
    } else {
        /*
         * Use a TreeMap because we need to be certain the the entries
         * get applied to the new portlet definition in a sane order...
         */
        Map<IPortletLifecycleEntry, IPerson> convertedEntries = new TreeMap<>();
        /*
         * Convert each LifecycleEntry (JAXB) to an IPortletLifecycleEntry (internal)
         */
        for (LifecycleEntry entry : lifecycle.getEntries()) {
            final IPerson user = StringUtils.isNotBlank(entry.getUser())
                    ? userIdentityStore.getPerson(entry.getUser(), true)
                    : systemUser; // default
            // We will support case insensitivity of entry/@name in the XML
            final PortletLifecycleState state = PortletLifecycleState.valueOf(entry.getName().toUpperCase());
            // Entries added by an upgrade transform will not have a date
            final Date date = entry.getValue().equals(useCurrentDatetimeSignal) ? new Date()
                    : entry.getValue().getTime();
            convertedEntries.put(new IPortletLifecycleEntry() {
                @Override
                public int getUserId() {
                    return user.getID();
                }

                @Override
                public PortletLifecycleState getLifecycleState() {
                    return state;
                }

                @Override
                public Date getDate() {
                    return date;
                }

                @Override
                public int compareTo(IPortletLifecycleEntry o) {
                    int rslt = date.compareTo(o.getDate());
                    if (rslt == 0) {
                        rslt = state.getOrder() - o.getLifecycleState().getOrder();
                    }
                    return rslt;
                }
            }, user);
        }
        /*
         * Apply them to the portlet definition
         */
        convertedEntries.forEach((k, v) -> {
            portletDefinition.updateLifecycleState(k.getLifecycleState(), v, k.getDate());
        });
    }
}

From source file:org.rapidandroid.activity.chart.form.FormDataBroker.java

private JSONGraphData loadMessageOverTimeHistogram() {
    Date startDateToUse = getStartDate();
    DateDisplayTypes displayType = this.getDisplayType(startDateToUse, mEndDate);

    String selectionArg = getSelectionString(displayType);

    StringBuilder rawQuery = new StringBuilder();

    rawQuery.append("select time, count(*) from  ");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());

    rawQuery.append(" join rapidandroid_message on (");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());
    rawQuery.append(".message_id = rapidandroid_message._id");
    rawQuery.append(") ");
    if (startDateToUse.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(startDateToUse)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }/* ww  w.ja  v  a2s. c o m*/

    rawQuery.append(" group by ").append(selectionArg);
    rawQuery.append("order by ").append(selectionArg).append(" ASC");

    // the X date value is column 0
    // the y value magnitude is column 1
    SQLiteDatabase db = rawDB.getReadableDatabase();
    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    return getDateQuery(displayType, cr, db);

}

From source file:org.socraticgrid.displayalert.DisplayAlertMessages.java

private boolean checkRead(AlertTicket ticket, String userId) {
    boolean value = false;
    Date recentDate = null;

    for (AlertAction alertAction : ticket.getActionHistory()) {
        if (recentDate == null || alertAction.getActionTimestamp().compareTo(recentDate) > 0) {
            recentDate = alertAction.getActionTimestamp();
        }// w  w w . j  av a2 s .c om

        // If most recent alert action is Notfication generated then
        // set return value to false
        if (recentDate.compareTo(alertAction.getActionTimestamp()) > 0) {

            if (alertAction.getMessage().equals("Notification generated")
                    && alertAction.getUserId().equals(userId)) {
                value = false;
            }

        }

        // If alert action message is not Notification generated then
        // set return value to true
        value = (!alertAction.getMessage().equals("Notification generated")
                && alertAction.getUserId().equals(userId));

        if (value) {
            break;
        }
    }

    return value;
}

From source file:de.codesourcery.planning.swing.DateAxis.java

public BoundingBox render(ITimelineCallback callback, boolean layoutOnly) {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);/*www  .j ava  2  s. c  o  m*/
    cal.set(Calendar.MILLISECOND, 0);
    Date currentDate = cal.getTime();

    final Date endDate = duration.addTo(startDate);

    BoundingBox lastLabel = null;

    final int labelSpacing = 10;

    final Graphics2D graphics = callback.getGraphics();
    final int fontHeight = graphics.getFontMetrics().getHeight();

    final double scalingFactor = getXScalingFactor(callback.getBoundingBox());
    final BoundingBox box = callback.getBoundingBox();
    double x = callback.getBoundingBox().getX();
    final int tickToLabelSpacing = 2;
    final int tickLength = fontHeight;
    final int axisHeight = fontHeight + tickLength + tickToLabelSpacing;
    final double xIncrement = Math.floor(tickDuration.toSeconds() * scalingFactor);

    final Color oldColor = graphics.getColor();
    //      
    while (currentDate.compareTo(endDate) <= 0) {
        final int currentX = (int) Math.floor(x);
        if (lastLabel == null || lastLabel.getMaxX() < x) {
            final String labelText = callback.getLabelProvider().getTimelineLabel(currentDate);
            if (!StringUtils.isBlank(labelText)) {
                final Rectangle2D stringBounds = callback.getStringBounds(labelText);

                if (!layoutOnly) {
                    graphics.setColor(Color.BLACK);
                    // draw tick
                    final Stroke oldStroke = graphics.getStroke();
                    graphics.setStroke(new BasicStroke(2.0f));
                    graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                            box.getY() + fontHeight + tickToLabelSpacing);
                    graphics.setStroke(oldStroke);

                    // draw label
                    callback.drawString(Color.BLACK, currentX, box.getY(), labelText);
                }

                final BoundingBox labelBox = new BoundingBox(currentX, box.getY(),
                        currentX + (int) stringBounds.getWidth() + labelSpacing,
                        box.getY() + (int) stringBounds.getHeight());

                if (lastLabel == null) {
                    lastLabel = labelBox;
                } else {
                    lastLabel.add(labelBox);
                }

            }
        } else {
            // draw short tick
            if (!layoutOnly) {

                final int halfTickHeight = (int) Math.floor(tickLength / 2.0d);

                graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                        box.getY() + axisHeight - halfTickHeight);
            }
        }

        // draw part of axis
        if (!layoutOnly) {
            graphics.drawLine((int) x, box.getY() + axisHeight, (int) (x + xIncrement),
                    box.getY() + axisHeight);
        }
        x += xIncrement;
        currentDate = tickDuration.addTo(currentDate);
    }

    callback.getGraphics().setColor(oldColor);
    final BoundingBox result = lastLabel != null ? lastLabel : new BoundingBox(0, 0, 0, 0);
    result.incHeight(axisHeight);
    return result;
}