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.planetmayo.debrief.satc.model.contributions.Range1959ForecastContribution.java

@Override
protected double cumulativeScoreFor(CoreRoute route) {
    double min = this.getMinRange() == null ? 0 : this.getMinRange();
    double max = this.getMaxRange() == null ? 0 : this.getMaxRange();
    if (!isActive() || route.getType() == LegType.ALTERING || calculatedRange == null || calculatedRange < min
            || calculatedRange > max) {
        return 0;
    }/*from  ww  w  .j  a  va2 s .  c  o m*/
    double sum = 0;
    int count = 0;
    for (FrequencyMeasurement origin : measurements) {
        Date currentDate = origin.getDate();
        if (currentDate.compareTo(route.getStartTime()) >= 0
                && currentDate.compareTo(route.getEndTime()) <= 0) {
            State state = route.getStateAt(currentDate);
            // check that the route has a state at this time (since we may not
            // be generating states for all of our measurements)
            if (state != null) {
                Point location = state.getLocation();
                GeodeticCalculator calculator = GeoSupport.createCalculator();
                calculator.setStartingGeographicPoint(location.getX(), location.getY());
                calculator.setDestinationGeographicPoint(origin.getLocation().getLon(),
                        origin.getLocation().getLat());
                double distance = calculator.getOrthodromicDistance();

                double temp = distance - calculatedRange;
                // store the error
                state.setScore(this, temp * this.getWeight() / 10);

                // and prepare the cumulative score            
                sum += temp * temp;
                count++;
            }
        }
    }
    if (count == 0) {
        return 0;
    }
    double norm = Math.max(Math.abs(max - calculatedRange), Math.abs(min - calculatedRange));
    return Math.sqrt(sum / count) / norm;
}

From source file:org.inheritsource.service.common.domain.Timeline.java

public TreeMap<Date, List<TimelineItem>> getTimelineByDay() {
    TreeMap<Date, List<TimelineItem>> timelineByDay = new TreeMap<Date, List<TimelineItem>>(
            new Comparator<Date>() {
                @Override/* ww  w.  jav  a  2 s .  c o  m*/
                public int compare(Date o1, Date o2) {
                    int result = 0;
                    if (o1 == null) {
                        if (o2 == null) {
                            return 0;
                        } else {
                            result = 1;
                        }
                    } else {
                        if (o2 == null) {
                            return -1;
                        } else {
                            result = -o1.compareTo(o2);
                        }
                    }
                    return result;
                }
            });

    if (!sorted) {
        sort();
    }

    Date keyDay = null;
    List<TimelineItem> dayItems = null;
    if (items != null) {
        for (TimelineItem item : items) {
            if (item != null) {
                if (item.getTimestamp() == null) {
                    log.error("Timestamp in TimelineItem is not expected to be null: " + item);
                } else {
                    if (keyDay == null || !DateUtils.isSameDay(keyDay, item.getTimestamp())) {
                        // new day in Map => create new day in map and a new list for that day
                        keyDay = DateUtils.truncate(item.getTimestamp(), Calendar.DAY_OF_MONTH);
                        dayItems = new ArrayList<TimelineItem>();
                        timelineByDay.put(keyDay, dayItems);
                    }
                    // always add item to current day in map
                    if (dayItems != null) {
                        dayItems.add(item);
                    } else {
                        log.error("dayItems should never be null on add");
                    }
                }
            }
        }
    }

    return timelineByDay;
}

From source file:com.itd.dbmrgdao.TestTime_newscanner_backup.java

String FindInOut(String a, String b) throws ParseException {

    //        if (a == null) {
    //            return b;
    //        }//from  ww  w .j a  va  2 s .  c  o m

    SimpleDateFormat parser1 = new SimpleDateFormat("HH:mm");
    Date x = parser1.parse(a);
    Date y = parser1.parse(b);

    try {
        // The Magic happens here i only get the Time out of the Date Object
        SimpleDateFormat parser2 = new SimpleDateFormat("HH:mm");
        x = parser2.parse(parser2.format(x));
        y = parser2.parse(parser2.format(y));

    } catch (ParseException ex) {
        System.err.println(ex);
    }

    return ((x.compareTo(y) <= 0) ? "01" : "04");

}

