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.kuali.kfs.vnd.document.validation.impl.VendorRule.java

protected boolean validateDOBDate(VendorDetail vDetail) {
    boolean valid = true;
    DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
    Date today = dateTimeService.getCurrentDate();

    if (ObjectUtils.isNotNull(vDetail.getVendorHeader().getVendorDOB())) {

        Date dobDate = vDetail.getVendorHeader().getVendorDOB();
        if (ObjectUtils.isNotNull(dobDate)) {

            if (today.compareTo(dobDate) <= 0) {
                putFieldError(VendorPropertyConstants.VENDOR_DOB,
                        VendorKeyConstants.ERROR_VENDOR_W8ANDW9_SIGNED_AFTER_TODAY);
                valid &= false;/*from   w w  w  .ja  va  2s. c  o m*/
            }
        }
    }
    return valid;
}

From source file:com.streamreduce.core.service.InventoryServiceImpl.java

private void pullFeedActivity(Connection connection)
        throws ConnectionNotFoundException, InvalidCredentialsException, IOException {
    Date lastActivityPoll = connection.getLastActivityPollDate();
    Date lastActivity = lastActivityPoll;

    if (lastActivityPoll != null) {
        logger.debug("Creating feed messages for messages newer than (" + lastActivityPoll + ") for ["
                + connection.getId() + "]: " + connection.getAlias());
    } else {/*w  ww  .jav a 2  s .  c  o  m*/
        logger.debug("Creating feed messages for all messages [" + connection.getId() + "]: "
                + connection.getAlias());
    }

    try (XmlReader xmlReader = new XmlReader(URI.create(connection.getUrl()).toURL())) {
        SyndFeed rssFeed = new SyndFeedInput().build(xmlReader);
        List feedEntries = rssFeed.getEntries();

        Collections.sort(feedEntries, new Comparator<Object>() {
            @Override
            public int compare(Object first, Object second) {
                SyndEntry firstEntry = (SyndEntry) first;
                SyndEntry secondEntry = (SyndEntry) second;
                Date firstDate = firstEntry.getPublishedDate() != null ? firstEntry.getPublishedDate()
                        : new Date();
                Date secondDate = secondEntry.getPublishedDate() != null ? secondEntry.getPublishedDate()
                        : new Date();

                return firstDate.compareTo(secondDate);
            }
        });

        for (Object rawEntry : feedEntries) {
            SyndEntry entry = (SyndEntry) rawEntry;

            //use published date if it exists... otherwise don't process the message as it is an update
            //this skips feed messages from feeds that don't include a publishedDate
            Date pubDate = entry.getPublishedDate();
            if (pubDate == null || pubDate.before(lastActivityPoll)) {
                continue;
            }

            lastActivity = pubDate.after(lastActivity) ? pubDate : lastActivity;

            Map<String, Object> eventContext = new HashMap<>();
            String messageBodyAsJson = determineMessageBodyAsJsonFromSyndEntry(entry);

            eventContext.put("activityPubDate", pubDate);
            eventContext.put("activityTitle", entry.getTitle());
            eventContext.put("payload", messageBodyAsJson);

            Event event = eventService.createEvent(EventId.ACTIVITY, connection, eventContext);

            FeedEntryDetails details = new FeedEntryDetails.Builder().url(entry.getUri())
                    .title(entry.getTitle())
                    .description(entry.getDescription() != null ? entry.getDescription().getValue() : null)
                    .publishedDate(pubDate).build();

            // Create a new message to be delivered to inboxes
            messageService.sendActivityMessage(event, connection, pubDate.getTime(), details);
        }
    } catch (IOException e) {
        logger.error(String.format("Error opening the connection %s for feed %s. Returned error: %s",
                connection.getId(), connection.getUrl(), e.getMessage()));
    } catch (Exception e) {
        logger.error(
                String.format("Unable to process messages for connection %s with feed %s. Returned error: %s",
                        connection.getId(), connection.getUrl(), e.getMessage()));
    } finally {
        // Update the connection's last polling timeconnection.setLastActivityPollDate(new Date(lastActivity.getTime() + 1));
        try {
            connectionService.updateConnection(connection, true);
        } catch (Exception e) {
            // This is a silent update to only update the last polling time so this should never throw an exception
        }
    }
}

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

