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:ch.algotrader.service.PortfolioServiceImpl.java

/**
 * {@inheritDoc}/*ww w  . j  a v a2  s .  c o  m*/
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void restorePortfolioValues(final Strategy strategy, final Date fromDate, final Date toDate) {

    Validate.notNull(strategy, "Strategy is null");
    Validate.notNull(fromDate, "From date is null");
    Validate.notNull(toDate, "To date is null");

    // delete existing portfolio values;
    List<PortfolioValue> portfolioValues = this.portfolioValueDao.findByStrategyAndMinDate(strategy.getName(),
            fromDate);

    if (portfolioValues.size() > 0) {

        this.portfolioValueDao.deleteAll(portfolioValues);

        // need to flush since new portfoliovalues will be created with same date and strategy
        this.sessionFactory.getCurrentSession().flush();
    }

    // init cron
    CronSequenceGenerator cron = new CronSequenceGenerator("0 0 * * * 1-5", TimeZone.getDefault());

    // group PortfolioValues by strategyId and date
    Map<MultiKey<Long>, PortfolioValue> portfolioValueMap = new HashMap<>();

    // create portfolioValues for all cron time slots
    Date date = cron.next(DateUtils.addHours(fromDate, -1));
    while (date.compareTo(toDate) <= 0) {

        PortfolioValue portfolioValue = getPortfolioValue(strategy.getName(), date);
        if (portfolioValue.getNetLiqValueDouble() == 0) {
            date = cron.next(date);
            continue;
        } else {
            MultiKey<Long> key = new MultiKey<>(strategy.getId(), date.getTime());
            portfolioValueMap.put(key, portfolioValue);

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("processed portfolioValue for {} {}", strategy.getName(), date);
            }

            date = cron.next(date);
        }
    }

    // save values for all cashFlows
    List<Transaction> transactions = this.transactionDao.findCashflowsByStrategyAndMinDate(strategy.getName(),
            fromDate);
    for (Transaction transaction : transactions) {

        // only process performanceRelevant transactions
        if (!transaction.isPerformanceRelevant()) {
            continue;
        }

        // do not save before fromDate
        if (transaction.getDateTime().compareTo(fromDate) < 0) {
            continue;
        }

        // if there is an existing PortfolioValue, add the cashFlow
        MultiKey<Long> key = new MultiKey<>(transaction.getStrategy().getId(),
                transaction.getDateTime().getTime());
        if (portfolioValueMap.containsKey(key)) {
            PortfolioValue portfolioValue = portfolioValueMap.get(key);
            if (portfolioValue.getCashFlow() != null) {
                portfolioValue.setCashFlow(portfolioValue.getCashFlow().add(transaction.getGrossValue()));
            } else {
                portfolioValue.setCashFlow(transaction.getGrossValue());
            }
        } else {
            PortfolioValue portfolioValue = getPortfolioValue(transaction.getStrategy().getName(),
                    transaction.getDateTime());
            portfolioValue.setCashFlow(transaction.getGrossValue());
            portfolioValueMap.put(key, portfolioValue);
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("processed portfolioValue for {} {} cashflow {}", transaction.getStrategy().getName(),
                    transaction.getDateTime(), transaction.getGrossValue());
        }
    }

    // perisist the PortfolioValues
    this.portfolioValueDao.saveAll(portfolioValueMap.values());
}

From source file:org.kitodo.services.ProcessService.java

/**
 * Filter and sort after creation date list of process properties for correction and solution messages.
 *
 * @return list of ProcessProperty objects
 *///ww w . ja  v  a 2s.  co  m
public List<ProcessProperty> getSortedCorrectionSolutionMessages(Process process) {
    List<ProcessProperty> filteredList;
    List<ProcessProperty> lpe = process.getProperties();

    if (lpe.isEmpty()) {
        return new ArrayList<>();
    }

    filteredList = filterForCorrectionSolutionMessages(lpe);

    // sorting after creation date
    Collections.sort(filteredList, new Comparator<ProcessProperty>() {
        @Override
        public int compare(ProcessProperty o1, ProcessProperty o2) {
            Date o1Date = o1.getCreationDate();
            Date o2Date = o2.getCreationDate();
            if (o1Date == null) {
                o1Date = new Date();
            }
            if (o2Date == null) {
                o2Date = new Date();
            }
            return o1Date.compareTo(o2Date);
        }
    });

    return new ArrayList<>(filteredList);
}

From source file:com.jeans.iservlet.action.asset.AssetAction.java

/**
 * ?/*from w w w.  ja v a 2s.c  o m*/
 * 
 * @return
 * @throws Exception
 */
