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:org.eclipse.winery.repository.resources.imports.xsdimports.XSDImportResource.java

@SuppressWarnings("unchecked")
public Collection<String> getAllDefinedLocalNames(short type) {
    RepositoryFileReference ref = this.getXSDFileReference();
    if (ref == null) {
        return Collections.emptySet();
    }/*  w w  w .  j  a v  a  2 s .c om*/
    Date lastUpdate = Repository.INSTANCE.getLastUpdate(ref);

    String cacheFileName = "definedLocalNames " + Integer.toString(type) + ".cache";
    RepositoryFileReference cacheRef = new RepositoryFileReference(this.id, cacheFileName);
    boolean cacheNeedsUpdate = true;
    if (Repository.INSTANCE.exists(cacheRef)) {
        Date lastUpdateCache = Repository.INSTANCE.getLastUpdate(cacheRef);
        if (lastUpdate.compareTo(lastUpdateCache) <= 0) {
            cacheNeedsUpdate = false;
        }
    }

    List<String> result;
    if (cacheNeedsUpdate) {

        XSModel model = this.getXSModel();
        if (model == null) {
            return Collections.emptySet();
        }
        XSNamedMap components = model.getComponents(type);
        //@SuppressWarnings("unchecked")
        int len = components.getLength();
        result = new ArrayList<>(len);
        for (int i = 0; i < len; i++) {
            XSObject item = components.item(i);
            // if queried for TYPE_DEFINITION, then XSD base types (such as IDREF) are also returned
            // We want to return only types defined in the namespace of this resource
            if (item.getNamespace().equals(this.id.getNamespace().getDecoded())) {
                result.add(item.getName());
            }
        }

        String cacheContent = null;
        try {
            cacheContent = Utils.mapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            XSDImportResource.LOGGER.error("Could not generate cache content", e);
        }
        try {
            Repository.INSTANCE.putContentToFile(cacheRef, cacheContent, MediaType.APPLICATION_JSON_TYPE);
        } catch (IOException e) {
            XSDImportResource.LOGGER.error("Could not update cache", e);
        }
    } else {
        // read content from cache
        // cache should contain most recent information
        try (InputStream is = Repository.INSTANCE.newInputStream(cacheRef)) {
            result = Utils.mapper.readValue(is, java.util.List.class);
        } catch (IOException e) {
            XSDImportResource.LOGGER.error("Could not read from cache", e);
            result = Collections.emptyList();
        }
    }
    return result;
}

From source file:com.w20e.socrates.process.TestRunnerImpl.java

public void testGetCreationTime() {

    Date earlier = new Date();
    RunnerImpl rnr = new RunnerImpl(null);
    Date later = new Date();
    assertTrue(earlier.compareTo(rnr.getCreationTime()) <= 0);
    assertTrue(later.compareTo(rnr.getCreationTime()) >= 0);
}

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitUtilTest.java

/**
 * Check the valid next period to start.
 *///from w  w w.  j a v  a 2s  . co  m
