Example usage for java.util Date after

List of usage examples for java.util Date after

Introduction

In this page you can find the example usage for java.util Date after.

Prototype

public boolean after(Date when) 

Source Link

Document

Tests if this date is after the specified date.

Usage

From source file:Dates.java

/**
 * Date Arithmetic function (date2 - date1). subtract a date from another
 * date, return the difference as the required fields. E.g. if specified
 * Calendar.Date, the smaller range of fields is ignored and this method
 * return the difference of days./*from   w ww.j  a v  a  2  s.  co  m*/
 * 
 * @param date2
 *          The date2.
 * @param tz
 *          The time zone.
 * @param field
 *          The time field; e.g., Calendar.DATE, Calendar.YEAR, it's default
 *          value is Calendar.DATE
 * @param date1
 *          The date1.
 */
public static final long subtract(Date date2, TimeZone tz, int field, Date date1) {
    if (tz == null)
        tz = TimeZones.getCurrent();

    boolean negative = false;
    if (date1.after(date2)) {
        negative = true;
        final Date d = date1;
        date1 = date2;
        date2 = d;
    }

    final Calendar cal1 = Calendar.getInstance(tz);
    cal1.setTimeInMillis(date1.getTime());// don't call cal.setTime(Date) which
                                          // will reset the TimeZone.

    final Calendar cal2 = Calendar.getInstance(tz);
    cal2.setTimeInMillis(date2.getTime());// don't call cal.setTime(Date) which
                                          // will reset the TimeZone.

    int year1 = cal1.get(Calendar.YEAR);
    int year2 = cal2.get(Calendar.YEAR);

    switch (field) {
    case Calendar.YEAR: {
        return negative ? (year1 - year2) : (year2 - year1);
    }
    case Calendar.MONTH: {
        int month1 = cal1.get(Calendar.MONTH);
        int month2 = cal2.get(Calendar.MONTH);
        int months = 12 * (year2 - year1) + month2 - month1;
        return negative ? -months : months;
    }
    case Calendar.HOUR: {
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long min1 = (time1 < 0 ? (time1 - (1000 * 60 * 60 - 1)) : time1) / (1000 * 60 * 60);
        long min2 = (time2 < 0 ? (time2 - (1000 * 60 * 60 - 1)) : time2) / (1000 * 60 * 60);
        return negative ? (min1 - min2) : (min2 - min1);
    }
    case Calendar.MINUTE: {
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long min1 = (time1 < 0 ? (time1 - (1000 * 60 - 1)) : time1) / (1000 * 60);
        long min2 = (time2 < 0 ? (time2 - (1000 * 60 - 1)) : time2) / (1000 * 60);
        return negative ? (min1 - min2) : (min2 - min1);
    }
    case Calendar.SECOND: {
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long sec1 = (time1 < 0 ? (time1 - (1000 - 1)) : time1) / 1000;
        long sec2 = (time2 < 0 ? (time2 - (1000 - 1)) : time2) / 1000;

        return negative ? (sec1 - sec2) : (sec2 - sec1);
    }
    case Calendar.MILLISECOND: {
        return negative ? (date1.getTime() - date2.getTime()) : (date2.getTime() - date1.getTime());
    }
    case Calendar.DATE:
    default: /* default, like -1 */
    {
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int maxDay1 = year1 == year2 ? 0 : cal1.getActualMaximum(Calendar.DAY_OF_YEAR);
        int days = maxDay1 - day1 + day2;

        final Calendar cal = Calendar.getInstance(tz);
        for (int year = year1 + 1; year < year2; year++) {
            cal.set(Calendar.YEAR, year);
            days += cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        }
        return negative ? -days : days;
    }
    }
}

From source file:com.pinterest.secor.util.FileUtil.java

