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.enonic.cms.itest.content.ContentServiceImpl_createContentTest.java

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

    CreateContentCommand command = createCreateContentCommand(ContentStatus.DRAFT);

    ContentKey contentKey = contentService.createContent(command);

    ContentEntity persistedContent = contentDao.findByKey(contentKey);

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

From source file:org.openmrs.module.facilitydata.web.controller.FacilityDataFormSchemaController.java

@RequestMapping("/module/facilitydata/cloneSchema.form")
public String cloneSchema(ModelMap map, @RequestParam(required = true) FacilityDataFormSchema schema,
        @RequestParam(required = false) Date startDate) throws Exception {

    FacilityDataService svc = Context.getService(FacilityDataService.class);

    Date maxDateEntered = svc.getMaxEnteredStartDateForSchema(schema);

    Date endDate = schema.getValidTo();
    if (endDate == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);/*w w  w .  ja  v a  2 s  .co m*/
        cal.add(Calendar.DATE, -1);
        endDate = cal.getTime();
    }

    if (maxDateEntered != null && maxDateEntered.compareTo(endDate) > 0) {
        throw new IllegalArgumentException(
                "You cannot enter a valid end date if entered values exist after this date");
    }

    schema.setValidTo(endDate);
    svc.saveFacilityDataFormSchema(schema);

    FacilityDataFormSchema newSchema = new FacilityDataFormSchema();
    newSchema.setName(schema.getName());
    newSchema.setDescription(schema.getDescription());
    newSchema.setForm(schema.getForm());
    newSchema.setValidFrom(startDate);
    for (FacilityDataFormSection section : schema.getSections()) {
        FacilityDataFormSection newSection = new FacilityDataFormSection();
        newSection.setSchema(newSchema);
        newSection.setName(section.getName());
        newSection.setDescription(section.getDescription());
        newSchema.addSection(newSection);
        for (FacilityDataFormQuestion question : section.getQuestions()) {
            FacilityDataFormQuestion newQuestion = new FacilityDataFormQuestion();
            newQuestion.setSection(newSection);
            newQuestion.setName(question.getName());
            newQuestion.setDescription(question.getDescription());
            newQuestion.setQuestion(question.getQuestion());
            newQuestion.setQuestionNumber(question.getQuestionNumber());
            newSection.getQuestions().add(newQuestion);
        }
    }
    newSchema = svc.saveFacilityDataFormSchema(newSchema);
    return String.format("redirect:schema.form?id=%s", newSchema.getId());
}

From source file:org.openvpms.web.component.im.edit.act.AbstractActEditor.java

/**
 * Invoked when the start time changes. Sets the value to end time if
 * start time > end time.// w w  w  . j  a v  a 2s .  c o  m
 */
protected void onStartTimeChanged() {
    Date start = getStartTime();
    Date end = getEndTime();
    if (start != null && end != null) {
        if (start.compareTo(end) > 0) {
            setStartTime(end, true);
        }
    }
}

From source file:architecture.ee.web.community.poll.DefaultPoll.java

/**
 * @param startDate//from w  w w .j av  a 2 s .  c  om
 *             startDate
 */
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
public void setStartDate(Date startDate) {
    if (startDate == null || this.endDate != null && startDate.compareTo(this.endDate) > 0)
        throw new IllegalArgumentException("Start date can not be null or greater than endDate.");
    this.startDate = startDate;
}

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

