Java Code Examples for java.time.Instant#compareTo()

The following examples show how to use java.time.Instant#compareTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DoubleArrayTimeCacheFromVDoubles.java    From diirt with MIT License 6 votes vote down vote up
private void deleteBefore(Instant Instant) {
    if (cache.isEmpty())
        return;

    // This we want to keep as we need to draw the area
    // from the Instant to the first new value
    Instant firstEntryBeforeInstant = cache.lowerKey(Instant);
    if (firstEntryBeforeInstant == null)
        return;

    // This is the last entry we want to delete
    Instant lastToDelete = cache.lowerKey(firstEntryBeforeInstant);
    if (lastToDelete == null)
        return;

    Instant firstKey = cache.firstKey();
    while (firstKey.compareTo(lastToDelete) <= 0) {
        cache.remove(firstKey);
        firstKey = cache.firstKey();
    }
}
 
Example 2
Source File: ArchiveChannel.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** Add given info value to buffer, tweaking its time stamp if necessary
 *  @param value Value to archive
 *  @return Value that was actually added, which may have adjusted time stamp
 */
final protected VType addInfoToBuffer(VType value)
{
    final VType last_value = last_archived_value;
    if (last_value != null)
    {
        final Instant last = VTypeHelper.getTimestamp(last_value);
        if (last.compareTo(VTypeHelper.getTimestamp(value)) >= 0)
        {   // Patch the time stamp
            final Instant next = last.plus(Duration.ofMillis(100));
            value = VTypeHelper.transformTimestamp(value, next);
        }
        // else: value is OK as is
    }
    addValueToBuffer(value);
    return value;
}
 
Example 3
Source File: MergingValueIterator.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** Determine the next value, i.e. the oldest sample from the base iterators
 *  @throws Exception on error
 */
private void fetchNext()
{
    // Find oldest time stamp
    Instant time = null;
    int index = -1;
    for (int i=0; i<raw_data.length; ++i)
    {
        if (raw_data[i] == null)
            continue;
        final Instant sample_time = VTypeHelper.getTimestamp(raw_data[i]);
        if (time == null  ||  sample_time.compareTo(time) < 0)
        {
            time = sample_time;
            index = i;
        }
    }
    if (time == null)
    {   // No channel left with any data.
        raw_data = null;
        value = null;
        return;
    }
    value = raw_data[index];
    raw_data[index] = iters[index].hasNext() ? iters[index].next() :  null;
}
 
Example 4
Source File: DatedTreeNode.java    From swblocks-decisiontree with Apache License 2.0 6 votes vote down vote up
private void updateDateRange(final TreeNode exactNode, final Range<Instant> range) {
    final Range<Instant> original = exactNode.getDateRange();
    Instant start = original.getStart();
    Instant finish = original.getFinish();

    if (start.isAfter(range.getStart())) {
        start = range.getStart();
    }
    if (finish.isBefore(range.getFinish())) {
        finish = range.getFinish();
    }

    if (start.compareTo(original.getStart()) != 0 ||
            finish.compareTo(original.getFinish()) != 0) {
        this.nextNodes.remove(new DatedNodeKey(exactNode.getValue(), original));

        exactNode.setDateRange(new Range<Instant>(start, finish));
        this.nextNodes.put(
                new DatedNodeKey(exactNode.getValue(), exactNode.getDateRange()), exactNode);
    }
}
 
Example 5
Source File: Profiler.java    From diirt with MIT License 5 votes vote down vote up
public void profile(){
    preLoopAction();

    stopWatch = new StopWatch(profileSettings.getMaxTries());
    stopWatch.setTimeType(profileSettings.getTimeType());

    nTries = 0;

    //System Time
    Instant start = Instant.now();
    Instant end = start.plus(Duration.ofSeconds(profileSettings.getTestTime()));

    //Trials
    while (end.compareTo(Instant.now()) >= 0 &&           //not over max time
           !Thread.currentThread().isInterrupted() &&       //not interrupted
           nTries < profileSettings.getMaxTries()) {        //not over max tries

                nTries++;
                stopWatch.start();

                iterationAction();

                stopWatch.stop();

                postIterationAction();
    }
}
 
Example 6
Source File: DetectionResultEvalutationIT.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private int isAnomaly(Instant time, List<Entry<Instant, Instant>> labels) {
    for (int i = 0; i < labels.size(); i++) {
        Entry<Instant, Instant> window = labels.get(i);
        if (time.compareTo(window.getKey()) >= 0 && time.compareTo(window.getValue()) <= 0) {
            return i;
        }
    }
    return -1;
}
 