public static boolean s3PathPrefixIsAltered(String logFileName, SecorConfig config) throws Exception {
    Date logDate = null;//w ww . j av a  2  s  .  c  om
    if (config.getS3AlterPathDate() != null && !config.getS3AlterPathDate().isEmpty()) {

        Date s3AlterPathDate = new SimpleDateFormat("yyyy-MM-dd").parse(config.getS3AlterPathDate());

        // logFileName contains the log path, e.g. raw_logs/secor_topic/dt=2016-04-20/3_0_0000000000000292564
        Matcher dateMatcher = datePattern.matcher(logFileName);
        if (dateMatcher.find()) {
            logDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateMatcher.group(1));
        }

        if (logDate == null) {
            throw new Exception("Did not find a date in the format yyyy-MM-dd in " + logFileName);
        }

        if (!s3AlterPathDate.after(logDate)) {
            return true;
        }
    }

    return false;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private static void validateToken(ServerIssuedToken token, TokenType expectedTokenType) {
    String error = null;/*from w  w  w  .java  2  s.c  o m*/

    if (!token.getAudience().contains(clientId)) {
        error = "audience does not contain expected client_id";
    }

    if (error == null && !clientId.equals(token.getClientID().getValue())) {
        error = "incorrect client_id";
    }

    if (error == null && !tenantName.equals(token.getTenant())) {
        error = "incorrect tenant";
    }

    Date now = new Date();
    Date adjustedExpirationTime = new Date(
            token.getExpirationTime().getTime() + CLOCK_TOLERANCE_SECONDS * 1000L);
    if (error == null && now.after(adjustedExpirationTime)) {
        error = "expired jwt";
    }

    if (error == null && token.getTokenType() != expectedTokenType) {
        error = "incorrect token_type";
    }

    if (expectedTokenType == TokenType.HOK) {
        if (error == null && token.getHolderOfKey() == null) {
            error = "missing hotk claim";
        }

        if (error == null) {
            RSAPublicKey rsaPublicKey = token.getHolderOfKey();
            if (rsaPublicKey == null) {
                error = "could not extract an RSA 256 public key out of hotk";
            } else if (!rsaPublicKey.equals(clientCertificate.getPublicKey())) {
                error = "hotk is not equal to the public key we sent";
            }
        }

        if (error == null && token.getActAs() == null) {
            error = "missing act_as claim";
        }
    }

    if (error != null) {
        throw new IllegalStateException(
                String.format("%s validation error: %s", token.getTokenClass().getValue(), error));
    }
}

From source file:com.sitewhere.hbase.device.HBaseDeviceEvent.java

/**
 * Find all event rows associated with a site and return values that match the search
 * criteria. TODO: This is not optimized at all and will take forever in cases where
 * there are ton of assignments and events. It has to go through every record
 * associated with the site. It works for now though.
 * /*from www . j  av  a 2  s .  c o  m*/
 * @param hbase
 * @param siteToken
 * @param eventType
 * @param criteria
 * @return
 * @throws SiteWhereException
 */