public int doStartTag() {
    UserContext userContext = Context.getUserContext();

    Locale loc = userContext.getLocale();
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);

    Set<Concept> addConceptList = OpenmrsUtil.conceptSetHelper(addConcept);
    Set<Concept> removeConceptList = OpenmrsUtil.conceptSetHelper(removeConcept);
    List<Concept> otherConceptList = OpenmrsUtil.conceptListHelper(otherGroupedConcepts);

    boolean doObsGroups = otherConceptList.size() > 0;

    if (onDate == null)
        onDate = new Date();

    // maps Concept to the date that became active
    Map<Concept, Obs> activeList = new HashMap<Concept, Obs>();
    for (Obs o : observations) {
        // skip observations in the future
        if (OpenmrsUtil.compare(o.getObsDatetime(), onDate) > 0)
            continue;
        Concept c = o.getConcept();/*from w  w  w.java 2 s.  c o m*/
        Concept toDo = o.getValueCoded();
        if (toDo == null)
            toDo = c;
        if (addConceptList.contains(o.getConcept())) {
            Date newActiveDate = o.getObsDatetime();
            Obs tmp = activeList.get(c);
            Date currentActiveDate = tmp == null ? null : tmp.getObsDatetime();
            if (currentActiveDate == null || newActiveDate.compareTo(currentActiveDate) < 0)
                activeList.put(toDo, o);
        } else if (removeConceptList.contains(o.getConcept())) {
            activeList.remove(toDo);
        }
    }
    List<Map.Entry<Concept, Obs>> ordered = new ArrayList<Map.Entry<Concept, Obs>>(activeList.entrySet());
    Collections.sort(ordered, new Comparator<Map.Entry<Concept, Obs>>() {

        public int compare(Map.Entry<Concept, Obs> left, Map.Entry<Concept, Obs> right) {
            return left.getValue().getObsDatetime().compareTo(right.getValue().getObsDatetime());
        }
    });

    Map<Obs, Collection<Obs>> obsGroups = new HashMap<Obs, Collection<Obs>>();
    if (doObsGroups) {
        ObsService os = Context.getObsService();
        for (Obs o : activeList.values())
            if (o.isObsGrouping())
                obsGroups.put(o, o.getGroupMembers());
    }

    StringBuilder sb = new StringBuilder();
    String before = "";
    String after = "";
    String obsGroupHeader = "";
    String beforeItem = "";
    String afterItem = "";
    String obsGroupItemSeparator = "";

    if ("ol".equals(displayStyle) || "ul".equals(displayStyle)) {
        before = "<" + displayStyle + ">";
        after = "</" + displayStyle + ">";
        beforeItem = "<li>";
        afterItem = "</li>";
        obsGroupItemSeparator = ", ";

    } else if (displayStyle.startsWith("separator:")) {
        afterItem = displayStyle.substring(displayStyle.indexOf(":") + 1);
        obsGroupItemSeparator = " ";

    } else if ("table".equals(displayStyle)) {
        before = "<table>";
        after = "</table>";
        beforeItem = "<tr><td>";
        afterItem = "</td></tr>";
        obsGroupItemSeparator = "</td><td>";
        if (doObsGroups) {
            StringBuilder s = new StringBuilder();
            s.append("<tr><th></th>");
            for (Concept c : otherConceptList) {
                ConceptName cn = c.getBestShortName(loc);
                s.append("<th><small>" + cn.getName() + "</small></th>");
            }
            s.append("</tr>");
            obsGroupHeader = s.toString();
        }

    } else {
        throw new RuntimeException("Unknown displayStyle: " + displayStyle);
    }

    if (ordered.size() > 0) {
        sb.append(before);
        sb.append(obsGroupHeader);
        for (Map.Entry<Concept, Obs> e : ordered) {
            sb.append(beforeItem);
            sb.append(e.getKey().getName(loc, false).getName());
            if (showDate)
                sb.append(" ").append(df.format(e.getValue().getObsDatetime()));
            if (doObsGroups) {
                Collection<Obs> obsGroup = obsGroups.get(e.getValue());
                for (Concept c : otherConceptList) {
                    sb.append(obsGroupItemSeparator);
                    if (obsGroup != null) {
                        for (Obs o : obsGroup) {
                            if (c.equals(o.getConcept())) {
                                sb.append(o.getValueAsString(loc));
                                break;
                            }
                        }
                    }
                }
            }
            sb.append(afterItem);
        }
        sb.append(after);
    }

    try {
        JspWriter w = pageContext.getOut();
        w.println(sb);
    } catch (IOException ex) {
        log.error("Error while writing to JSP", ex);
    }

    return SKIP_BODY;
}

From source file:com.netflix.priam.backup.IncrementalRestore.java