Example 7
Source File: TransactionId.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
private static synchronized Instant getIncreasingInstant() {
    // Allows the transaction to be accepted as long as the
    // server is not more than 10 seconds behind us
    final Instant instant = Clock.systemUTC()
        .instant()
        .minusSeconds(10);

    // ensures every instant is at least always greater than the last
    lastInstant = lastInstant != null && instant.compareTo(lastInstant) <= 0
        ? lastInstant.plusNanos(1)
        : instant;

    return lastInstant;
}
 
Example 8
Source File: ModelSampleIterator.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @param start Start time
 *  @return Index sample with time stamp at-or-before start time, or -1.
 */
private int findSampleLessOrEqual(final Instant start)
{
    // Would like to use PlotSampleSearch, but that operates on array
    // of PlotSample[]
    int low = 0;
    int high = samples.size()-1;
    int cmp = 0;
    int mid = -1;
    while (low <= high)
    {
        mid = (low + high) / 2;
        // Compare 'mid' sample to goal
        final Instant time = samples.get(mid).getPosition();
        final int compare = time.compareTo(start);
        if (compare > 0)
        {   // 'mid' too big, search lower half
            cmp = 1;
            high = mid - 1;
        }
        else if (compare < 0)
        {   // 'mid' too small, search upper half
            cmp = -1;
            low = mid + 1;
        }
        else
        {
            cmp = 0;
            return mid; // found exact time
        }
    }
    // Didn't find exact match.
    if (cmp < 0) // 'mid' sample is smaller than x, so it's OK
        return mid;
    // cmp > 0, 'mid' sample is greater than x.
    // If there is a sample before, use that
    if (mid > 0)
        return mid-1;
    return -1;
}
 
Example 9
Source File: KCVSLog.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
private Duration timeSinceFirstMsg() {

            Duration sinceFirst =  Duration.ZERO;

            if (!toSend.isEmpty()) {
                Instant firstTimestamp = toSend.get(0).message.getMessage().getTimestamp();
                Instant nowTimestamp   = times.getTime();

                if (firstTimestamp.compareTo(nowTimestamp) < 0) {
                    sinceFirst = Duration.between(firstTimestamp, nowTimestamp);
                }
            }

            return sinceFirst;
        }
 
Example 10
Source File: ValidityPeriod.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
ValidityPeriod(final Instant from, final Instant to)
{
    if (from == null || to == null)
    {
        throw new IllegalArgumentException("Both 'to' and 'from' parameters cannot be null");
    }
    if (to.compareTo(from) < 0)
    {
        throw new IllegalArgumentException("Parameter 'to' cannot be less than 'from' value");
    }
    _from = from;
    _to = to;
}
 
Example 11
Source File: AnnouncementWrapperComparator.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private int compareInstantsNullSafe(Instant date1, Instant o2ModDate) {
    if (date1 == null && o2ModDate == null) {
        return 0;
    } else if (date1 == null) {
        return 1;
    } else if (o2ModDate == null) {
        return -1;
    }
    else {
    	return date1.compareTo(o2ModDate);
    }
}
 
Example 12
Source File: TimeTicks.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean isSupportedRange(final Instant low, final Instant high)
{
    final Duration range = Duration.between(low, high);
    return low.compareTo(high) < 0  &&
           range.compareTo(min) >= 0  &&  range.compareTo(max) <= 0;
}
 
Example 13
Source File: TimeTicks.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public String format(final Instant tick)
{
    final ZonedDateTime local = ZonedDateTime.ofInstant(tick, ZoneId.systemDefault());
    // Use full format for the start tick
    if (tick.compareTo(start) <= 0)
        return config.start_formatter.format(local);
    return config.formatter.format(local);
}
 
Example 14
Source File: TimeUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Instant min(Instant a, Instant b) {
    return a.compareTo(b) <= 0 ? a : b;
}
 
Example 15
Source File: TCKInstant.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_compareTo_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.compareTo(null);
}
 
Example 16
Source File: DateUtils.java    From kafka-connect-github-source with MIT License 4 votes vote down vote up
public static Instant MaxInstant (Instant i1, Instant i2){
    return i1.compareTo(i2) > 0 ? i1 : i2;
}
 