@Override
public void validate(RawMaterialPayRoll rawMaterialPayRoll) throws RawMaterialPayRollException {
    Date lastEndDate = (Date) getEntityManager()
            .createNamedQuery("RawMaterialPayRoll.findLasEndDateByMetaProductAndProductiveZone")
            .setParameter("productiveZone", rawMaterialPayRoll.getProductiveZone())
            .setParameter("metaProduct", rawMaterialPayRoll.getMetaProduct()).getSingleResult();

    if (lastEndDate != null && rawMaterialPayRoll.getStartDate().compareTo(lastEndDate) <= 0) {
        throw new RawMaterialPayRollException(CROSS_WITH_ANOTHER_PAYROLL, lastEndDate);
    }//w  w  w .  j a v a 2 s . co  m

    if (lastEndDate == null) {
        lastEndDate = new Date(0L);
    }

    Calendar c = Calendar.getInstance();
    c.setTime(lastEndDate);
    c.add(DAY_OF_MONTH, 1);
    lastEndDate = c.getTime();

    Date minimumStartDate = (Date) getEntityManager()
            .createNamedQuery(
                    "RawMaterialCollectionSession.findMinimumDateOfCollectionSessionByMetaProductBetweenDates")
            .setParameter("productiveZone", rawMaterialPayRoll.getProductiveZone())
            .setParameter("metaProduct", rawMaterialPayRoll.getMetaProduct())
            .setParameter("startDate", lastEndDate).setParameter("endDate", rawMaterialPayRoll.getStartDate())
            .getSingleResult();

    if (minimumStartDate != null && minimumStartDate.compareTo(rawMaterialPayRoll.getStartDate()) < 0) {
        throw new RawMaterialPayRollException(MINIMUM_START_DATE, minimumStartDate);
    }
}

From source file:cn.apputest.ctria.sql.DBManager.java

public JobCertStatusDataEntity queryJobCertStatus(String certNumber) {
    DateFormat newdate = new DateFormat();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date dateTime1 = null;
    try {/*  w  w w.  jav  a2  s .  c o m*/
        dateTime1 = dateFormat.parse(newdate.getDate3());
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    Cursor c = queryTheCursorJobCertStatus(certNumber);
    JobCertStatusDataEntity jobcertstatus = new JobCertStatusDataEntity();
    while (c.moveToNext()) {
        String endTime = c.getString(c.getColumnIndex("EXPIRE_DATE"));
        if (endTime.equals("")) {
            jobcertstatus.setStatus("-1");
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                jobcertstatus.setStatus("1");
            } else {
                jobcertstatus.setStatus("0");
            }
        }
        jobcertstatus.setEndDate(endTime);
    }
    c.close();
    return jobcertstatus;
}

From source file:com.neusoft.mid.clwapi.service.statistics.StatisticsServiceImpl.java

/**
 * ???/*www .java  2  s.  co  m*/
 * 
 * @param token
 *            
 * @param eTag
 *            ??
 * @return ???
 */
@Override
public Object getAllDesc(String token, String eTag) {
    // ?Etag
    boolean checkEtagFlag = true;
    // ??ID
    String enId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);
    logger.info("???");

    // ???
    List<ReportDesc> list = stMapper.getReportDesc(enId);
    logger.info("????");
    logger.debug("list = " + (list == null ? "NULL" : list.size()));

    // ???
    if (list == null || list.size() == 0) {
        logger.error("????");
        throw new ApplicationException(ErrorConstant.ERROR10010, Response.Status.NOT_FOUND);
    } else {
        logger.debug("?");
        if (logger.isDebugEnabled()) {
            Iterator<ReportDesc> it = list.iterator();
            int i = 0;
            while (it.hasNext()) {
                ReportDesc iReportDesc = it.next();
                logger.debug(++i + iReportDesc.toString());
            }
        }
    }

    // ??
    String plaETag = list.get(0).getUpdateTime();

    logger.info("????[" + enId + "]?");
    logger.info("?ETag:" + eTag);
    logger.info("??ETag:" + plaETag);

    // ?
    Date dateTer = new Date();
    // ??
    Date datePla = new Date();

    if (eTag == null) {
        logger.error("If-None-Match");
        throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
    }

    // 
    if (!eTag.equals("0")) {
        try {
            dateTer = BeanUtil.checkTimeForm(eTag, HttpConstant.TIME_FORMAT);
        } catch (ParseException e) {
            logger.error("??", e);
            throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
        }
        // ??
        if (!plaETag.equals("0")) {
            try {
                datePla = BeanUtil.checkTimeForm(plaETag, HttpConstant.TIME_FORMAT);
            } catch (ParseException e) {
                logger.error("???", e);
                throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
            }
        }
    } else {
        checkEtagFlag = false;
    }

    // ??
    if (checkEtagFlag && dateTer.compareTo(datePla) == 0) {
        logger.info("???");
        return Response.notModified().build();
    } else if (checkEtagFlag && dateTer.compareTo(datePla) > 0) {
        logger.error("???");
        throw new ApplicationException(ErrorConstant.ERROR10103, Response.Status.BAD_REQUEST);
    }

    // ?
    List<ReportDesc> temp = new ArrayList<ReportDesc>();
    // ????
    Iterator<ReportDesc> it = list.iterator();
    while (it.hasNext()) {
        ReportDesc iReportDesc = it.next();
        // ??
        if (iReportDesc.getDel().equals("0")) {
            temp.add(iReportDesc);
        }
    }

    // ?
    ReportDescResp iReportDescResp = new ReportDescResp();
    iReportDescResp.setEtag(plaETag);
    iReportDescResp.setList(temp);
    return JacksonUtils.toJsonRuntimeException(iReportDescResp);
}