public void updateNextPeriodToStart() throws RSSException {
    DbeExpendControl control = new DbeExpendControl();
    DbeExpendLimitPK id = new DbeExpendLimitPK();
    id.setTxElType(ProcessingLimitService.DAY_PERIOD_TYPE);
    control.setId(id);

    Date currentDate = new Date();
    control.setDtNextPeriodStart(currentDate);
    ProcessingLimitUtilTest.logger.debug("Current date: {}", control.getDtNextPeriodStart().toString());
    utils.updateNextPeriodToStart(control);
    ProcessingLimitUtilTest.logger.debug("New date: {}", control.getDtNextPeriodStart().toString());
    Assert.assertTrue(currentDate.compareTo(control.getDtNextPeriodStart()) < 0);

    // Week
    id.setTxElType(ProcessingLimitService.WEEK_TYPE);
    control.setId(id);
    currentDate = new Date();
    control.setDtNextPeriodStart(currentDate);
    ProcessingLimitUtilTest.logger.debug("Current date: {}", control.getDtNextPeriodStart().toString());
    utils.updateNextPeriodToStart(control);
    ProcessingLimitUtilTest.logger.debug("New date: {}", control.getDtNextPeriodStart().toString());
    Assert.assertTrue(currentDate.compareTo(control.getDtNextPeriodStart()) < 0);

    // Month
    id.setTxElType(ProcessingLimitService.MONTH_PERIOD_TYPE);
    control.setId(id);
    currentDate = new Date();
    control.setDtNextPeriodStart(currentDate);
    ProcessingLimitUtilTest.logger.debug("Current date: {}", control.getDtNextPeriodStart().toString());
    utils.updateNextPeriodToStart(control);
    ProcessingLimitUtilTest.logger.debug("New date: {}", control.getDtNextPeriodStart().toString());
    Assert.assertTrue(currentDate.compareTo(control.getDtNextPeriodStart()) < 0);
}

From source file:org.dashbuilder.dataset.backend.BackendIntervalBuilderDynamicDate.java