@Action(value = "load-assets", results = { @Result(type = "json", params = { "root", "data" }) })
public String loadAssets() throws Exception {
    long[] total = new long[1];
    List<Asset> assets = assetService.loadAssets(getCurrentCompany(), type, page, rows, total);
    List<AssetItem> assetItemsList = new ArrayList<AssetItem>();
    for (Asset asset : assets) {
        if (asset instanceof Hardware) {
            assetItemsList.add(HardwareItem.createInstance((Hardware) asset));
        } else if (asset instanceof Software) {
            assetItemsList.add(SoftwareItem.createInstance((Software) asset));
        }
    }
    data = new DataGrid<AssetItem>(total[0], assetItemsList);
    if (null != sort && data.getRows().size() > 0) {
        Collections.sort(data.getRows(), new Comparator<AssetItem>() {

            @Override
            public int compare(AssetItem o1, AssetItem o2) {
                int ret = 0;
                boolean asc = "asc".equals(order);
                boolean isHardware = o1 instanceof HardwareItem;
                switch (sort) {
                case "code":
                    ret = compString(((HardwareItem) o1).getCode(), ((HardwareItem) o2).getCode(), asc);
                    break;
                case "financialCode":
                    ret = compString(((HardwareItem) o1).getFinancialCode(),
                            ((HardwareItem) o2).getFinancialCode(), asc);
                    break;
                case "name":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getName(), ((HardwareItem) o2).getName(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getName(), ((SoftwareItem) o2).getName(), asc);
                    }
                    break;
                case "vendor":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getVendor(), ((HardwareItem) o2).getVendor(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getVendor(), ((SoftwareItem) o2).getVendor(), asc);
                    }
                    break;
                case "modelOrVersion":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getModelOrVersion(), ((HardwareItem) o2).getName(),
                                asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getModelOrVersion(),
                                ((SoftwareItem) o2).getModelOrVersion(), asc);
                    }
                    break;
                case "sn":
                    ret = compString(((HardwareItem) o1).getSn(), ((HardwareItem) o2).getSn(), asc);
                    break;
                case "purchaseTime":
                    Date t1 = isHardware ? ((HardwareItem) o1).getPurchaseTime()
                            : ((SoftwareItem) o1).getPurchaseTime();
                    Date t2 = isHardware ? ((HardwareItem) o2).getPurchaseTime()
                            : ((SoftwareItem) o2).getPurchaseTime();
                    if (null == t1) {
                        if (null == t2) {
                            ret = 0;
                        } else {
                            ret = asc ? -1 : 1;
                        }
                    } else {
                        if (null == t2) {
                            ret = asc ? 1 : -1;
                        } else {
                            ret = asc ? t1.compareTo(t2) : t2.compareTo(t1);
                        }
                    }
                    break;
                case "quantity":
                    if (isHardware) {
                        ret = asc
                                ? Integer.compare(((HardwareItem) o1).getQuantity(),
                                        ((HardwareItem) o2).getQuantity())
                                : Integer.compare(((HardwareItem) o2).getQuantity(),
                                        ((HardwareItem) o1).getQuantity());
                    } else {
                        ret = asc
                                ? Integer.compare(((SoftwareItem) o1).getQuantity(),
                                        ((SoftwareItem) o2).getQuantity())
                                : Integer.compare(((SoftwareItem) o2).getQuantity(),
                                        ((SoftwareItem) o1).getQuantity());
                    }
                    break;
                case "cost":
                    BigDecimal d1 = isHardware ? ((HardwareItem) o1).getCost() : ((SoftwareItem) o1).getCost();
                    BigDecimal d2 = isHardware ? ((HardwareItem) o2).getCost() : ((SoftwareItem) o2).getCost();
                    if (null == d1) {
                        d1 = new BigDecimal(0.0);
                    }
                    if (null == d2) {
                        d2 = new BigDecimal(0.0);
                    }
                    ret = asc ? d1.compareTo(d2) : d2.compareTo(d1);
                    break;
                case "state":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getState(), ((HardwareItem) o2).getState(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getState(), ((SoftwareItem) o2).getState(), asc);
                    }
                    break;
                case "warranty":
                    ret = compString(((HardwareItem) o1).getWarranty(), ((HardwareItem) o2).getWarranty(), asc);
                    break;
                case "location":
                    ret = compString(((HardwareItem) o1).getLocation(), ((HardwareItem) o2).getLocation(), asc);
                    break;
                case "ip":
                    ret = compString(((HardwareItem) o1).getIp(), ((HardwareItem) o2).getIp(), asc);
                    break;
                case "importance":
                    ret = compString(((HardwareItem) o1).getImportance(), ((HardwareItem) o2).getImportance(),
                            asc);
                    break;
                case "owner":
                    ret = compString(((HardwareItem) o1).getOwner(), ((HardwareItem) o2).getOwner(), asc);
                    break;
                case "softwareType":
                    ret = compString(((SoftwareItem) o1).getSoftwareType(),
                            ((SoftwareItem) o2).getSoftwareType(), asc);
                    break;
                case "license":
                    ret = compString(((SoftwareItem) o1).getLicense(), ((SoftwareItem) o2).getLicense(), asc);
                    break;
                case "expiredTime":
                    Date e1 = ((SoftwareItem) o1).getPurchaseTime();
                    Date e2 = ((SoftwareItem) o2).getPurchaseTime();
                    if (null == e1) {
                        if (null == e2) {
                            ret = 0;
                        } else {
                            ret = asc ? -1 : 1;
                        }
                    } else {
                        if (null == e2) {
                            ret = asc ? 1 : -1;
                        } else {
                            ret = asc ? e1.compareTo(e2) : e2.compareTo(e1);
                        }
                    }
                }
                return ret;
            }

            private int compString(String s1, String s2, boolean asc) {
                if (null == s1) {
                    if (null == s2) {
                        return 0;
                    } else {
                        return asc ? -1 : 1;
                    }
                } else {
                    if (null == s2) {
                        return asc ? 1 : -1;
                    } else {
                        return asc ? Collator.getInstance(java.util.Locale.CHINA).compare(s1, s2)
                                : Collator.getInstance(java.util.Locale.CHINA).compare(s2, s1);
                    }
                }
            }

        });
    }
    return SUCCESS;
}