@Override
public void execute() throws Exception {
    String prefix = config.getRestorePrefix();
    if (Strings.isNullOrEmpty(prefix)) {
        logger.error(/*from  w w  w  .j  a  v  a2s  .  c o m*/
                "Restore prefix is not set, skipping incremental restore to avoid looping over the incremental backups. Plz check the configurations");
        return; // No point in restoring the files which was just backedup.
    }

    if (config.isRestoreClosestToken()) {
        priamServer.getId().getInstance().setToken(restoreToken.toString());
    }

    Date start = tracker.first().time;
    Iterator<AbstractBackupPath> incrementals = fs.list(prefix, start, Calendar.getInstance().getTime());
    FileUtils.createDirectory(restoreDir); // create restore dir.
    while (incrementals.hasNext()) {
        AbstractBackupPath temp = incrementals.next();
        if (tracker.contains(temp) || start.compareTo(temp.time) >= 0)
            continue; // ignore the ones which where already downloaded.
        if (temp.getType() != BackupFileType.SST)
            continue; // download SST's only.
        // skip System Keyspace, else you will run into concurrent schema issues.
        if (temp.getKeyspace().equalsIgnoreCase("System"))
            continue;
        /* Cassandra will rebuild Secondary index's after streaming is complete so we can ignore those */
        if (SECONDRY_INDEX_PATTERN.matcher(temp.fileName).matches()) // Make this use the constant from 1.1
            continue;

        // Create Directory for Individual Token respective to each incoming file
        File tokenDir = new File(restoreDir, temp.getToken());
        FileUtils.createDirectory(tokenDir);
        File keyspaceDir = config.getTargetKSName() == null ? new File(tokenDir, temp.keyspace)
                : new File(tokenDir, config.getTargetKSName());
        FileUtils.createDirectory(keyspaceDir);
        File columnFamilyDir = config.getTargetCFName() == null ? new File(keyspaceDir, temp.columnFamily)
                : new File(tokenDir, config.getTargetCFName());
        FileUtils.createDirectory(columnFamilyDir);
        logger.debug("*** Keyspace = " + keyspaceDir.getAbsolutePath() + " Column Family = "
                + columnFamilyDir.getAbsolutePath() + " File = " + temp.getRemotePath());
        if (config.getTargetKSName() != null || config.getTargetCFName() != null)
            temp.fileName = renameIncrementalRestoreFile(temp.fileName);
        download(temp, new File(columnFamilyDir, temp.fileName));
    }
    // wait for all the downloads in this batch to complete.
    waitToComplete();
    // stream the SST's in the dir
    for (File tokenDir : restoreDir.listFiles()) {
        for (File keyspaceDir : tokenDir.listFiles()) {
            for (File columnFamilyDir : keyspaceDir.listFiles()) {
                Collection<PendingFile> streamedSSTs = loader.stream(columnFamilyDir);
                addToStreamedIncrementalRestorePaths(streamedSSTs);
                if (streamedIncrementalRestorePaths.size() > 0) {
                    logger.debug("streamedIncrementalRestorePaths > 0, hence notifying observers");
                    notifyStreamedDataObservers();
                }
                // cleanup the dir which where streamed.
                loader.deleteCompleted(streamedSSTs);
            }
        }
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

@SuppressWarnings("unchecked")
public JSONObject getBackupJSON() {

    final JSONArray dateListJSON = new JSONArray();
    final File backupDir = new File("Backups");
    if (!backupDir.exists()) {
        backupDir.mkdir();/*from ww w  .  j a va 2 s . co m*/
    }
    final File[] backupFiles = backupDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return new File(dir, name).isFile() && name.endsWith("zip");
        }
    });
    final SimpleDateFormat zipFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
    final SimpleDateFormat friendlyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");

    final Map<Date, List<File>> backupByDays = new HashMap<Date, List<File>>();
    for (final File backupFile : backupFiles) {
        Date backupDate = null;
        Date backupDay = null;
        try {
            backupDate = zipFormat.parse(backupFile.getName());
            final String day = dayFormat.format(backupDate);
            backupDay = dayFormat.parse(day);
        } catch (final ParseException e) {
            LogHelper.warn("The backup file " + backupFile.getName()
                    + " is not well formed. Format should be yyyyMMdd_HHmmss.zip");
        }
        if (!backupByDays.containsKey(backupDay)) {
            backupByDays.put(backupDay, new ArrayList<File>());
        }
        backupByDays.get(backupDay).add(backupFile);
    }
    final ArrayList<Date> sortedDays = new ArrayList<Date>(backupByDays.keySet());
    Collections.sort(sortedDays, new Comparator<Date>() {
        @Override
        public int compare(final Date o1, final Date o2) {
            return o2.compareTo(o1);
        }
    });

    final double MB = 1024 * 1024;

    for (final Date day : sortedDays) {
        final String dayStr = dayFormat.format(day);
        final JSONObject dateJSON = new JSONObject();
        final JSONArray backups = new JSONArray();
        for (final File backupFile : backupByDays.get(day)) {
            final JSONObject backup = new JSONObject();
            Date backupDate = null;
            try {
                backupDate = zipFormat.parse(backupFile.getName());
            } catch (final ParseException e) {
                /**/ }
            backup.put("date", backupDate == null ? "???" : friendlyFormat.format(backupDate));
            final long byteSize = backupFile.length();
            backup.put("size", NumberFormat.getInstance().format(byteSize / MB) + " MB");
            backup.put("name", backupFile.getName());
            backups.add(backup);
        }
        dateJSON.put("day", dayStr);
        dateJSON.put("backups", backups);

        dateListJSON.add(dateJSON);
    }
    final JSONObject backupJSON = new JSONObject();
    backupJSON.put("dates", dateListJSON);

    return backupJSON;
}