From source file:com.surevine.alfresco.webscript.perishable.PerishableWebscript.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    final Map<String, Object> model = new HashMap<String, Object>();

    ensureScopePresent();//ww  w.ja  va 2  s .com

    ResultSet rs = null;
    try {
        final SearchParameters parameters = new SearchParameters();
        parameters.addStore(STORE_REF);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        parameters.setQuery(
                "+PATH:\"/app:company_home//*\" +ASPECT:\"md:perishable\" -ASPECT:\"md:failedToDelete\"");
        parameters.addSort("@md:perishDue", true);

        rs = _searchService.query(parameters);

        final List<NodeRef> untrimmedNodeRefs = rs.getNodeRefs();
        final List<NodeRef> nodeRefs = untrimmedNodeRefs.subList(0,
                untrimmedNodeRefs.size() > MAX_RESULTS ? MAX_RESULTS : untrimmedNodeRefs.size());

        final ArrayList<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

        final List<ItemApplicabilityVoter> voters = getVoters(
                _serviceRegistry.getAuthenticationService().getCurrentUserName());

        for (final NodeRef nodeRef : nodeRefs) {
            boolean isApplicable = false;

            ArrayList<String> explanations = new ArrayList<String>();

            for (ItemApplicabilityVoter voter : voters) {
                if (voter.isItemApplicable(nodeRef)) {
                    isApplicable = true;

                    explanations.add(voter.getApplicabilityString(nodeRef));
                }
            }

            if (!isApplicable) {
                continue;
            }

            final String perishRequestedBy = String
                    .valueOf(_nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_REQUESTED_BY));

            NodeArchivalDetails archiveDetails = _managedDeletionService.getArchivalDetails(nodeRef);

            final Map<String, Object> item = new HashMap<String, Object>();
            item.put("node", new ScriptNode(nodeRef, _serviceRegistry, _scope));
            item.put("perishRequestedByUser", _personService.getPerson(perishRequestedBy));
            item.put("perishRequestedByPresence", _presenceService.getUserPresence(perishRequestedBy, false));
            item.put("perishDue", _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_DUE));
            item.put("perishApplied",
                    _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISHED_APPLIED));
            item.put("archiveDue", archiveDetails.archivalDue());
            item.put("explanations", explanations);

            // For an unknown reason node.children[] is returning null so we get the information using
            // the longer syntax
            if (_nodeService.getType(nodeRef).equals(ForumModel.TYPE_TOPIC)) {
                List<ChildAssociationRef> postAssocRefs = _nodeService.getChildAssocs(nodeRef,
                        ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);

                if (postAssocRefs.isEmpty()) {
                    // This really shouldn't happen, but if it does, handle it cleanly
                    _logger.warn("Topic node without any posts: " + nodeRef);
                    continue;
                }

                item.put("postNode",
                        new ScriptNode(postAssocRefs.get(0).getChildRef(), _serviceRegistry, _scope));
            }

            results.add(item);
        }

        // Re-sort the results as the lucene results are sorted by perishDue
        // (which does not take into account marked for deletion)
        Collections.sort(results, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                Date archiveDue0 = (Date) arg0.get("archiveDue");
                Date archiveDue1 = (Date) arg1.get("archiveDue");

                return archiveDue0.compareTo(archiveDue1);
            }
        });

        model.put("results", results);
    } finally {
        if (rs != null)
            rs.close();
    }

    return model;
}

From source file:org.rapidandroid.activity.chart.message.MessageDataBroker.java

private JSONGraphData loadMessageTrends() {
    SQLiteDatabase db = rawDB.getReadableDatabase();

    Date startDateToUse = mStartDate;
    // if (firstDateFromForm.after(mStartDate)) {
    // // first date in the form is more recent than the start date, so just
    // go with that.
    // startDateToUse = firstDateFromForm;
    // }//from  w  w  w. j a  v  a  2 s  .  co m
    DateDisplayTypes displayType = this.getDisplayType(startDateToUse, mEndDate);

    String selectionArg = getSelectionString(displayType);

    StringBuilder rawQuery = new StringBuilder();
    rawQuery.append("select time, count(*) from rapidandroid_message ");
    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) + "' ");
    }
    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

    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    return this.getDateQuery(displayType, cr, db);
}

From source file:org.mule.transport.http.CookieWrapperTestCase.java

@Test
public void testCookieWrapperExpiryDateExpression() throws ParseException {
    Date now = new Date();
    cookieWrapper.setName("test");
    cookieWrapper.setValue("test");
    cookieWrapper.setExpiryDate("#[expiryDate]");

    when(mockExpressionManager.isExpression("#[expiryDate]")).thenReturn(true);
    when(mockExpressionManager.evaluate("#[expiryDate]", mockMuleMessage)).thenReturn(now);
    mockParse();/*w  w  w  .  ja va  2  s . c  o  m*/

    cookieWrapper.parse(mockMuleMessage, mockExpressionManager);
    Cookie cookie = cookieWrapper.createCookie();

    Date expiryDate = cookie.getExpiryDate();
    assertEquals(0, now.compareTo(expiryDate));
}

From source file:edu.usu.sdl.openstorefront.core.sort.BeanComparator.java