From source file:com.encens.khipus.service.production.RawMaterialPayRollServiceBean.java

private boolean isDateInRange(Date date, Date start, Date end) {
    if (date.compareTo(start) < 0)
        return false;
    if (date.compareTo(end) > 0)
        return false;
    return true;//from   w w  w  .j av a2s  .  c  om
}

From source file:org.apache.ivory.workflow.engine.OozieWorkflowEngine.java

private List<CoordinatorJob> getApplicableCoords(Entity entity, OozieClient client, Date start, Date end,
        List<BundleJob> bundles) throws IvoryException {
    List<CoordinatorJob> applicableCoords = new ArrayList<CoordinatorJob>();
    try {/*from   w w  w .j a  va 2 s.  c o m*/
        for (BundleJob bundle : bundles) {
            List<CoordinatorJob> coords = client.getBundleJobInfo(bundle.getId()).getCoordinators();
            for (CoordinatorJob coord : coords) {
                String coordName = EntityUtil.getWorkflowName(Tag.RETENTION, entity).toString();
                if (coordName.equals(coord.getAppName()))
                    continue;
                if ((start.compareTo(coord.getStartTime()) >= 0 && start.compareTo(coord.getEndTime()) <= 0)
                        || (end.compareTo(coord.getStartTime()) >= 0
                                && end.compareTo(coord.getEndTime()) <= 0)) {
                    applicableCoords.add(coord);
                }
            }
        }
        sortCoordsByStartTime(applicableCoords);
        return applicableCoords;
    } catch (OozieClientException e) {
        throw new IvoryException(e);
    }
}

From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java