From source file:org.jpos.gl.rule.CanPost.java

public void check(GLSession session, GLTransaction txn, String param, Account account, int[] entryOffsets,
        short[] layers) throws GLException {
    Journal journal = txn.getJournal();//from w w w .j  av a2  s.c o m
    Date postDate = txn.getPostDate();
    Date end = journal.getEnd();
    Date start = journal.getStart();
    Date lockDate = journal.getLockDate();

    session.checkPermission(GLPermission.POST, journal);

    if (journal.isClosed()) {
        throw new GLException("Journal '" + journal.getName() + "' is closed");
    }
    if (postDate == null)
        throw new GLException("Invalid transaction. Posting date is null");

    if (start != null && postDate.compareTo(start) < 0) {
        throw new GLException("Journal '" + journal.getName()
                + "' cannot accept transactions with a posting date less than " + start.toString());
    }
    if (end != null && postDate.compareTo(end) > 0) {
        throw new GLException("Journal '" + journal.getName()
                + "' cannot accept transactions with a post date greater than " + end.toString());
    }
    if (lockDate != null && postDate.compareTo(lockDate) <= 0) {
        throw new GLException(
                "Journal '" + journal.getName() + "' has a temporary lockDate at " + lockDate.toString());
    }
    checkEntries(txn, postDate);
}

From source file:org.eclipse.skalli.core.feed.jpa.JPAFeedServiceTest.java