@Override
public int compare(T o1, T o2) {
    T obj1 = o1;//  www.  ja v a  2  s . co m
    T obj2 = o2;
    if (OpenStorefrontConstant.SORT_ASCENDING.equals(sortDirection)) {
        obj1 = o2;
        obj2 = o1;
    }

    if (obj1 != null && obj2 == null) {
        return 1;
    } else if (obj1 == null && obj2 != null) {
        return -1;
    } else if (obj1 != null && obj2 != null) {
        if (StringUtils.isNotBlank(sortField)) {
            try {
                Object o = obj1;
                Class<?> c = o.getClass();

                Field f = c.getDeclaredField(sortField);
                f.setAccessible(true);
                if (f.get(o) instanceof Date) {
                    int compare = 0;
                    DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                    if (BeanUtils.getProperty(obj1, sortField) != null
                            && BeanUtils.getProperty(obj2, sortField) == null) {
                        return 1;
                    } else if (BeanUtils.getProperty(obj1, sortField) == null
                            && BeanUtils.getProperty(obj2, sortField) != null) {
                        return -1;
                    } else if (BeanUtils.getProperty(obj1, sortField) != null
                            && BeanUtils.getProperty(obj2, sortField) != null) {
                        Date value1 = format.parse(BeanUtils.getProperty(obj1, sortField));
                        Date value2 = format.parse(BeanUtils.getProperty(obj2, sortField));
                        if (value1 != null && value2 == null) {
                            return 1;
                        } else if (value1 == null && value2 != null) {
                            return -1;
                        } else if (value1 != null && value2 != null) {

                            compare = value1.compareTo(value2);
                        }
                    }
                    return compare;
                } else {
                    try {
                        String value1 = BeanUtils.getProperty(obj1, sortField);
                        String value2 = BeanUtils.getProperty(obj2, sortField);
                        if (value1 != null && value2 == null) {
                            return 1;
                        } else if (value1 == null && value2 != null) {
                            return -1;
                        } else if (value1 != null && value2 != null) {

                            if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2)
                                    && StringUtils.isNumeric(value1) && StringUtils.isNumeric(value2)) {

                                BigDecimal numValue1 = new BigDecimal(value1);
                                BigDecimal numValue2 = new BigDecimal(value2);
                                return numValue1.compareTo(numValue2);
                            } else {
                                return value1.toLowerCase().compareTo(value2.toLowerCase());
                            }
                        }
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                        log.log(Level.FINER, MessageFormat.format("Sort field doesn''t exist: {0}", sortField));
                    }
                }
            } catch (ParseException | NoSuchFieldException | SecurityException | IllegalArgumentException
                    | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                try {
                    String value1 = BeanUtils.getProperty(obj1, sortField);
                    String value2 = BeanUtils.getProperty(obj2, sortField);
                    if (value1 != null && value2 == null) {
                        return 1;
                    } else if (value1 == null && value2 != null) {
                        return -1;
                    } else if (value1 != null && value2 != null) {

                        if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2)
                                && StringUtils.isNumeric(value1) && StringUtils.isNumeric(value2)) {

                            BigDecimal numValue1 = new BigDecimal(value1);
                            BigDecimal numValue2 = new BigDecimal(value2);
                            return numValue1.compareTo(numValue2);
                        } else {
                            return value1.toLowerCase().compareTo(value2.toLowerCase());
                        }
                    }
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex2) {
                    log.log(Level.FINER, MessageFormat.format("Sort field doesn''t exist: {0}", sortField));
                }
            }
        }
    }
    return 0;
}

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

/**
 * Check the valid next period to start.
 *//*from   w  w w.j av a2 s  .  c  o  m*/
@Test
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:jp.co.rakuten.rakutenvideoplayer.base.BaseActivity.java

/**
 * search data update last//from   w w  w  .  j  a v  a 2 s.c o m
 * @return
 */
public Hashtable<String, String> findDayUpdate() {
    String[] tableVideoKey = new String[] { "video_id", "content_id", "content_name", "url", "image_url",
            "r_enabled", "r_polling_time", "r_position", "r_updated_at", "ss_enabled", "ss_token", "nc_name",
            "nc_url", "nc_url_image" };
    ArrayList<Hashtable<String, String>> getTable = databaseSQLLiteHelper.getDataFromTable(TABLE_VIDEO,
            tableVideoKey);

    int position = 0;
    if (getTable.size() <= 0)
        return null;

    Date dateUpdate = stringToDate(getTable.get(0).get("r_updated_at"));
    for (int i = 0; i < getTable.size(); i++) {
        Date dateCheck = stringToDate(getTable.get(i).get("r_updated_at"));
        if (dateUpdate.compareTo(dateCheck) < 0) {
            dateUpdate = dateCheck;
            position = i;
        }
    }
    return getTable.get(position);

}

From source file:dk.netarkivet.harvester.datamodel.PartialHarvest.java

/**
 * Check if this harvest definition should be run, given the time now.
 *
 * @param now The current time/* w ww.  j  a v a2s.co m*/
 * @return true if harvest definition should be run
 */
public boolean runNow(Date now) {
    ArgumentNotValid.checkNotNull(now, "now");
    if (!getActive()) {
        return false; // inactive definitions are never run
    }
    return nextDate != null && now.compareTo(nextDate) >= 0;
}