public IntervalList build(DataSetHandler handler, ColumnGroup columnGroup) {
    IntervalDateRangeList results = new IntervalDateRangeList(columnGroup);
    DataSet dataSet = handler.getDataSet();
    List values = dataSet.getColumnById(columnGroup.getSourceId()).getValues();
    if (values.isEmpty()) {
        return results;
    }//from w ww  .j  a v  a2 s  .  c o m

    // Sort the column dates.
    DataSetSort sortOp = new DataSetSort();
    sortOp.addSortColumn(new ColumnSort(columnGroup.getSourceId(), SortOrder.ASCENDING));
    DataSetHandler sortResults = handler.sort(sortOp);
    List<Integer> sortedRows = sortResults.getRows();
    if (sortedRows == null || sortedRows.isEmpty()) {
        return results;
    }

    // Get the lower & upper limits.
    SortedList sortedValues = new SortedList(values, sortedRows);
    Date minDate = (Date) sortedValues.get(0);
    Date maxDate = (Date) sortedValues.get(sortedValues.size() - 1);

    // If min/max are equals then create a single interval.
    if (minDate.compareTo(maxDate) == 0) {
        IntervalDateRange interval = new IntervalDateRange(DAY, minDate, maxDate);
        for (int row = 0; row < sortedValues.size(); row++)
            interval.rows.add(row);
        results.add(interval);
        return results;
    }

    // Calculate the interval type used according to the constraints set.
    int maxIntervals = columnGroup.getMaxIntervals();
    if (maxIntervals < 1)
        maxIntervals = 15;
    DateIntervalType intervalType = YEAR;
    long millis = (maxDate.getTime() - minDate.getTime());
    for (DateIntervalType type : values()) {
        long nintervals = millis / getDurationInMillis(type);
        if (nintervals < maxIntervals) {
            intervalType = type;
            break;
        }
    }

    // Ensure the interval mode obtained is always greater or equals than the preferred interval size.
    DateIntervalType intervalSize = null;
    if (!StringUtils.isBlank(columnGroup.getIntervalSize())) {
        intervalSize = getByName(columnGroup.getIntervalSize());
    }
    if (intervalSize != null && compare(intervalType, intervalSize) == -1) {
        intervalType = intervalSize;
    }

    // Adjust the minDate according to the interval type.
    Calendar gc = GregorianCalendar.getInstance();
    gc.setLenient(false);
    gc.setTime(minDate);
    if (YEAR.equals(intervalType)) {
        gc.set(Calendar.MONTH, 0);
        gc.set(Calendar.DAY_OF_MONTH, 1);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (QUARTER.equals(intervalType)) {
        int currentMonth = gc.get(Calendar.MONTH);
        int firstMonthYear = columnGroup.getFirstMonthOfYear().getIndex();
        int rest = Quarter.getPositionInQuarter(firstMonthYear, currentMonth);
        gc.add(Calendar.MONTH, rest * -1);
        gc.set(Calendar.DAY_OF_MONTH, 1);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (MONTH.equals(intervalType)) {
        gc.set(Calendar.DAY_OF_MONTH, 1);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType)) {
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (HOUR.equals(intervalType)) {
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (MINUTE.equals(intervalType)) {
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (SECOND.equals(intervalType)) {
        gc.set(Calendar.MILLISECOND, 0);
    }

    // Create the intervals according to the min/max dates.
    int index = 0;
    while (gc.getTime().compareTo(maxDate) <= 0) {
        Date intervalMinDate = gc.getTime();

        // Go to the next interval
        if (MILLENIUM.equals(intervalType)) {
            gc.add(Calendar.YEAR, 1000);
        }
        if (CENTURY.equals(intervalType)) {
            gc.add(Calendar.YEAR, 100);
        }
        if (DECADE.equals(intervalType)) {
            gc.add(Calendar.YEAR, 10);
        }
        if (YEAR.equals(intervalType)) {
            gc.add(Calendar.YEAR, 1);
        }
        if (QUARTER.equals(intervalType)) {
            gc.add(Calendar.MONTH, 3);
        }
        if (MONTH.equals(intervalType)) {
            gc.add(Calendar.MONTH, 1);
        }
        if (WEEK.equals(intervalType)) {
            gc.add(Calendar.DAY_OF_MONTH, 7);
        }
        if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType)) {
            gc.add(Calendar.DAY_OF_MONTH, 1);
        }
        if (HOUR.equals(intervalType)) {
            gc.add(Calendar.HOUR_OF_DAY, 1);
        }
        if (MINUTE.equals(intervalType)) {
            gc.add(Calendar.MINUTE, 1);
        }
        if (SECOND.equals(intervalType)) {
            gc.add(Calendar.SECOND, 1);
        }

        // Create the interval.
        Date intervalMaxDate = gc.getTime();
        IntervalDateRange interval = new IntervalDateRange(intervalType, intervalMinDate, intervalMaxDate);
        results.add(interval);

        // Add the target rows to the interval.
        boolean stop = false;
        while (!stop) {
            if (index >= sortedValues.size()) {
                stop = true;
            } else {
                Date dateValue = (Date) sortedValues.get(index);
                Integer row = sortedRows.get(index);
                if (dateValue.before(intervalMaxDate)) {
                    interval.rows.add(row);
                    index++;
                } else {
                    stop = true;
                }
            }
        }
    }

    // Reverse intervals if requested
    boolean asc = columnGroup.isAscendingOrder();
    if (!asc)
        Collections.reverse(results);

    return results;
}

From source file:org.jwebsocket.watchdog.executor.TaskExecutor.java

@Override
public void run() {
    try {//from  w ww  . j  a v  a  2s .  c om
        while (true) {

            List<IWatchDogTask> lList = mTaskService.list();
            int lComparison;
            Date lDate;
            for (IWatchDogTask lTask : lList) {
                if (lTask.getType().equals("m")) {
                    //getting the frequency
                    lDate = addMinutes(lTask.getEveryNMinutes());
                } else if (lTask.getType().equals("h")) {
                    //getting the frequency
                    lDate = addHour(lTask.getEveryNHours());
                } else {
                    lDate = addDays(lTask.getEveryNDays());
                }
                lComparison = lDate.compareTo(new Date(lTask.getLastExecution()));
                if (0 >= lComparison) {
                    //Execute the task
                    mTestManager.execute(lTask);
                }
            }
            Thread.sleep(60000);
        }
    } catch (Exception ex) {
        Logger.getLogger(TaskExecutor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java

/**
 * Checks whether the object is null or not
 * /* w ww  .  j a va 2s. c om*/
 * @param validationObject
 * @param annotate
 * @return
 */
private boolean validatePast(Object validationObject, Annotation annotate) {
    if (checkNullObject(validationObject)) {
        return true;
    }

    int res = 0;

    if (validationObject.getClass().isAssignableFrom(java.util.Date.class)) {
        Date today = new Date();
        Date pastDate = (Date) validationObject;

        res = pastDate.compareTo(today);
    } else if (validationObject.getClass().isAssignableFrom(java.util.Calendar.class)) {

        Calendar cal = Calendar.getInstance();
        Calendar pastDate = (Calendar) validationObject;
        res = pastDate.compareTo(cal);

    }
    // else
    // {
    // ruleExceptionHandler(((Past) annotate).message());
    // }
    if (res >= 0) {
        throwValidationException(((Past) annotate).message());
    }

    return true;
}

From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java

/**
 * Checks whether a given date is that in future or not
 * /*  w  w  w .ja va2  s  .  com*/
 * @param validationObject
 * @param annotate
 * @return
 */
private boolean validateFuture(Object validationObject, Annotation annotate) {
    if (checkNullObject(validationObject)) {
        return true;
    }

    int res = 0;

    if (validationObject.getClass().isAssignableFrom(java.util.Date.class)) {
        Date today = new Date();
        Date futureDate = (Date) validationObject;

        res = futureDate.compareTo(today);
    } else if (validationObject.getClass().isAssignableFrom(java.util.Calendar.class)) {

        Calendar cal = Calendar.getInstance();
        Calendar futureDate = (Calendar) validationObject;
        res = futureDate.compareTo(cal);

    }
    // else
    // {
    // //ruleExceptionHandler(((Future) annotate).message());
    // throw new RuleValidationException(((Future)
    // annotate).message());
    // }
    if (res <= 0) {
        throwValidationException(((Future) annotate).message());
    }

    return true;
}

From source file:com.neusoft.mid.clwapi.service.homePage.HomePageServiceImpl.java

/**
 * ??/*from w ww  . java  2  s  .  c  om*/
 * 
 * @param token
 *            
 * @param eTag
 *            ????|???
 * @return ?
 */
@Override
public String getHomePageInfo(String token, String uptime) {
    logger.info("???");
    logger.info("[ " + uptime + " ](??|?)");

    logger.info("????");
    // ?up_time
    try {
        Map<?, ?> map = JacksonUtils.jsonToMap(uptime);
        uptime = (String) map.get(HttpConstant.UP_TIME);
    } catch (Exception e) {
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }
    logger.info("??");

    String usrId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);
    String enId = context.getHttpHeaders().getHeaderString(UserInfoKey.ENTERPRISE_ID);
    String organizationId = context.getHttpHeaders().getHeaderString(UserInfoKey.ORGANIZATION_ID);

    String alarmParName1 = null;
    String alarmParName2 = null;
    String timea = null;
    String timeb = null;

    // ?
    Date[] etag = getEtag(uptime);
    // ?
    String yesterday = TimeUtil.getSysdateYesterday();
    String now = TimeUtil.getSysdate();
    Date zeroTime = TimeUtil.getTodayZero();
    // ???
    if (etag[1] == null) {
        alarmParName1 = HttpConstant.ALARM_PARPITION + now;
        alarmParName2 = HttpConstant.ALARM_PARPITION + yesterday;
        timeb = TimeUtil.formatDateToString(etag[1], HttpConstant.TIME_FORMAT);
    } else if (zeroTime.compareTo(etag[1]) <= 0) {
        alarmParName1 = HttpConstant.ALARM_PARPITION + now;
        alarmParName2 = null;
        timea = TimeUtil.formatDateToString(etag[1], HttpConstant.TIME_FORMAT);
    } else {
        alarmParName1 = HttpConstant.ALARM_PARPITION + now;
        alarmParName2 = HttpConstant.ALARM_PARPITION + yesterday;
        timeb = TimeUtil.formatDateToString(etag[1], HttpConstant.TIME_FORMAT);
    }

    String newsNumTime = null;

    // ??
    newsNumTime = etag[0] == null ? null : TimeUtil.formatDateToString(etag[0], HttpConstant.TIME_FORMAT);

    logger.info("???time=" + newsNumTime);
    // ???
    String newsNum = homePageMapper.getNewsNum(newsNumTime);
    logger.info("????num=" + newsNum);
    logger.info("??time=" + timeb);
    // ?
    String alarmNum = homePageMapper.getAlarmNum(timea, timeb, enId, alarmParName1, alarmParName2,
            organizationId);
    logger.info("???num=" + alarmNum);
    logger.info("??");
    // ??24??
    List<String> photoList = homePageMapper.getPhotoList(usrId, organizationId);
    logger.debug("???");

    if (photoList == null || photoList.size() == 0) {
        logger.info("");
        if (photoList == null) {
            photoList = new ArrayList<String>();
        }
    } else {
        logger.info("??");
        if (logger.isDebugEnabled()) {
            Iterator<String> it = photoList.iterator();
            while (it.hasNext()) {
                logger.debug(it.next());
            }
        }
    }

    logger.info("??ID????");
    // ??ID????
    MonitorResp iMonitorResp = carMonitorService.getEpCarNums(enId, organizationId);
    logger.info("??");

    logger.info("??");
    List<String> monthList = homePageMapper.getEpReportMonth(enId);
    logger.info("??");

    logger.info("??? ");
    String epNum = homePageMapper.getEpReportNum(enId);
    logger.info("??");

    // 
    PageInfoResp iPageInfoResp = new PageInfoResp();
    iPageInfoResp.setMsgNum(newsNum);
    iPageInfoResp.setWarnNum(alarmNum);
    iPageInfoResp.setPhotoContent(photoList.size() == 0 ? null : photoList);
    iPageInfoResp.setTotal(iMonitorResp.getCarNum());
    iPageInfoResp.setRunning(iMonitorResp.getRunNum());
    iPageInfoResp.setStop(iMonitorResp.getStopNum());
    iPageInfoResp.setEpMonth(monthList.size() == 0 ? null : monthList.get(0));
    iPageInfoResp.setServerDate(now);
    iPageInfoResp.setHasReport("0".equals(epNum) ? HttpConstant.ZERO : HttpConstant.ONE);
    logger.info("????");

    return JacksonUtils.toJsonRuntimeException(iPageInfoResp);
}

From source file:com.stratelia.webactiv.util.DateUtilTest.java

@Test
public void testDatesAreEqual() {
    Date date1 = java.sql.Date.valueOf("2013-01-01");
    Date date2 = DateUtils.addHours(java.sql.Date.valueOf("2013-01-02"), 3);
    assertThat(false, is(DateUtil.datesAreEqual(date1, date2)));

    date1 = java.sql.Date.valueOf("2013-01-02");
    assertThat(false, is(date1.compareTo(date2) == 0));
    assertThat(true, is(DateUtil.datesAreEqual(date1, date2)));
}

From source file:com.inkubator.hrm.service.impl.TempAttendanceRealizationServiceImpl.java

private static List<Date> getRangeOfDates(Date firstDate, Date secondDate) {
    List<Date> result = new ArrayList<Date>();
    Calendar cal = Calendar.getInstance();
    Date left;//from   ww w  . j a  v  a  2  s . com
    Date right;

    // Compare the dates to see which is less
    if (firstDate.compareTo(secondDate) < 0) {
        left = firstDate;
        right = secondDate;
    } else {
        right = firstDate;
        left = secondDate;
    }

    cal.clear();
    cal.setTime(left); // Seed the calendar with the starting date

    for (int i = 0; left.compareTo(right) < 0; i++) {
        result.add(left); // Add the date iterator value to the result set
        cal.add(Calendar.DATE, 1); // Add one day
        left = cal.getTime(); // Update the date iterator to the new date
    }

    return result;
}