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.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.EncounterController1_8Test.java

@Test
public void createEncounter_shouldDefaultDatetimeToNowIfNotSpecified() throws Exception {
    Date since = new Date();
    String json = "{\"location\":\"9356400c-a5a2-4532-8f2b-2361b3446eb8\", \"encounterType\": \"61ae96f4-6afe-4351-b6f8-cd4fc383cce1\", \"patient\": \"da7f524f-27ce-4bb2-86d6-6d1d05312bd5\", \"provider\":\"ba1b19c2-3ed6-4f63-b8c0-f762dc8d7562\"}";

    Object newEncounter = deserialize(handle(newPostRequest(getURI(), json)));
    Assert.assertNotNull(newEncounter);//from   w  ww  .j  av a2s. c o m
    Date encounterDatetime = (Date) ConversionUtil
            .convert(((SimpleObject) newEncounter).get("encounterDatetime"), Date.class);
    Assert.assertTrue(encounterDatetime.compareTo(since) >= 0);
}

From source file:org.kuali.kfs.module.endow.web.struts.TransactionStatementAction.java

/**
 * Generates Transaction Statement in the PDF form
 * /*from  w w w. ja v a2  s.co  m*/
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward print(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    TransactionStatementReportService transactionStatementReportService = SpringContext
            .getBean(TransactionStatementReportService.class);

    // get all the value strings from the form
    TransactionStatementForm transactionStatementForm = (TransactionStatementForm) form;
    String kemids = transactionStatementForm.getKemid();
    String benefittingOrganziationCampuses = transactionStatementForm.getBenefittingOrganziationCampus();
    String benefittingOrganziationCharts = transactionStatementForm.getBenefittingOrganziationChart();
    String benefittingOrganziations = transactionStatementForm.getBenefittingOrganziation();
    String typeCodes = transactionStatementForm.getTypeCode();
    String purposeCodes = transactionStatementForm.getPurposeCode();
    String combineGroupCodes = transactionStatementForm.getCombineGroupCode();
    String beginningDate = transactionStatementForm.getBeginningDate();
    String endingDate = transactionStatementForm.getEndingDate();
    String endowmentOption = transactionStatementForm.getEndowmentOption();
    String listKemidsInHeader = transactionStatementForm.getListKemidsInHeader();
    String closedIndicator = transactionStatementForm.getClosedIndicator();
    String message = transactionStatementForm.getMessage();

    List<TransactionStatementReportDataHolder> transactionStatementReportDataHolders = null;

    // check to see if the ending date is greater than the beginning date
    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    try {
        java.util.Date beginDate = df.parse(beginningDate);
        java.util.Date endDate = df.parse(endingDate);

        if (beginDate.compareTo(endDate) >= 0) {
            transactionStatementForm.setMessage(ERROR_REPORT_ENDING_DATE_NOT_GREATER_THAN_BEGINNING_DATE);
            return mapping.findForward(KFSConstants.MAPPING_BASIC);
        }
    } catch (ParseException e) {
        transactionStatementForm.setMessage(e.getMessage());
        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    /*
     * Creates the report data based on the selected criteria.
     * The criteria are selected as follows.
     * 1. Kemid and the other criteria cannot be selected at the same time.
     * 2. If none of them are selected, all kemids will be selected.
     * 3. The other criteria other than kemid are "OR" combined.
     * 4. All the criteria in the text input can be multiple by the use of wild card or the separator ('&' for kemid, ',' for the others) 
     * 5. Beginning Date and Ending Date are required.
     */

    if (StringUtils.isNotBlank(beginningDate) && StringUtils.isNotBlank(endingDate)) {
        if (StringUtils.isNotBlank(kemids)) {

            if ((StringUtils.isNotBlank(benefittingOrganziationCampuses)
                    || StringUtils.isNotBlank(benefittingOrganziationCharts)
                    || StringUtils.isNotBlank(benefittingOrganziations) || StringUtils.isNotBlank(typeCodes)
                    || StringUtils.isNotBlank(purposeCodes) || StringUtils.isNotBlank(combineGroupCodes))) {

                // kemid and the other criteria cannot be selected at the same time 
                transactionStatementForm.setMessage(ERROR_REPORT_KEMID_WITH_OTHER_CRITERIA);
                return mapping.findForward(KFSConstants.MAPPING_BASIC);

            } else {
                // by kemid only
                List<String> kemidList = parseValueString(kemids, KEMID_SEPERATOR);
                transactionStatementReportDataHolders = transactionStatementReportService
                        .getTransactionStatementReportsByKemidByIds(kemidList, beginningDate, endingDate,
                                endowmentOption, closedIndicator);
            }
        } else {
            if ((StringUtils.isBlank(benefittingOrganziationCampuses)
                    && StringUtils.isBlank(benefittingOrganziationCharts)
                    && StringUtils.isBlank(benefittingOrganziations) && StringUtils.isBlank(typeCodes)
                    && StringUtils.isBlank(purposeCodes) && StringUtils.isBlank(combineGroupCodes))) {

                // for all kemids
                transactionStatementReportDataHolders = transactionStatementReportService
                        .getTransactionStatementReportForAllKemids(beginningDate, endingDate, endowmentOption,
                                closedIndicator);

            } else {
                // by other criteria
                transactionStatementReportDataHolders = transactionStatementReportService
                        .getTransactionStatementReportsByOtherCriteria(
                                parseValueString(benefittingOrganziationCampuses, OTHER_CRITERIA_SEPERATOR),
                                parseValueString(benefittingOrganziationCharts, OTHER_CRITERIA_SEPERATOR),
                                parseValueString(benefittingOrganziations, OTHER_CRITERIA_SEPERATOR),
                                parseValueString(typeCodes, OTHER_CRITERIA_SEPERATOR),
                                parseValueString(purposeCodes, OTHER_CRITERIA_SEPERATOR),
                                parseValueString(combineGroupCodes, OTHER_CRITERIA_SEPERATOR), beginningDate,
                                endingDate, endowmentOption, closedIndicator);
            }
        }
    } else {
        transactionStatementForm.setMessage(ERROR_BOTH_BEGINNING_AND_ENDING_DATE_REQUIRED);
        return mapping.findForward(KFSConstants.MAPPING_BASIC);

    }

    // See to see if you have something to print        
    if (transactionStatementReportDataHolders != null && !transactionStatementReportDataHolders.isEmpty()) {
        // prepare the header sheet data
        EndowmentReportHeaderDataHolder reportRequestHeaderDataHolder = transactionStatementReportService
                .createReportHeaderSheetData(getKemidsSelected(transactionStatementReportDataHolders),
                        parseValueString(benefittingOrganziationCampuses, OTHER_CRITERIA_SEPERATOR),
                        parseValueString(benefittingOrganziationCharts, OTHER_CRITERIA_SEPERATOR),
                        parseValueString(benefittingOrganziations, OTHER_CRITERIA_SEPERATOR),
                        parseValueString(typeCodes, OTHER_CRITERIA_SEPERATOR),
                        parseValueString(purposeCodes, OTHER_CRITERIA_SEPERATOR),
                        parseValueString(combineGroupCodes, OTHER_CRITERIA_SEPERATOR), REPORT_NAME,
                        endowmentOption, null);

        // generate the report in PDF 
        ByteArrayOutputStream pdfStream = new TransactionStatementReportPrint().printTransactionStatementReport(
                reportRequestHeaderDataHolder, transactionStatementReportDataHolders, listKemidsInHeader);
        if (pdfStream != null) {
            transactionStatementForm.setMessage("Reports Generated");
            WebUtils.saveMimeOutputStreamAsFile(response, "application/pdf", pdfStream, REPORT_FILE_NAME);
            return null;
        }
    }

    // No report was generated
    if (StringUtils.isBlank(kemids)) {
        transactionStatementForm.setMessage("Report was not generated.");
    } else {
        transactionStatementForm.setMessage("Report was not generated for " + kemids + ".");
    }

    return mapping.findForward(KFSConstants.MAPPING_BASIC);
}

From source file:edu.umn.cs.spatialHadoop.util.TemporalIndexManager.java

/**
 * Based on a certain time range, this method filters all directories and
* determines which files need to be indexed on daily, monthly and yearly
* levels. After calling this method, you need to call the daily, monthly
* and yearly getters to return paths required to be indexed.
 * @param timeRange//from  w ww  . java2s.  c  om
 * @throws IOException
 * @throws ParseException
 */
public void prepareNeededIndexes(String timeRange) throws IOException, ParseException {
    if (timeRange == null) {
        LOG.error("TimeRange is empty");
        return;
    }

    // Parse start and end dates
    final Date startDate, endDate;
    try {
        startDate = dayFormat.parse(timeRange.split("\\.\\.")[0]);
        endDate = dayFormat.parse(timeRange.split("\\.\\.")[1]);
    } catch (ArrayIndexOutOfBoundsException e) {
        LOG.error("Use the seperator two periods '..' to seperate from and to dates");
        return;
    } catch (ParseException e) {
        LOG.error("Illegal date format in " + timeRange);
        return;
    }

    // Filter all file/folder paths based on the start-end date range
    FileStatus[] matchingDirs = fileSystem.listStatus(datasetPath, new PathFilter() {
        @Override
        public boolean accept(Path p) {
            String dirName = p.getName();
            try {
                Date date = dayFormat.parse(dirName);
                return date.compareTo(startDate) >= 0 && date.compareTo(endDate) <= 0;
            } catch (ParseException e) {
                LOG.warn("Cannot parse directory name: " + dirName);
                return false;
            }
        }
    });
    if (matchingDirs.length == 0) {
        LOG.warn("No matching directories for the given input");
    }

    // Re-indexing check for each matching
    for (FileStatus matchingDir : matchingDirs) {
        String matchingDirDateString = NASADatasetUtil.extractDateStringFromFileStatus(matchingDir);
        if (existYearlyIndexes.containsKey(NASADatasetUtil.getYearFormat(matchingDirDateString))) {
            // needs to re-build year, month and year indexes
            existYearlyIndexes.put(NASADatasetUtil.getYearFormat(matchingDirDateString), true);
            existMonthlyIndexes.put(NASADatasetUtil.getMonthFormat(matchingDirDateString), true);
            existDailyIndexes.put(NASADatasetUtil.getDayFormat(matchingDirDateString), true);
        } else if (existMonthlyIndexes.containsKey(NASADatasetUtil.getMonthFormat(matchingDirDateString))) {
            // needs to re-build month and day indexes
            existMonthlyIndexes.put(NASADatasetUtil.getMonthFormat(matchingDirDateString), true);
            existDailyIndexes.put(NASADatasetUtil.getDayFormat(matchingDirDateString), true);
        } else if (existDailyIndexes.containsKey(NASADatasetUtil.getDayFormat(matchingDirDateString))) {
            // needs to re-build day index
            existDailyIndexes.put(NASADatasetUtil.getDayFormat(matchingDirDateString), true);
        } else {
            // needs to build a new index
            existDailyIndexes.put(NASADatasetUtil.getDayFormat(matchingDirDateString), true);

            int daysCountInMonth = getMatchesCountFromMap(existDailyIndexes,
                    NASADatasetUtil.getMonthFormat(matchingDirDateString));

            if (daysCountInMonth >= getNumDaysPerMonth(
                    NASADatasetUtil.extractMonthFromDate(matchingDirDateString))) {
                existMonthlyIndexes.put(NASADatasetUtil.getMonthFormat(matchingDirDateString), true);

                int monthsCountInYear = getMatchesCountFromMap(existMonthlyIndexes,
                        NASADatasetUtil.getYearFormat(matchingDirDateString));
                if (monthsCountInYear >= getNumMonthsPerYear()) {
                    existYearlyIndexes.put(NASADatasetUtil.getYearFormat(matchingDirDateString), true);
                }
            }
        }

    }
    convertNeededIndexesListIntoArrays();
}

From source file:org.egov.stms.web.controller.masters.DonationMasterController.java

@RequestMapping(value = "/donationUpdate/{id}", method = POST)
public String updateDonationValues(@ModelAttribute final DonationMaster donationMaster,
        @PathVariable final Long id, final Model model, final BindingResult errors,
        final RedirectAttributes redirectAttrs) throws ParseException {

    sewerageMasterDataValidator.validateDonationMasterUpdate(errors, donationMaster);
    if (errors.hasErrors()) {
        model.addAttribute(DONATIONMASTER, donationMaster);
        return DONATION_MASTER_UPDATE;
    }// w ww.ja  v  a  2s.c  o m
    final DonationMaster donationMstr = donationMasterService.findById(id);
    if (donationMstr != null) {
        final SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
        final String todaysdate = myFormat.format(new Date());
        final String effectiveFromDate = myFormat.format(donationMstr.getFromDate());

        final Date effectiveDate = myFormat.parse(effectiveFromDate);
        final Date currentDate = myFormat.parse(todaysdate);

        if (effectiveDate.compareTo(currentDate) < 0) {
            model.addAttribute(MESSAGE, "msg.donationrate.modification.rejected");
            return DONATION_MASTER_UPDATE;
        }
        donationMstr.setLastModifiedDate(new Date());
        final List<DonationDetailMaster> existingdonationDetailList = new ArrayList<>();
        if (donationMaster != null && !donationMaster.getDonationDetail().isEmpty())
            existingdonationDetailList.addAll(donationMstr.getDonationDetail());
        if (donationMaster != null && donationMaster.getDonationDetail() != null)
            updateDonationMaster(donationMaster, donationMstr, existingdonationDetailList);
    } else {
        model.addAttribute(MESSAGE, "msg.donationrate.notfound");
        return DONATION_MASTER_UPDATE;
    }
    redirectAttrs.addFlashAttribute(MESSAGE, "msg.donationrate.update.success");
    return REDIRECT_TO_SUCCESS_PAGE + id;
}

From source file:org.mot.common.util.DateBuilder.java

/**
 * @param dateA/*from   www  .  j av  a  2  s . c om*/
 * @param dateB
 * @return    0 if both values are the same
 *          +1 if dateA is after dateB
 *          -1 if dateA is before dateB
 */
public int compareDates(Date dateA, Date dateB) {
    return dateA.compareTo(dateB);
}

From source file:org.libreplan.web.planner.company.CompanyPlanningController.java

public Constraint checkConstraintStartDate() {
    return new Constraint() {
        @Override//from www.  j a v a2s. co  m
        public void validate(Component comp, Object value) throws WrongValueException {
            Date startDate = (Date) value;

            if ((startDate != null) && (filterFinishDate.getRawValue() != null)
                    && (startDate.compareTo((Date) filterFinishDate.getRawValue()) > 0)) {

                filterStartDate.setValue(null);
                throw new WrongValueException(comp, _("must be lower than end date"));
            }
        }
    };
}

From source file:org.libreplan.web.planner.company.CompanyPlanningController.java

/**
 * Operations to filter the tasks by multiple filters.
 *///from ww  w.  ja  v a2s .  c  om

public Constraint checkConstraintFinishDate() {
    return new Constraint() {
        @Override
        public void validate(Component comp, Object value) throws WrongValueException {
            Date finishDate = (Date) value;

            if ((finishDate != null) && (filterStartDate.getRawValue() != null)
                    && (finishDate.compareTo((Date) filterStartDate.getRawValue()) < 0)) {

                filterFinishDate.setValue(null);
                throw new WrongValueException(comp, _("must be after start date"));
            }
        }
    };
}

From source file:it.cilea.osd.jdyna.widget.WidgetDate.java

@Override
public ValidationMessage valida(Object valore) {
    if (valore == null) {
        return null;
    } else {/*from  w w  w  . j a  v  a2 s  . co m*/
        Date date = (Date) valore;
        Date max = null;
        Date min = null;
        if (minYear != null) {
            min = new GregorianCalendar(minYear, 1, 1).getTime();
        }
        if (maxYear != null) {
            max = new GregorianCalendar(maxYear + 1, 1, 1).getTime();
        }

        if (minYear != null && date.compareTo(min) == -1) {
            return new ValidationMessage("date.mustbeafter", new Object[] { min });
        }
        if (maxYear != null && date.compareTo(max) == 1) {
            return new ValidationMessage("date.mustbebefor", new Object[] { max });
        }
        return null;
    }

}

From source file:com.all.client.model.TimeComparator.java

@Override
public int compare(String o1, String o2) {
    try {/*from   w  w  w .  ja  va  2s .c om*/
        Date one = parseDate(o1);
        Date two = parseDate(o2);
        return one.compareTo(two);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }
    return 0;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.ProjectCaseDashboardServiceImpl.java

protected String getMostRecentBCRFile(String path, String bcr) {
    final List<Date> dateList = new LinkedList<Date>();
    final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-yyyy");
    if (path == null) {
        return null;
    }//from ww w .j  ava 2s . c o m
    final File file = new File(path);
    if (file.isDirectory()) {
        for (int i = 0; i < file.list().length; i++) {
            final String el = file.list()[i];
            if (el.endsWith(".json") && el.contains(bcr + "-BCR_")) {
                try {
                    dateList.add(dateFormat.parse(el.substring(el.indexOf("_") + 1, el.indexOf(".json"))));
                } catch (ParseException e) {
                    logger.info(e);
                    return null;
                }
            }
        }
        if (dateList.size() > 0) {
            Collections.sort(dateList, new Comparator<Date>() {
                public int compare(final Date o1, final Date o2) {
                    return -(o1.compareTo(o2));
                }
            });
            return bcr + "-BCR_" + dateFormat.format(dateList.get(0)) + ".json";
        } else {
            return null;
        }
    } else {
        return null;
    }
}