@Test
public void testFindCalls() throws Exception {

    final Date testDate = new Date(1318946441120L);

    FeedPersistenceService jPAFeedPersistenceService = getFeedPersistenceService();
    FeedEntry e1 = jPAFeedPersistenceService.createEntry();
    e1.setSource("source-a");
    e1.setProjectId(testFindProjectUuid);
    e1.setTitle("t1");
    e1.setPublished(testDate);// w  ww  . j  ava  2  s.com
    updateId(e1);

    FeedEntry e2 = jPAFeedPersistenceService.createEntry();
    e2.setSource("source-a");
    e2.setProjectId(testFindProjectUuid);
    e2.setTitle("t2");
    e2.setPublished(new Date(testDate.getTime() + 1));
    updateId(e2);

    FeedEntry e3 = jPAFeedPersistenceService.createEntry();
    e3.setSource("source-a");
    e3.setProjectId(testFindProjectUuid);
    e3.setTitle("t3");
    e3.setPublished(new Date(testDate.getTime() + 2));
    updateId(e3);

    FeedEntry e4 = jPAFeedPersistenceService.createEntry();
    e4.setSource("source-b");
    e4.setProjectId(testFindProjectUuid);
    e4.setTitle("t4");
    e4.setPublished(new Date(testDate.getTime() + 3));
    updateId(e4);

    Collection<FeedEntry> entries = new ArrayList<FeedEntry>();
    entries.add(e1);
    entries.add(e2);
    entries.add(e3);
    entries.add(e4);
    jPAFeedPersistenceService.merge(entries);

    // findEntries: check that the maxResult parameter of findEnties works:
    FeedService jPAFeedService = getFeedService();
    for (int maxResults = 0; maxResults < 10; maxResults++) {
        List<Entry> foundEntries = jPAFeedService.findEntries(testFindProjectUuid, maxResults);
        assertThat(foundEntries.size(), is(Math.min(maxResults, 4)));

        if (maxResults > 0) {
            // check that the entries are ordered desc by published
            for (int i = 1; i < foundEntries.size(); i++) {
                Date date0 = foundEntries.get(i - 1).getPublished();
                Date date1 = foundEntries.get(i).getPublished();
                assertTrue("expected: " + date0.getTime() + ">" + date1.getTime(), date0.compareTo(date1) > 0);
            }
        }
    }

    // findEntries: check find with 1 source
    List<Entry> foundEntries = jPAFeedService.findEntries(testFindProjectUuid,
            Collections.singleton("source-a"), 10);
    assertThat(foundEntries.size(), is(3));
    for (Entry entry : foundEntries) {
        assertThat(entry.getSource(), is("source-a"));
    }

    // findEntries:: check find with 2 different sources
    Collection<String> sources = new ArrayList<String>();
    sources.add("source-a");
    sources.add("source-b");
    foundEntries = jPAFeedService.findEntries(testFindProjectUuid, sources, 10);
    assertThat(foundEntries.size(), is(4));
    for (Entry entry : foundEntries) {
        assertThat(entry.getSource(), isIn(sources));
    }

    // findEntries: check find with 1 sources and second one not existing
    sources = new ArrayList<String>();
    sources.add("source-a");
    sources.add("notExistingSource");
    foundEntries = jPAFeedService.findEntries(testFindProjectUuid, sources, 10);
    assertThat(foundEntries.size(), is(3));
    for (Entry entry : foundEntries) {
        assertThat(entry.getSource(), is("source-a"));
    }

    // findEntries: check find with 1 sources not persisted source
    sources = new ArrayList<String>();
    sources.add("notExistingSource");
    foundEntries = jPAFeedService.findEntries(testFindProjectUuid, sources, 10);
    assertThat(foundEntries.size(), is(0));

    // findSources
    List<String> foundSources = jPAFeedService.findSources(testFindProjectUuid);
    assertThat(foundSources.size(), is(2));
    // sources are expected to be order by there name
    assertThat(foundSources.get(0), is("source-a"));
    assertThat(foundSources.get(1), is("source-b"));
}

From source file:cz.muni.fi.airportservicelayer.services.StewardServiceImpl.java

@Override
public List<Steward> findAvailableStewards(Date fromDate, Date toDate) {
    if (fromDate == null) {
        throw new IllegalArgumentException("fromDate");
    }/*from   w  ww  . jav a2  s. c  o  m*/
    if (toDate == null) {
        throw new IllegalArgumentException("toDate");
    }
    if (fromDate.compareTo(toDate) > 0) {
        throw new IllegalArgumentException("fromDate is later than toDate");
    }
    try {
        return stewardDao.findAvailableStewards(fromDate, toDate);
    } catch (IllegalArgumentException | NullPointerException ex) {
        throw new IllegalArgumentDataException(ex);
    } catch (ValidationException ex) {
        throw new ValidationDataException(ex);
    } catch (Exception ex) {
        throw new BasicDataAccessException(ex);
    }
}