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.pentaho.metaverse.util.VfsDateRangeFilter.java

@Override
public boolean includeFile(FileSelectInfo fileInfo) {
    boolean result = super.includeFile(fileInfo);
    try {//from  w  w  w.  ja va  2s .  c o  m
        if (fileInfo.getFile().getType() == FileType.FOLDER) {

            Date folderDate = format.parse(fileInfo.getFile().getName().getBaseName());

            // assume a match on start & end dates
            int startCompare = 0;
            int endCompare = 0;

            // it is a valid date, now, is it greater than or equal to the requested date?
            if (startingDate != null) {
                startCompare = folderDate.compareTo(startingDate);
            }
            if (endingDate != null) {
                endCompare = folderDate.compareTo(endingDate);
            }

            return startCompare >= 0 && endCompare <= 0 && result;
        } else {
            return false;
        }
    } catch (ParseException | FileSystemException e) {
        // folder name is not a valid date string, reject it
        return false;
    }
}

From source file:com.github.thebigs.foscam.recorder.Recorder.java

private String[] getRecordedVideoFiles() {
    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setIncludes(new String[] { "*.mp4" });
    scanner.setBasedir(outputDir);/*  w w w.j a v  a 2  s. c  o m*/
    scanner.setCaseSensitive(false);
    scanner.scan();

    String[] mp4Files = scanner.getIncludedFiles();

    List<String> validRecordedVideoFiles = new ArrayList<String>();
    for (String mp4File : mp4Files) {
        try {
            Recording.FILE_DATE_FORMAT.parse(mp4File);
            if (mp4File.endsWith(camName + ".mp4")) {
                validRecordedVideoFiles.add(mp4File);
            }
        } catch (java.text.ParseException e) {
            // didn't match
        }
    }

    Collections.sort(validRecordedVideoFiles, new Comparator<String>() {
        @Override
        public int compare(String arg0, String arg1) {
            try {
                Date date0 = Recording.FILE_DATE_FORMAT.parse(arg0);
                Date date1 = Recording.FILE_DATE_FORMAT.parse(arg1);

                return date0.compareTo(date1);
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
            return 0;
        }
    });

    String[] recordedVideoFilesSorted = new String[validRecordedVideoFiles.size()];
    for (int i = 0; i < validRecordedVideoFiles.size(); i++) {
        recordedVideoFilesSorted[i] = validRecordedVideoFiles.get(i);
    }
    return recordedVideoFilesSorted;
}

From source file:com.amazon.notification.utils.DataManager.java

public int compareDates(String dateString1, String dateString2) {
    Date date1 = null, date2 = null;
    try {/*w ww  .  ja  v a  2 s . c  o m*/
        DateFormat format = new SimpleDateFormat("dd-M-yyyy", Locale.ENGLISH);
        date1 = format.parse(dateString1);
        date2 = format.parse(dateString2);
    } catch (Exception e) {

    }
    return date1.compareTo(date2);

}

From source file:org.esupportail.dining.web.controllers.ViewController.java

@RequestMapping("/meals")
public ModelAndView renderMealsView(@RequestParam(value = "id", required = true) int id) throws Exception {

    ModelMap model = new ModelMap();
    User user = this.authenticator.getUser();

    try {/*w  ww .j  a  va2s. c om*/

        ResultSet prefUser = this.dc
                .executeQuery("SELECT NUTRITIONCODE FROM nutritionPreferences WHERE USERNAME='"
                        + StringEscapeUtils.escapeSql(user.getLogin()) + "';");

        Set<String> nutritionPrefs = new HashSet<String>();

        while (prefUser.next()) {
            nutritionPrefs.add(prefUser.getString("NUTRITIONCODE"));
        }

        model.put("nutritionPrefs", nutritionPrefs);

    } catch (SQLException e) { /**/
    } catch (NullPointerException e) { /*
                                       * Useful is the user isn't logged
                                       * in
                                       */
    }

    try {
        Restaurant restaurant = this.cache.getCachedDining(id);
        model.put("restaurant", restaurant);
        List<Manus> menuList = new ArrayList<Manus>();
        Date dateNow = new Date();
        for (Manus m : restaurant.getMenus()) {
            Date dateMenu = new SimpleDateFormat("yyyy-MM-dd").parse(m.getDate());
            // We only send upcomings menu to the view
            if (dateMenu.compareTo(dateNow) >= 0) {
                menuList.add(m);
            }
        }
        model.put("menus", menuList);

        if (this.feed.isClosed(restaurant)) {
            model.put("restaurantClosed", true);
        }

    } catch (Exception e) {
        return new ModelAndView("error", new ModelMap("err", e.getMessage()));
    }

    try {
        ResultSet results = this.dc.executeQuery("SELECT * FROM FAVORITERESTAURANT WHERE USERNAME='"
                + StringEscapeUtils.escapeSql(user.getLogin()) + "' AND RESTAURANTID='" + id + "';");
        if (results.next()) {
            model.put("isFavorite", true);
        }
    } catch (NullPointerException e) { /*
                                       * Useful is the user isn't logged
                                       * in
                                       */
    }

    return new ModelAndView("meals", model);
}

From source file:org.overlord.security.eval.jaxrs.auth.SAMLBearerTokenLoginModule.java

/**
 * Validates that the assertion is acceptable based on configurable criteria.
 * @param assertion/*from  ww w . j  a  v a  2s  .  c om*/
 * @param request
 * @throws LoginException
 */
private boolean validateAssertion(AssertionType assertion, HttpServletRequest request) throws LoginException {
    // Possibly fail the assertion based on issuer.
    String issuer = assertion.getIssuer().getValue();
    if (!issuer.equals(expectedIssuer)) {
        throw new LoginException("Unexpected SAML Assertion Issuer: " + issuer);
    }

    // Possibly fail the assertion based on audience restriction
    String currentAudience = request.getContextPath();
    Set<String> audienceRestrictions = getAudienceRestrictions(assertion);
    if (!audienceRestrictions.contains(currentAudience)) {
        throw new LoginException(
                "SAML Assertion Audience Restrictions not valid for this context (" + currentAudience + ")");
    }

    // Possibly fail the assertion based on time.
    Date now = new Date();
    ConditionsType conditions = assertion.getConditions();
    Date notBefore = conditions.getNotBefore().toGregorianCalendar().getTime();
    Date notOnOrAfter = conditions.getNotOnOrAfter().toGregorianCalendar().getTime();
    if (now.compareTo(notBefore) == -1) {
        throw new LoginException("SAML Assertion not yet valid.");
    }
    if (now.compareTo(notOnOrAfter) >= 0) {
        throw new LoginException("SAML Assertion no longer valid.");
    }

    return true;
}

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

@Test
public void testCookieWrapperExpiryDate() throws ParseException {
    Date now = new Date();
    cookieWrapper.setName("test");
    cookieWrapper.setValue("test");
    cookieWrapper.setExpiryDate(now);//from   w  w w . j  a  v  a  2 s .c o  m

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

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

From source file:org.iwethey.forums.web.forum.ForumController.java

/**
 *  Prepare the model to show a single forum.
 *///  w w  w  . j a  v a 2s  .c  om
public ModelAndView show(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HashMap model = new HashMap();

    int forumId = RequestUtils.getIntParameter(request, "forumid", 1);
    Forum forum = forumManager.getForumById(forumId);

    boolean showAll = true;
    boolean showChildren = true;

    User user = (User) request.getAttribute(USER_ATTRIBUTE);

    Date mark = user.getShowNewPostsOnly() ? user.getForumMark(forumId) : null;

    // HTML title
    KeyedEntry title = new KeyedEntry("title.forum");
    title.addArg(forum.getDisplayName());
    model.put("title", title);

    // Navigation bar
    List navigation = new ArrayList();
    navigation.add(BoardController.createNavigationEntry(forum.getBoard()));
    navigation.add(createNavigationEntry(forum));
    model.put("navigation", navigation);

    // Command bar
    List cmd = new ArrayList();

    // Use the time from when the forum was selected.
    if (!user.isAnonymous()) {
        cmd.add(new NavigationEntry("mark.forum.read", ForumController.markReadURI(forum)));
    }

    if (user.getShowNewPostsOnly()) {
        cmd.add(new NavigationEntry("show.all.threads", UserController.toggleURI("showNewPostsOnly")));
        showAll = false;
    } else {
        cmd.add(new NavigationEntry("show.new.threads.only", UserController.toggleURI("showNewPostsOnly")));
    }

    if (user.getShowThreadsCollapsed()) {
        cmd.add(new NavigationEntry("show.threads.expanded", UserController.toggleURI("showThreadsCollapsed")));
        showChildren = false;
    } else {
        cmd.add(new NavigationEntry("show.threads.collapsed",
                UserController.toggleURI("showThreadsCollapsed")));
    }

    if (!user.isAnonymous()) {
        cmd.add(new NavigationEntry("add.topic", NewPostController.newURI(forum)));
    }

    model.put("commands", cmd);

    // PAGING
    int pageNumber = RequestUtils.getIntParameter(request, "pageNumber", 1);
    int batchSize = user.getForumBatchSize();

    List threads = forumManager.getThreadPage(forum, (batchSize * (pageNumber - 1)), batchSize,
            user.getSortByLastModified(), mark);

    int count = forumManager.getThreadCount(forum, mark).intValue();
    model.put("itemCount", new Integer(count));
    model.put("pageNumber", new Integer(pageNumber));
    model.put("pageBreak", new Integer(PAGE_BREAK));
    model.put("pagerSize", new Integer(PAGER_SIZE));

    int pageCount = count / batchSize;
    if (count % batchSize != 0) {
        pageCount++;
    }
    model.put("pageCount", new Integer(pageCount));

    if (pageCount > PAGER_SIZE) {
        int start = pageNumber - PAGE_BREAK + 2;
        start = (start < 2 ? 2 : start);
        model.put("pageBarStart", new Integer(start));

        int end = start + PAGER_SIZE - 3;
        end = (end > (pageCount - 1) ? pageCount - 1 : end);
        model.put("pageBarEnd", new Integer(end));
    } else {
        model.put("pageBarStart", new Integer(2));
        model.put("pageBarEnd", new Integer(pageCount - 1));
    }

    // Populate the children for each thread.
    boolean getChildren = !user.getShowThreadsCollapsed();
    Date latest = null;

    for (Iterator i = threads.iterator(); i.hasNext();) {
        Post p = (Post) i.next();

        Date last = p.getLastUpdated();
        if (latest == null || latest.compareTo(last) < 0) {
            latest = last;
        }

        if (getChildren) {
            postManager.getChildren(p);
        } else {
            p.setChildren(null);
        }
    }

    if (forum.getHeaderImage() != null) {
        request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/" + forum.getHeaderImage());
    }

    model.put("threads", threads);
    model.put("forum", forum);
    model.put("board", forum.getBoard());

    model.put("lastRead", user.getForumMark(forum));

    return new ModelAndView("forum/show", model);
}

From source file:org.cloudgraph.recognizer.GraphRecognizerSupport.java

private boolean evaluate(Date propertyValue, RelationalOperatorName operator, Date literalValue) {
    int comp = propertyValue.compareTo(literalValue);
    return evaluate(operator, comp);
}

From source file:com.sammyun.util.DateUtil.java

/**
 * ?  //from  ww  w.  j  a  v a 2  s  .  c  om
 * 
 * @param date
 * @param startDate
 * @param endDate
 * @return 
 */
public static Long getIntersection(Date date, Date startDate, Date endDate) {
    int days = 0;
    int maxDay = DateUtils.toCalendar(date).get(Calendar.DAY_OF_MONTH);
    int month = DateUtils.toCalendar(date).get(Calendar.MONTH) + 1;
    int startMonth = DateUtils.toCalendar(startDate).get(Calendar.MONTH) + 1;
    int endDay = DateUtils.toCalendar(endDate).get(Calendar.DAY_OF_MONTH);
    int startDay = DateUtils.toCalendar(startDate).get(Calendar.DAY_OF_MONTH);
    int currentMonth = DateUtils.toCalendar(new Date()).get(Calendar.MONTH) + 1;
    if (currentMonth == month) {
        if (date.compareTo(endDate) < 0) {
            if (startMonth < month) {
                days = days + maxDay - 1;
            } else {
                days = days + maxDay - startDay + 1;
            }
        } else {
            if (startMonth < month) {
                days = days + endDay - 1;
            } else {
                days = days + endDay - startDay;
            }
        }
    } else {
        if (date.compareTo(endDate) < 0) {
            if (startMonth < month) {
                days = days + maxDay;
            } else {
                days = days + maxDay - startDay + 1;
            }
        } else {
            if (startMonth < month) {
                days = days + endDay - 1;
            } else {
                days = days + endDay - startDay;
            }
        }
    }
    return (long) days;
}

From source file:org.kuali.rice.kns.web.struts.form.KualiTableRenderFormMetadata.java

/**
 * Sorts a list on the form according to the form metadata (sortColumName, previouslySortedColumnName)
 *
 * @param memberTableMetadata// w w w .  jav  a  2 s .  c om
 * @param items
 * @param maxRowsPerPage
 * @throws org.kuali.rice.kew.api.exception.WorkflowException
 */
public void sort(List<?> items, int maxRowsPerPage) {

    // Don't bother to sort null, empty or singleton lists
    if (items == null || items.size() <= 1)
        return;

    String columnToSortOn = getColumnToSortName();

    // Don't bother to sort if no column to sort on is provided
    if (StringUtils.isEmpty(columnToSortOn))
        return;

    String previouslySortedColumnName = getPreviouslySortedColumnName();

    // We know members isn't null or empty from the check above
    Object firstItem = items.get(0);
    // Need to decide if the comparator is for a bean property or a mapped key on the qualififer attribute set
    Comparator comparator = null;
    Comparator subComparator = new Comparator<Object>() {

        public int compare(Object o1, Object o2) {
            if (o1 == null)
                return -1;
            if (o2 == null)
                return 1;

            if (o1 instanceof java.util.Date && o2 instanceof java.util.Date) {
                Date d1 = (Date) o1;
                Date d2 = (Date) o2;
                return d1.compareTo(d2);
            }

            String s1 = o1.toString();
            String s2 = o2.toString();
            int n1 = s1.length(), n2 = s2.length();
            for (int i1 = 0, i2 = 0; i1 < n1 && i2 < n2; i1++, i2++) {
                char c1 = s1.charAt(i1);
                char c2 = s2.charAt(i2);
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }
    };
    // If the columnName is a readable bean property on the first member, then it's safe to say we need a simple bean property comparator,
    // otherwise it's a mapped property -- syntax for BeanComparator is "name" and "name(key)", respectively
    if (PropertyUtils.isReadable(firstItem, columnToSortOn))
        comparator = new BeanComparator(columnToSortOn, subComparator);
    else
        comparator = new BeanComparator(
                new StringBuilder().append("qualifierAsMap(").append(columnToSortOn).append(")").toString(),
                subComparator);

    // If the user has decided to resort by the same column that the list is currently sorted by, then assume that s/he wants to reverse the order of the sort
    if (!StringUtils.isEmpty(columnToSortOn) && !StringUtils.isEmpty(previouslySortedColumnName)
            && columnToSortOn.equals(previouslySortedColumnName)) {
        // we're already sorted on the same column that the user clicked on, so we reverse the list
        if (isSortDescending())
            comparator = Collections.reverseOrder(comparator);

        setSortDescending(!isSortDescending());
    } else {
        // Track which column we're currently sorting, so that the above logic will work on the next sort
        setPreviouslySortedColumnName(columnToSortOn);
        setSortDescending(true);
    }

    //if the user is just going between pages no need to sort
    if (getSwitchToPageNumber() == getViewedPageNumber()) {
        Collections.sort(items, comparator);
    }

    jumpToFirstPage(items.size(), maxRowsPerPage);
}