From source file:com.cloud.bridge.service.EC2RestServlet.java

/**
 * We check this to reduce replay attacks.
 * //from w  w w.j a va2s .  co  m
 * @param timeStamp
 * @return true - if the request is not longer valid, false otherwise
 * @throws ParseException
 */
private boolean hasSignatureExpired(String timeStamp) {
    Calendar cal = EC2RestAuth.parseDateString(timeStamp);
    if (null == cal)
        return false;

    Date expiredTime = cal.getTime();
    Date today = new Date(); // -> gets set to time of creation
    if (0 >= expiredTime.compareTo(today)) {
        logger.debug("timestamp given: [" + timeStamp + "], now: [" + today.toString() + "]");
        return true;
    } else
        return false;
}

From source file:org.kuali.kra.budget.calculator.SalaryCalculator.java

/**
 * -Uses sorted Budget Persons list and Inflation rates list to create salary breakup periods, each period consisting of a
 * SalaryDetails /*from  w  w w  .  j  av  a2s. c  om*/
 * -Call calculate method of each bean to calculate salary
 * 
 */
private QueryList<SalaryDetails> createSalBreakupIntervals() {
    QueryList combinedList = new QueryList();
    combinedList.addAll(filterBudgetPersons());
    combinedList.addAll(filterInflationRates());
    // initializing the break up intervals
    QueryList<SalaryDetails> breakUpIntervals = new QueryList<SalaryDetails>();
    BudgetPerson budgetPerson = null;
    BudgetRate budgetRate = null;
    BudgetRate prevBudgetProposalRate = null;
    Date tempStartDate = startDate;
    Date tempEndDate = endDate;
    Date rateChangeDate = null;
    /*
     * Creating an instance for storing the base values
     */
    SalaryDetails salaryDetails;
    SalaryDetails prevSalaryDetails = new SalaryDetails();
    for (int index = 0; index < combinedList.size(); index++) {
        Object changedObject = combinedList.get(index);
        boolean personFlag = changedObject instanceof BudgetPerson;
        if (personFlag) {
            budgetPerson = (BudgetPerson) changedObject;
            rateChangeDate = budgetPerson.getStartDate();
            prevSalaryDetails.setActualBaseSalary(budgetPerson.getCalculationBase());
            if (budgetPerson.getAppointmentType() == null) {
                budgetPerson.refreshReferenceObject("appointmentType");
            }
            prevSalaryDetails.setWorkingMonths(budgetPerson.getAppointmentType().getDuration());

        } else {
            budgetRate = (BudgetRate) changedObject;
            rateChangeDate = budgetRate.getStartDate();
        }
        if (budgetPerson == null)
            continue;//need to get the calc base first. So continue till you find a person node from the combined list
        int compareDateChange = rateChangeDate.compareTo(tempStartDate);
        if (compareDateChange > 0) {
            //                if(compareDateChange>0){
            // rate changed so get the previous day date and use it as endDate
            Calendar rateChangeCal = dateTimeService.getCalendar(rateChangeDate);
            rateChangeCal.add(Calendar.DATE, -1);
            tempEndDate = rateChangeCal.getTime();
            //                }
            Boundary boundary = new Boundary(tempStartDate, tempEndDate);
            salaryDetails = new SalaryDetails();
            salaryDetails.setBoundary(boundary);
            if (!personFlag && budgetRate != null) {
                // may have problem here, prevSalaryDetails may not be set yet.
                // before apply the inflation applicable rate
                salaryDetails.setActualBaseSalary(getPrevSalaryBase(budgetPerson, boundary));
                //salaryDetails.calculateActualBaseSalary(budgetProposalRate.getApplicableRate());
                if (prevBudgetProposalRate != null
                        && budgetPerson.getEffectiveDate().before(prevBudgetProposalRate.getStartDate())
                        && budgetPerson.getEffectiveDate().before(boundary.getStartDate())
                        && prevBudgetProposalRate.getStartDate().before(boundary.getEndDate())
                        && (prevBudgetProposalRate.getStartDate().equals(boundary.getStartDate())
                                || budget.getBudgetPeriods().get(0).getEndDate().before(startDate))) {
                    salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
                } else {
                    if (budgetRate != null && budgetPerson.getEffectiveDate().before(budgetRate.getStartDate())
                            && budgetPerson.getEffectiveDate().before(startDate)
                            && budgetRate.getStartDate().before(boundary.getEndDate())
                            && (budgetRate.getStartDate().compareTo(startDate) <= 0
                                    || budget.getBudgetPeriods().get(0).getEndDate().before(startDate))) {
                        salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
                    }
                }
                salaryDetails.setWorkingMonths(prevSalaryDetails.getWorkingMonths());
                salaryDetails.setAltBudgetPerson(getSameJobPerson(boundary, budgetPerson));
            }
            if (personFlag && budgetPerson != null) {
                salaryDetails.setActualBaseSalary(budgetPerson.getCalculationBase());
                salaryDetails.setWorkingMonths(budgetPerson.getAppointmentType().getDuration());
                salaryDetails.setAltBudgetPerson(getSameJobPerson(boundary, budgetPerson));
            }
            if (budgetPerson.getStartDate().compareTo(tempStartDate) <= 0) {
                breakUpIntervals.add(salaryDetails);
            }
            prevBudgetProposalRate = budgetRate;
            prevSalaryDetails = salaryDetails;
            tempStartDate = rateChangeDate;
        }
    }
    salaryDetails = new SalaryDetails();
    Boundary boundary = new Boundary(tempStartDate, endDate);
    salaryDetails = new SalaryDetails();
    salaryDetails.setBoundary(boundary);
    if (budgetRate != null && budgetPerson != null
            && budgetPerson.getEffectiveDate().before(budgetRate.getStartDate())) {
        salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
        salaryDetails.setWorkingMonths(prevSalaryDetails.getWorkingMonths());
    }
    if (budgetPerson != null) {
        //salaryDetails.setActualBaseSalary(budgetPerson.getCalculationBase());
        salaryDetails.setActualBaseSalary(getPrevSalaryBase(budgetPerson, boundary));
        populateAppointmentType(budgetPerson);
        BudgetPerson newBudgetPerson = getBudgetPersonApplied(budgetPerson, boundary);
        if (budgetRate != null && ((newBudgetPerson == null
                && budgetPerson.getEffectiveDate().before(budgetRate.getStartDate()))
                || (newBudgetPerson != null
                        && newBudgetPerson.getEffectiveDate().before(budgetRate.getStartDate())))) {
            salaryDetails.calculateActualBaseSalary(budgetRate.getApplicableRate());
        }

        if (newBudgetPerson != null) {
            newBudgetPerson.refreshReferenceObject("appointmentType");
            salaryDetails.setWorkingMonths(newBudgetPerson.getAppointmentType() == null ? DEFAULT_WORKING_MONTHS
                    : newBudgetPerson.getAppointmentType().getDuration());

        } else {
            salaryDetails.setWorkingMonths(budgetPerson.getAppointmentType() == null ? DEFAULT_WORKING_MONTHS
                    : budgetPerson.getAppointmentType().getDuration());
        }
        salaryDetails.setAltBudgetPerson(getSameJobPerson(boundary, budgetPerson));
    }
    breakUpIntervals.add(salaryDetails);
    return breakUpIntervals;

}