private void checkExpiration() {
    String sExp = root.getAttribute("ExpirationDate");
    java.util.Date dExp = null;
    int iValidDays = CivetConfig.getCviValidDays();
    Calendar cal = Calendar.getInstance();
    boolean bSet = false;
    try {/*  w  w  w. j a v  a  2  s.co m*/
        dExp = dateFormat.parse(sExp);
    } catch (ParseException e) {
        dExp = null;
    }
    NodeList nl = root.getElementsByTagName("Animal");
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        String sInsp = e.getAttribute("InspectionDate");
        if (sInsp != null && sInsp.trim().length() > 0) {
            java.util.Date dInsp = null;
            try {
                dInsp = dateFormat.parse(sInsp);
                if (dInsp != null) {
                    cal.setTime(dInsp);
                    cal.add(Calendar.DATE, iValidDays);
                    if (dExp == null || dExp.compareTo(cal.getTime()) > 0) {
                        dExp = cal.getTime();
                        bSet = true;
                    }

                }
            } catch (ParseException pe) {
                dExp = null;
            }
        }
    }
    if (bSet) {
        String sNewExp = dateFormat.format(dExp);
        root.setAttribute("ExpirationDate", sNewExp);
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Compares two java.util.Date objects, but handles java.sql.Timestamp (which is not directly
 * comparable to a date) by dropping its nanosecond value.
 *//*from www.  j  av a 2 s  .  c  o  m*/
public static int compare(Date d1, Date d2) {
    if (d1 instanceof Timestamp && d2 instanceof Timestamp) {
        return d1.compareTo(d2);
    }
    if (d1 instanceof Timestamp) {
        d1 = new Date(((Timestamp) d1).getTime());
    }
    if (d2 instanceof Timestamp) {
        d2 = new Date(((Timestamp) d2).getTime());
    }
    return d1.compareTo(d2);
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleBlobMetadata(HttpServletRequest request, HttpServletResponse response,
        BlobStore blobStore, String containerName, String blobName) throws IOException, S3Exception {
    BlobMetadata metadata = blobStore.blobMetadata(containerName, blobName);
    if (metadata == null) {
        throw new S3Exception(S3ErrorCode.NO_SUCH_KEY);
    }/*from   w ww.  ja v a2  s.  c o  m*/

    // BlobStore.blobMetadata does not support GetOptions so we emulate
    // conditional requests.
    String ifMatch = request.getHeader(HttpHeaders.IF_MATCH);
    String ifNoneMatch = request.getHeader(HttpHeaders.IF_NONE_MATCH);
    long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    long ifUnmodifiedSince = request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE);

    String eTag = metadata.getETag();
    if (eTag != null) {
        eTag = maybeQuoteETag(eTag);
        if (ifMatch != null && !ifMatch.equals(eTag)) {
            throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED);
        }
        if (ifNoneMatch != null && ifNoneMatch.equals(eTag)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
    }

    Date lastModified = metadata.getLastModified();
    if (lastModified != null) {
        if (ifModifiedSince != -1 && lastModified.compareTo(new Date(ifModifiedSince)) <= 0) {
            throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED);
        }
        if (ifUnmodifiedSince != -1 && lastModified.compareTo(new Date(ifUnmodifiedSince)) >= 0) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
    addMetadataToResponse(request, response, metadata);
}

From source file:org.kuali.kfs.module.cam.batch.service.impl.AssetDepreciationServiceImpl.java

protected boolean runAssetDepreciation() throws ParseException {
    boolean executeJob = false;
    List<String> errorMessages = new ArrayList<String>();
    Date currentDate = convertToDate(dateTimeService.toDateString(dateTimeService.getCurrentDate()));
    Date beginDate = getBlankOutBeginDate(errorMessages);
    Date endDate = getBlankOutEndDate(errorMessages);

    if (hasBlankOutPeriodStarted(beginDate, endDate, errorMessages)) {
        String blankOutPeriodrunDate = parameterService.getParameterValueAsString(AssetDepreciationStep.class,
                CamsConstants.Parameters.BLANK_OUT_PERIOD_RUN_DATE);
        if (!StringHelper.isNullOrEmpty(blankOutPeriodrunDate)) {
            Date runDate = convertToDate(blankOutPeriodrunDate);

            if (runDate.compareTo(beginDate) >= 0 && runDate.compareTo(endDate) <= 0) {
                if (currentDate.equals(runDate)) {
                    executeJob = true;//  w ww  .j av a 2  s  .  c  o  m
                } else {
                    LOG.info("Today is not BLANK_OUT_PERIOD_RUN_DATE. executeJob not set to true");
                }

            } else {
                String blankOutBegin = parameterService.getParameterValueAsString(AssetDepreciationStep.class,
                        CamsConstants.Parameters.BLANK_OUT_BEGIN_MMDD);
                String blankOutEnd = parameterService.getParameterValueAsString(AssetDepreciationStep.class,
                        CamsConstants.Parameters.BLANK_OUT_END_MMDD);
                String message = "BLANK_OUT_PERIOD_RUN_DATE: " + blankOutPeriodrunDate
                        + " is not in the blank out period range." + "Blank out period range is [ "
                        + blankOutBegin + "-" + blankOutEnd + " ] .";
                errorMessages.add(message);
                LOG.info(message);
            }
        } else {
            String message = "Parameter BLANK_OUT_PERIOD_RUN_DATE (component: Asset Depreciation Step) is not set"
                    + " Please set the date correctly to run the job.";
            errorMessages.add(message);
            LOG.info(message);
        }
    } else {
        if (getSchedulerService().cronConditionMet(this.cronExpression)) {
            executeJob = true;
        } else {
            LOG.info("Cron condition not met. executeJob not set to true");
        }
    }

    if (!executeJob && !errorMessages.isEmpty()) {
        sendWarningMail(errorMessages);
    }

    return executeJob;
}

From source file:org.apache.falcon.workflow.engine.OozieWorkflowEngine.java

protected void sortDescByStartTime(List<CoordinatorJob> consideredCoords) {
    Collections.sort(consideredCoords, new Comparator<CoordinatorJob>() {
        @Override/*from www .  j  a  v a2 s  .  com*/
        public int compare(CoordinatorJob left, CoordinatorJob right) {
            Date leftStart = left.getStartTime();
            Date rightStart = right.getStartTime();
            return rightStart.compareTo(leftStart);
        }
    });
}