protected static Pager<byte[]> getEventRowsForSite(ISiteWhereHBaseClient hbase, String siteToken,
        DeviceAssignmentRecordType eventType, IDateRangeSearchCriteria criteria) throws SiteWhereException {
    Long siteId = IdManager.getInstance().getSiteKeys().getValue(siteToken);
    if (siteId == null) {
        throw new SiteWhereSystemException(ErrorCode.InvalidSiteToken, ErrorLevel.ERROR);
    }
    byte[] startPrefix = HBaseSite.getAssignmentRowKey(siteId);
    byte[] afterPrefix = HBaseSite.getAfterAssignmentRowKey(siteId);

    HTableInterface events = null;
    ResultScanner scanner = null;
    try {
        events = hbase.getTableInterface(ISiteWhereHBase.EVENTS_TABLE_NAME);
        Scan scan = new Scan();
        scan.setStartRow(startPrefix);
        scan.setStopRow(afterPrefix);
        scanner = events.getScanner(scan);

        List<DatedByteArray> matches = new ArrayList<DatedByteArray>();
        Iterator<Result> results = scanner.iterator();
        while (results.hasNext()) {
            Result current = results.next();
            byte[] key = current.getRow();
            if (key.length > 7) {
                Map<byte[], byte[]> cells = current.getFamilyMap(ISiteWhereHBase.FAMILY_ID);
                for (byte[] qual : cells.keySet()) {
                    byte[] value = cells.get(qual);
                    if ((qual.length > 3) && (qual[3] == eventType.getType())) {
                        Date eventDate = getDateForEventKeyValue(key, qual);
                        if ((criteria.getStartDate() != null) && (eventDate.before(criteria.getStartDate()))) {
                            continue;
                        }
                        if ((criteria.getEndDate() != null) && (eventDate.after(criteria.getEndDate()))) {
                            continue;
                        }
                        matches.add(new DatedByteArray(eventDate, value));
                    }
                }
            }
        }
        Collections.sort(matches, Collections.reverseOrder());
        Pager<byte[]> pager = new Pager<byte[]>(criteria);
        for (DatedByteArray match : matches) {
            pager.process(match.getJson());
        }
        return pager;
    } catch (IOException e) {
        throw new SiteWhereException("Error scanning event rows.", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
        HBaseUtils.closeCleanly(events);
    }
}

From source file:com.sitewhere.hbase.device.HBaseDeviceEvent.java

/**
 * Find all event rows associated with a device assignment and return cells that match
 * the search criteria./*from  w  w  w .  j a  v a 2  s. c  om*/
 * 
 * @param hbase
 * @param assnToken
 * @param eventType
 * @param criteria
 * @return
 * @throws SiteWhereException
 */
protected static Pager<byte[]> getEventRowsForAssignment(ISiteWhereHBaseClient hbase, String assnToken,
        DeviceAssignmentRecordType eventType, IDateRangeSearchCriteria criteria) throws SiteWhereException {
    byte[] assnKey = IdManager.getInstance().getAssignmentKeys().getValue(assnToken);
    if (assnKey == null) {
        throw new SiteWhereSystemException(ErrorCode.InvalidDeviceAssignmentToken, ErrorLevel.ERROR);
    }

    // Note: Because time values are inverted, start and end keys are reversed.
    byte[] startKey = null, endKey = null;
    if (criteria.getStartDate() != null) {
        startKey = getRowKey(assnKey, criteria.getEndDate().getTime());
    } else {
        startKey = getAbsoluteStartKey(assnKey);
    }
    if (criteria.getEndDate() != null) {
        endKey = getRowKey(assnKey, criteria.getStartDate().getTime());
    } else {
        endKey = getAbsoluteEndKey(assnKey);
    }

    HTableInterface events = null;
    ResultScanner scanner = null;
    try {
        events = hbase.getTableInterface(ISiteWhereHBase.EVENTS_TABLE_NAME);
        Scan scan = new Scan();
        scan.setStartRow(startKey);
        scan.setStopRow(endKey);
        scanner = events.getScanner(scan);

        Pager<byte[]> pager = new Pager<byte[]>(criteria);
        Iterator<Result> results = scanner.iterator();
        while (results.hasNext()) {
            Result current = results.next();
            Map<byte[], byte[]> cells = current.getFamilyMap(ISiteWhereHBase.FAMILY_ID);
            for (byte[] qual : cells.keySet()) {
                byte[] value = cells.get(qual);
                if ((qual.length > 3) && (qual[3] == eventType.getType())) {
                    Date eventDate = getDateForEventKeyValue(current.getRow(), qual);
                    if ((criteria.getStartDate() != null) && (eventDate.before(criteria.getStartDate()))) {
                        continue;
                    }
                    if ((criteria.getEndDate() != null) && (eventDate.after(criteria.getEndDate()))) {
                        continue;
                    }
                    pager.process(value);
                }
            }
        }
        return pager;
    } catch (IOException e) {
        throw new SiteWhereException("Error scanning event rows.", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
        HBaseUtils.closeCleanly(events);
    }

}

From source file:com.saiton.ccs.validations.FormatAndValidate.java

private static boolean doesTheDateFallsBetween(Date from, Date to, Date date) {

    return (date.equals(from) || date.equals(to) || (date.after(from) && date.before(to)));

}

From source file:ua.com.fielden.platform.example.swing.booking.BookingChartPanelExample.java

private static BookingSeries<VehicleEntity, BookingEntity> createBookingSeries(final Date now) {
    final SingleTypeBookingEntity<VehicleEntity, BookingEntity> entity = new SingleTypeBookingEntity<VehicleEntity, BookingEntity>(
            BookingEntity.class, "bookingStart", "bookingFinish", null, now, null) {

        @Override//w w w  . j ava2 s .c  o m
        public boolean canEditSubEntity(final VehicleEntity entity, final BookingEntity subEntity,
                final BookingChangedEventType type, final BookingStretchSide side) {
            if (BookingChangedEventType.MOVE == type) {
                if (subEntity.getBookingStart().before(now) || subEntity.getBookingFinish().before(now)) {
                    return false;
                }
            } else {
                if (BookingStretchSide.LEFT == side && now.after(subEntity.getBookingStart())) {
                    return false;
                } else if (BookingStretchSide.RIGHT == side && now.after(subEntity.getBookingFinish())) {
                    return false;
                }
            }
            return true;
        }

    };

    final BookingSeries<VehicleEntity, BookingEntity> series = new BookingSeries<>(entity);
    series.setCutOfFactor(0.10);
    series.setName("Booking series");
    series.setPainter(new IBookingPainter<VehicleEntity, BookingEntity>() {

        final Color color = new Color(254, 214, 88);
        //final Color invalidColor = new Color(238, 83, 35);
        //final Color requestColor = new Color(27, 114, 25);

        @Override
        public List<Pair<String, Paint>> getAvailableLegendItems() {
            return Arrays.asList(new Pair<String, Paint>("Booking duration", color));
        }

        @Override
        public Paint getPainterFor(final VehicleEntity entity, final BookingEntity subEntity) {
            return color;
        }
    });
    return series;
}

From source file:com.pearson.openideas.cq5.components.utils.ArticleUtils.java

/**
 * This method turns a tagged resource into an article object.
 * // w ww  .j  a v  a2s.c o m
 * @param resource
 *            the resource to extract data from
 * @param article
 *            the article object to add data to
 * @param tagManager
 *            the tag manager instance
 * @param indexing
 *            A boolean to indicate whether to include the indexing fields or not.
 * @return the completed/populated article object
 */
public static Article createArticleObject(Resource resource, Article article, TagManager tagManager,
        boolean indexing) {

    List<String> countries = new ArrayList<String>();
    List<String> contributors = new ArrayList<String>();
    List<String> organisations = new ArrayList<String>();
    List<String> keywords = new ArrayList<String>();
    List<String> contributorBiogs = new ArrayList<String>();

    log.debug("Are we indexing? " + indexing);

    Calendar weekAgo = Calendar.getInstance();
    weekAgo.set(weekAgo.get(Calendar.YEAR), weekAgo.get(Calendar.MONTH),
            weekAgo.get(Calendar.DAY_OF_MONTH) - BEFOREDAYS);

    String path = resource.getPath();
    log.debug("path to resource: " + path);
    article.setUrl(StringUtils.substring(path, 0, path.lastIndexOf("/")));
    ValueMap articleMap = resource.getChild("articleBody").adaptTo(ValueMap.class);
    article.setShortSummary(articleMap.get("shortsummary", ""));
    article.setArticleTitle(articleMap.get("articletitle", ""));

    //pull the image from the article
    Image image = new Image(resource.getChild("articleBody").getChild("image"));
    image.setSelector(".img");
    article.setImage(image);

    //also, pull the thumbnail image from the article
    if (resource.getChild("articleBody").getChild("imagethumb") != null) {
        Image thumbnail = new Image(resource.getChild("articleBody").getChild("imagethumb"));
        thumbnail.setSelector(".img");
        log.debug("article thumbnail has an image: " + thumbnail.hasContent());
        article.setThumbnail(thumbnail);
    } else {
        log.debug("no thumbnail, falling back to article image");
        article.setThumbnail(image);
    }

    // second, we'll pull the contributor tags from however many contributor components we have
    Resource leadContribResource = resource.getChild("leadContributor");

    // pull an array of one to get the lead contributor name for rendering
    Tag[] leadContribTags = tagManager.getTags(leadContribResource);
    if (leadContribTags != null && leadContribTags.length > 0) {
        article.setAuthor(leadContribTags[0].getTitle());
    } else {
        log.warn("Article " + article.getArticleTitle() + "has no lead contributor set yet.");
    }

    if (StringUtils.isNotBlank(articleMap.get("newpublishdate", ""))) {
        Date newPubDateObject = null;
        SimpleDateFormat sdf = new SimpleDateFormat(DateFormatEnum.CQDATEFORMAT.getDateFormat());

        try {
            newPubDateObject = sdf.parse(articleMap.get("newpublishdate", ""));
        } catch (ParseException e) {
            log.error("Error parsing date", e);
        }

        if (newPubDateObject != null) {
            String newDateString = new SimpleDateFormat(DateFormatEnum.CLIENTDATEFORMAT.getDateFormat())
                    .format(newPubDateObject);
            article.setPubDate(newDateString);
            article.setPubDateObject(newPubDateObject);
            if (newPubDateObject.after(weekAgo.getTime())) {
                article.setSuitableForEmail(true);
            }

        } else {
            log.warn("new pub date object is null");
        }
    } else {
        log.debug("Trying to parse original date object");
        Date originalPubDateObject = resource.adaptTo(ValueMap.class).get("jcr:created", Date.class);
        log.debug("original pub date: " + originalPubDateObject.toString());
        String originalPublishDateString = new SimpleDateFormat(DateFormatEnum.CLIENTDATEFORMAT.getDateFormat())
                .format(originalPubDateObject);
        article.setPubDate(originalPublishDateString);
        article.setPubDateObject(originalPubDateObject);
        if (originalPubDateObject.after(weekAgo.getTime())) {
            article.setSuitableForEmail(true);
        }
    }

    Tag[] tags = tagManager.getTags(resource);
    for (Tag tagFromPage : tags) {
        String tagPath = tagFromPage.getPath();

        if (tagPath.contains(NamespaceEnum.THEME.getNamespace())) {
            article.setTheme(tagFromPage.getTitle());
        } else if (tagPath.contains(NamespaceEnum.CATEGORY.getNamespace())) {
            article.setCategory(tagFromPage.getTitle());
        } else if (indexing && tagPath.contains(NamespaceEnum.CONTRIBUTOR.getNamespace())) {
            contributors.add(tagFromPage.getTitle());
            contributorBiogs.add(tagFromPage.getDescription());
        } else if (indexing && tagPath.contains(NamespaceEnum.KEYWORD.getNamespace())) {
            keywords.add(tagFromPage.getTitle());
        } else if (indexing && tagPath.contains(NamespaceEnum.ORGANISATION.getNamespace())) {
            organisations.add(tagFromPage.getTitle());
        } else if (indexing && tagPath.contains(NamespaceEnum.COUNTRY.getNamespace())) {
            countries.add(tagFromPage.getTitle());
        }
    }

    if (indexing) {
        article.setContributors(contributors);
        article.setCountries(countries);
        article.setOrganisations(organisations);
        article.setKeywords(keywords);
        article.setContributorBiogs(contributorBiogs);
        article.setCitation(articleMap.get("citation", ""));
        String articleText = articleMap.get("text", "");

        Resource par = resource.getChild("par");

        if (par != null) {
            Iterator<Resource> parResources = par.listChildren();
            while (parResources.hasNext()) {
                Resource parResource = parResources.next();
                ValueMap resourceMap = parResource.adaptTo(ValueMap.class);
                String type = resourceMap.get("sling:resourceType", "");
                if (type.endsWith("articleText")) {
                    articleText += resourceMap.get("text", "");
                }
            }
        }
        article.setArticleText(articleText);
    }
    return article;

}

From source file:com.example.app.profile.ui.user.ProfileMembershipManagement.java

private static boolean isOverlapped(List<Membership> list) {
    for (Membership m1 : list) {
        final Date startA = m1.getStartDate();
        final Date endA = m1.getEndDate();

        for (Membership m2 : list) {
            if (m1 == m2)
                continue;
            final Date startB = m2.getStartDate();
            final Date endB = m2.getEndDate();
            if ((startA == null || endB == null || startA.before(endB) || startA.equals(endB))
                    && (endA == null || startB == null || endA.after(startB) || endA.equals(startB)))
                return true;
        }//from   w  ww  . j a va  2s  . c o  m
    }
    return false;
}

From source file:cz.jirutka.spring.http.client.cache.DefaultCachedEntrySuitabilityChecker.java

public boolean canCachedEntryBeUsed(HttpRequest request, CacheEntry entry, Date now) {

    if (now.after(entry.getResponseExpiration())) {
        return false;
    }//w w w. jav a 2  s . co  m
    CacheControl cc = parseCacheControl(request.getHeaders());

    if (cc.getMaxAge() > -1 && responseCurrentAge(entry, now) > cc.getMaxAge()) {
        return false;
    }

    return true;
}