Example 17
Source File: CacheHelper.java    From diirt with MIT License 4 votes vote down vote up
/** Returns the minimum between the two specified {@link Timestamp}. */
public static Instant min(Instant t1, Instant t2) {
    if (t1 == null || t2 == null) return null;
    if (t1.compareTo(t2) <= 0) return t1;
    else return t2;
}
 
Example 18
Source File: TCKInstant.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_compareTo_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.compareTo(null);
}
 
Example 19
Source File: TCKInstant.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_compareTo_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.compareTo(null);
}
 
Example 20
Source File: KCVSLog.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    try {
        if (allowReadMarkerRecovery) setReadMarker();

        final int timeslice = getTimeSlice(messageTimeStart);

        // Setup time range we're about to query
        final Instant currentTime = times.getTime();
        // Can only read messages stamped up to the following time without violating design constraints
        final Instant maxSafeMessageTime = currentTime.minus(readLagTime);
        // We also have to stay inside the current timeslice or we could drop messages
        final Instant timesliceEnd = times.getTime((timeslice + 1) * TIMESLICE_INTERVAL);

        Instant messageTimeEnd =
                0 > maxSafeMessageTime.compareTo(timesliceEnd) /* maxSafeMessageTime < timesliceEnd */ ?
                maxSafeMessageTime : timesliceEnd;

        if (0 >  messageTimeStart.compareTo(messageTimeEnd)) {
            // nextTimepoint is strictly earlier than timeWindowEnd
            log.trace("MessagePuller time window: [{}, {})", messageTimeStart, messageTimeEnd);
        } else {
            /*
             * nextTimepoint is equal to or later than timeWindowEnd. We
             * can't run a column slice using these timestamps, since
             * the start would be greater than the end.
             *
             * This could happen during a brief window right after
             * startup with ReadMarker.fromNow(). However, if
             * nextTimestamp is much later than timeWindowEnd, then
             * something is probably misconfigured.
             */
            final Duration delta = Duration.between(messageTimeEnd, messageTimeStart);

            if (delta.toNanos() / 3 > readLagTime.toNanos()) {
                log.warn("MessagePuller configured with ReadMarker timestamp in the improbably distant future: {} (current time is {})", messageTimeStart, currentTime);
            } else {
                log.debug("MessagePuller configured with ReadMarker timestamp slightly ahead of read lag time; waiting for the clock to catch up");
            }

            return;
        }
        Preconditions.checkState(messageTimeStart.compareTo(messageTimeEnd) < 0);
        Preconditions.checkState(messageTimeEnd.compareTo(currentTime) <= 0, "Attempting to read messages from the future: messageTimeEnd=% vs currentTime=%s", messageTimeEnd, currentTime);

        StaticBuffer logKey = getLogKey(partitionId,bucketId,timeslice);
        KeySliceQuery query = new KeySliceQuery(logKey, BufferUtil.getLongBuffer(times.getTime(messageTimeStart)), BufferUtil.getLongBuffer(times.getTime(messageTimeEnd)));
        query.setLimit(maxReadMsg);
        log.trace("Converted MessagePuller time window to {}", query);

        List<Entry> entries= BackendOperation.execute(getOperation(query),KCVSLog.this,times,maxReadTime);
        prepareMessageProcessing(entries);
        if (entries.size()>=maxReadMsg) {
            /*Read another set of messages to ensure that we have exhausted all messages to the next timestamp.
            Since we have reached the request limit, it may be possible that there are additional messages
            with the same timestamp which we would miss on subsequent iterations */
            Entry lastEntry = entries.get(entries.size()-1);
            //Adding 2 microseconds (=> very few extra messages), not adding one to avoid that the slice is possibly empty
            messageTimeEnd = messageTimeEnd.plus(TWO_MICROSECONDS);
            log.debug("Extended time window to {}", messageTimeEnd);
            //Retrieve all messages up to this adjusted timepoint (no limit this time => get all entries to that point)
            query = new KeySliceQuery(logKey, BufferUtil.nextBiggerBuffer(lastEntry.getColumn()), BufferUtil.getLongBuffer(times.getTime(messageTimeEnd)));
            log.debug("Converted extended MessagePuller time window to {}", query);
            List<Entry> extraEntries = BackendOperation.execute(getOperation(query),KCVSLog.this,times,maxReadTime);
            prepareMessageProcessing(extraEntries);
        }
        messageTimeStart = messageTimeEnd;
    } catch (Throwable e) {
        log.warn("Could not read messages for timestamp ["+messageTimeStart+"] (this read will be retried)",e);
    }
}