From source file:cn.apputest.ctria.sql.DBManager.java

public DriverCertStatusDataEntity queryDrivercertstatus(String driverLicenseNumber) {

    DateFormat newdate = new DateFormat();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date dateTime1 = null;
    try {/*w w w  .j ava 2  s  . co  m*/
        dateTime1 = dateFormat.parse(newdate.getDate3());
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    Cursor c = queryTheCursorDriverCertStatus(driverLicenseNumber);
    DriverCertStatusDataEntity drivercertstatus = new DriverCertStatusDataEntity();

    while (c.moveToNext()) {
        String endTime = c.getString(c.getColumnIndex("EXPIRE_DATE"));
        if (endTime.equals("")) {
            drivercertstatus.setStatus("-1");
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                drivercertstatus.setStatus("1");
            } else {
                drivercertstatus.setStatus("0");
            }
        }
        drivercertstatus.setEndDate(endTime);
    }
    c.close();
    return drivercertstatus;
}

From source file:com.baidu.rigel.biplatform.tesseract.meta.impl.TimeDimensionMemberServiceImpl.java

/**
 * ?//  ww  w. j a  v  a2s  .  c  om
 * 
 * @param level
 * @param parentMember
 * @return
 */
private List<MiniCubeMember> genMembersFromOtherToWeek(Level level, Member parentMember) {
    List<MiniCubeMember> members = Lists.newArrayList();
    String parentName = parentMember.getName();
    String year = parentName.substring(0, 4);
    String month = parentName.substring(4, 6);
    int quarterIndex = Integer.valueOf(month) - 1; // 
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime(); // ?
    Date nowWeek = this.getFirstDayOfWeek(now); // ?

    cal.set(Calendar.YEAR, Integer.valueOf(year));
    cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
    cal.set(Calendar.DATE, 1);
    cal.setFirstDayOfWeek(Calendar.MONDAY);

    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    int count = 1; // 
    Date firstDay = cal.getTime();
    Date firstWeek = this.getFirstDayOfWeek(firstDay); // ?
    Date lastDay;
    Date lastWeek;
    int daysOfMonth;
    switch (parentMember.getLevel().getType()) {
    case TIME_YEARS:
        break;
    case TIME_QUARTERS:
        cal.add(Calendar.MONTH, 2); // ??
        daysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // ?
        cal.add(Calendar.DATE, daysOfMonth);
        lastDay = cal.getTime(); // 
        lastWeek = this.getFirstDayOfWeek(lastDay); // 
        // ???
        if (nowWeek.before(lastWeek) || (nowWeek.compareTo(lastWeek) == 0)) {
            lastWeek = nowWeek;
        }
        cal.setTime(firstWeek); // ?
        while (cal.getTime().before(lastWeek) || (cal.getTime().compareTo(lastWeek) == 0)) {
            String day = sf.format(cal.getTime());
            String caption = "" + (quarterIndex + 1) + "" + count + "";
            caption = caption + day;
            MiniCubeMember dayMember = new MiniCubeMember(day);
            dayMember.setCaption(caption);
            dayMember.setLevel(level);
            dayMember.setParent(parentMember);
            dayMember.setName(day);
            dayMember.setVisible(true);
            for (int i = 0; i <= 6; i++) {
                dayMember.getQueryNodes().add(sf.format(cal.getTime()));
                cal.add(Calendar.DATE, 1);
            }
            members.add(dayMember);
            // cal.add(Calendar.DATE, 1);
            count++;
        }
        break;
    case TIME_MONTHS:
        daysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // 
        cal.add(Calendar.DATE, daysOfMonth);
        lastDay = cal.getTime(); // 
        lastWeek = this.getFirstDayOfWeek(lastDay); // 
        // ???
        if (nowWeek.before(lastWeek) || (nowWeek.compareTo(lastWeek) == 0)) {
            lastWeek = nowWeek;
        }
        cal.setTime(firstWeek); // ?
        while (cal.getTime().before(lastWeek) || (cal.getTime().compareTo(lastWeek) == 0)) {
            String day = sf.format(cal.getTime());
            String caption = month + "" + count + "";
            MiniCubeMember dayMember = new MiniCubeMember(day);
            dayMember.setCaption(caption);
            dayMember.setLevel(level);
            dayMember.setParent(parentMember);
            dayMember.setName(day);
            dayMember.setVisible(true);
            for (int i = 0; i <= 6; i++) {
                dayMember.getQueryNodes().add(sf.format(cal.getTime()));
                cal.add(Calendar.DATE, 1);
            }
            members.add(dayMember);
            // cal.add(Calendar.DATE, 1);
            count++;
        }
        break;
    case TIME_WEEKS:
        break;
    case TIME_DAYS:
        break;
    default:
    }
    return members;
}