Java Code Examples for java.time.Instant.isBefore()

The following are Jave code examples for showing how to use isBefore() of the java.time.Instant class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: SensorThingsProcessor   File: ValidatorNewer.java   View Source Code Vote up 6 votes
@Override
public boolean isValid(Observation obs) throws ProcessException {
    try {
        Instant latest;
        Datastream ds = obs.getDatastream();
        if (ds == null) {
            MultiDatastream mds = obs.getMultiDatastream();
            if (mds == null) {
                throw new ProcessException("Observation has no Datastream of Multidatastream set!");
            }
            latest = getTimeForMultiDatastream(mds);
        } else {
            latest = getTimeForDatastream(ds);
        }
        TimeObject phenomenonTime = obs.getPhenomenonTime();
        Instant obsInstant;
        if (phenomenonTime.isInterval()) {
            obsInstant = phenomenonTime.getAsInterval().getStart();
        } else {
            obsInstant = phenomenonTime.getAsDateTime().toInstant();
        }
        return latest.isBefore(obsInstant);
    } catch (ServiceFailureException ex) {
        throw new ProcessException("Failed to validate.", ex);
    }
}
 
Example 2
Project: swblocks-decisiontree   File: DatedTreeNode.java   View Source Code Vote up 6 votes
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 3
Project: pravega-samples   File: PravegaAnomalyDetectionProcessor.java   View Source Code Vote up 6 votes
@Override
public Result fold(Result accumulator, Event.Alert value) throws Exception {
	accumulator.setCount(accumulator.getCount() + 1);
	accumulator.setNetworkId(value.getNetworkId());
	accumulator.getIpAddress().add(Event.EventType.formatAddress(value.getEvent().getSourceAddress()));
	if(accumulator.getMinTimestamp() == 0) {
		accumulator.setMinTimestamp(value.getEvent().getEventTime().toEpochMilli());
		accumulator.setMaxTimestamp(value.getEvent().getEventTime().toEpochMilli());
	} else {
		Instant d1 = Instant.ofEpochMilli(accumulator.getMinTimestamp());
		Instant d2 = value.getEvent().getEventTime();
		if(d1.isBefore(d2)) {
			accumulator.setMinTimestamp(d1.toEpochMilli());
			accumulator.setMaxTimestamp(d2.toEpochMilli());
		} else {
			accumulator.setMinTimestamp(d2.toEpochMilli());
			accumulator.setMaxTimestamp(d1.toEpochMilli());
		}
	}
	if(accumulator.getLocation() == null) {
		accumulator.setLocation(value.getEvent().getLatlon().getLat() + "," + value.getEvent().getLatlon().getLon());
	}
	return accumulator;
}
 
Example 4
Project: nautilus-samples   File: PravegaAnomalyDetectionProcessor.java   View Source Code Vote up 6 votes
@Override
public Result fold(Result accumulator, Event.Alert value) throws Exception {
	accumulator.setCount(accumulator.getCount() + 1);
	accumulator.setNetworkId(value.getNetworkId());
	accumulator.getIpAddress().add(Event.EventType.formatAddress(value.getEvent().getSourceAddress()));
	if(accumulator.getMinTimestamp() == 0) {
		accumulator.setMinTimestamp(value.getEvent().getEventTime().toEpochMilli());
		accumulator.setMaxTimestamp(value.getEvent().getEventTime().toEpochMilli());
	} else {
		Instant d1 = Instant.ofEpochMilli(accumulator.getMinTimestamp());
		Instant d2 = value.getEvent().getEventTime();
		if(d1.isBefore(d2)) {
			accumulator.setMinTimestamp(d1.toEpochMilli());
			accumulator.setMaxTimestamp(d2.toEpochMilli());
		} else {
			accumulator.setMinTimestamp(d2.toEpochMilli());
			accumulator.setMaxTimestamp(d1.toEpochMilli());
		}
	}
	if(accumulator.getLocation() == null) {
		accumulator.setLocation(value.getEvent().getLatlon().getLat() + "," + value.getEvent().getLatlon().getLon());
	}
	return accumulator;
}
 
Example 5
Project: pure-bliss-with-pure-java-functions   File: OfflineDevicesJobImpl.java   View Source Code Vote up 6 votes
/**
 * Calculates the last passed threshold given a start point and a current point in time plus a list of thresholds.
 * If the amount of time passed between the start and current instant is less than the first interval, it returns
 * empty.
 * If not, the amount is checked against each fixed interval and the calculated intervals after it. As soon
 * as the last passed interval has been determined, it will be returned.
 *
 * @param start      The start instant to compare the current instant with.
 * @param current    The current instant to compare with the starting point.
 * @param thresholds The list of fixed push notification thresholds.
 * @return The last passed threshold, or empty if no threshold has been passed yet.
 */
static Optional<Duration> calculateLastPassedThreshold(Instant start, Instant current, List<Duration> thresholds) {
    if (current.isBefore(start) || start.equals(current) || thresholds == null || thresholds.isEmpty()) {
        throw new IllegalArgumentException("Start must be before current and there should be at least 1 threshold");
    }

    Duration timePassed = Duration.between(start, current);

    if (timePassed.compareTo(thresholds.get(0)) <= 0) {
        return Optional.empty();
    }

    for (int i = 1; i < thresholds.size(); i++) {
        if (timePassed.compareTo(thresholds.get(i)) <= 0) {
            return Optional.of(thresholds.get(i - 1));
        }
    }

    return Optional.of(thresholds.get(thresholds.size() - 1));
}
 
Example 6
Project: Chronetic   File: ChronoSeries.java   View Source Code Vote up 5 votes
/**
 * Create a ChronoSeries from the given frequency information.
 *
 * @param minimumFrequency minimum frequency
 * @param maximumFrequency maximum frequency
 * @param frequencyUnit frequency unit
 * @param startInstant start timestamp
 * @param endInstant end stamp
 * @return ChronoSeries from the given frequency information
 */
@NotNull
public static ChronoSeries fromFrequency(long minimumFrequency, long maximumFrequency, @NotNull ChronoUnit frequencyUnit,
                                         @NotNull Instant startInstant, @NotNull Instant endInstant) {
    List<Instant> instants = new ArrayList<>();
    Instant itrTime = startInstant;
    while (itrTime.isBefore(endInstant) || itrTime.equals(endInstant)) {
        instants.add(itrTime);
        itrTime = itrTime.plus(RandomRegistry.getRandom().nextInt(
                (int) (maximumFrequency - minimumFrequency) + 1) + minimumFrequency, frequencyUnit);
    }
    return of(instants.toArray(new Instant[0]));
}
 
Example 7
Project: swage   File: RollingFileWriter.java   View Source Code Vote up 5 votes
/**
 * If necessary, close the current logfile and open a new one,
 * updating {@link #writer}.
 */
private void rollIfNeeded() throws IOException {
    // Do not roll unless record is complete, as indicated by flush
    if (!flushed) return;
    flushed = false;

    // If we have not yet passed the roll over mark do nothing
    Instant now = Instant.now();
    if (now.isBefore(rollAt)) {
        return;
    }

    // New file time, may not be the rollAt time if one or more intervals
    // have passed without anything being written
    Instant rollTime = now.truncatedTo(rollInterval);

    // Determine the name of the file that will be written to
    String name = this.baseName + format.format(LocalDateTime.ofInstant(rollTime, timeZone));
    this.outPath = this.directory.resolve(name);

    // Finish writing to previous log
    if (writer != null) {
        writer.flush();
        writer.close();
    }

    // Ensure the parent directory always exists, even if it was removed out from under us.
    // A no-op if the directory already exists.
    Files.createDirectories(outPath.getParent());

    // Create new file, set it as our write destination
    writer = Files.newBufferedWriter(
                outPath,
                StandardCharsets.UTF_8,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);

    // Point to the next time we want to roll the log, update rollAt
    this.rollAt = rollTime.plus(1, rollInterval);
}
 
Example 8
Project: trading4j   File: M5.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localBase = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final OffsetDateTime localStart = localBase.withMinute(localBase.getMinute() - localBase.getMinute() % 5);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(5).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 9
Project: oauth-filter-for-java   File: JwkManager.java   View Source Code Vote up 5 votes
private void ensureCacheIsFresh()
{
    _logger.info("Called ensureCacheIsFresh");

    Instant lastLoading = _jsonWebKeyByKID.getLastReloadInstant().orElse(Instant.MIN);
    boolean cacheIsNotFresh = lastLoading.isBefore(Instant.now()
            .minus(_jsonWebKeyByKID.getMinTimeBetweenReloads()));

    if (cacheIsNotFresh)
    {
        _logger.info("Invalidating JSON WebKeyID cache");

        _jsonWebKeyByKID.clear();
    }
}
 
Example 10
Project: ProjectAres   File: TimeUtils.java   View Source Code Vote up 5 votes
public static Duration duration(Instant start, Instant end) {
    if(isInfPast(start) || isInfFuture(end)) {
        return INF_POSITIVE;
    } else if(start.isBefore(end)) {
        return Duration.between(start, end);
    } else {
        return Duration.ZERO;
    }
}
 
Example 11
Project: ProjectAres   File: InactivePlayerListener.java   View Source Code Vote up 5 votes
@Override
public void tick() {
    final Duration timeout = config.timeout();
    final Duration warning = config.warning();

    Instant now = Instant.now();
    Instant kickTime = now.minus(timeout);
    Instant warnTime = warning == null ? null : now.minus(warning);
    Instant lastWarnTime = warning == null || lastCheck == null ? null : lastCheck.minus(warning);

    // Iterate over a copy, because kicking players while iterating the original
    // OnlinePlayerMapAdapter throws a ConcurrentModificationException
    for(Map.Entry<Player, Instant> entry : lastActivity.entrySetCopy()) {
        Player player = entry.getKey();
        Instant time = entry.getValue();

        if(time.isBefore(kickTime)) {
            playerServerChanger.kickPlayer(player, CommonsTranslations.get().t("afk.kick", player));
        } else if(warnTime != null && time.isAfter(lastWarnTime) && !time.isAfter(warnTime)) {
            player.playSound(player.getLocation(), Sound.BLOCK_NOTE_PLING, 1, 1);
            player.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD + CommonsTranslations.get().t(
                "afk.warn", player,
                ChatColor.AQUA.toString() + ChatColor.BOLD +
                    timeout.minus(warning).getSeconds() +
                    ChatColor.RED + ChatColor.BOLD
            ));
        }
    }

    lastCheck = now;
}
 
Example 12
Project: Concierge   File: Session.java   View Source Code Vote up 5 votes
public Session heartbeated(Instant heartbeatedAt) {
  if (heartbeatedAt.isBefore(this.heartbeatedAt)) {
    throw new IllegalArgumentException("Heartbeats should be monotonic");
  }

  return new Session(id, createdAt, heartbeatedAt, heartbeatDelay);
}
 
Example 13
Project: trading4j   File: M15.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localBase = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final OffsetDateTime localStart = localBase.withMinute(localBase.getMinute() - localBase.getMinute() % 15);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(15).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 14
Project: vars-annotation   File: BasicJWTAuthInterceptor.java   View Source Code Vote up 5 votes
private boolean isExpired(Authorization a) {
    try {
        DecodedJWT jwt = JWT.decode(a.getAccessToken());
        Instant iat = jwt.getExpiresAt().toInstant();
        return iat.isBefore(Instant.now());
    }
    catch (Exception e) {
        return true;
    }
}
 
Example 15
Project: pure-bliss-with-pure-java-functions   File: OfflineDevicesJobImpl.java   View Source Code Vote up 4 votes
static boolean shouldSendNotification(Instant jobStart, Instant deviceOffline, Instant lastNotification, List<Duration> thresholds) {
    Optional<Duration> lastPassedThreshold = calculateLastPassedThreshold(deviceOffline, jobStart, thresholds);

    return lastPassedThreshold.isPresent() && (lastNotification.isBefore(deviceOffline) || !lastPassedThreshold.equals(calculateLastPassedThreshold(deviceOffline, lastNotification, thresholds)));
}
 
Example 16
Project: openjdk-jdk10   File: TCKInstant.java   View Source Code Vote up 4 votes
@Test(expectedExceptions=NullPointerException.class)
public void test_isBefore_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.isBefore(null);
}
 
Example 17
Project: charts   File: Helper.java   View Source Code Vote up 4 votes
public static final Instant clamp(final Instant MIN, final Instant MAX, final Instant VALUE) {
    if (VALUE.isBefore(MIN)) return MIN;
    if (VALUE.isAfter(MAX)) return MAX;
    return VALUE;
}
 
Example 18
Project: SensorThingsProcessor   File: ProcessorBatchAggregate.java   View Source Code Vote up 4 votes
private void calculateAggregates(AggregateCombo combo) throws ServiceFailureException, ProcessException {
    Observation lastAggObs = combo.getLastForTarget();

    Instant calcIntervalStart;
    if (lastAggObs == null) {
        Observation firstSourceObs = combo.getFirstForSource();
        if (firstSourceObs == null) {
            LOGGER.debug("No source observations at all for {}.", combo);
            return;
        }
        Instant firstSourceStart = getPhenTimeStart(firstSourceObs);

        ZonedDateTime atZone = firstSourceStart.atZone(combo.getZoneId());
        ZonedDateTime firstIntStart = combo.level.toIntervalStart(atZone);
        if (atZone.isEqual(firstIntStart)) {
            calcIntervalStart = firstIntStart.toInstant();
        } else {
            calcIntervalStart = firstIntStart.plus(combo.level.duration).toInstant();
        }

    } else {
        TimeObject lastAggPhenTime = lastAggObs.getPhenomenonTime();
        calcIntervalStart = lastAggPhenTime.getAsInterval().getEnd();
    }
    Observation lastSourceObs = combo.getLastForSource();
    if (lastSourceObs == null) {
        LOGGER.debug("No source observations at all for {}.", combo);
        return;
    }
    Instant lastSourcePhenTime = getPhenTimeEnd(lastSourceObs);

    boolean more = true;
    while (more) {
        Instant calcIntervalEnd = calcIntervalStart.plus(combo.level.duration);

        if (lastSourcePhenTime.isBefore(calcIntervalEnd)) {
            LOGGER.info("Nothing (more) to do for {}.", combo);
            return;
        }

        calculateAggregate(combo, Interval.of(calcIntervalStart, calcIntervalEnd));
        calcIntervalStart = calcIntervalEnd;
    }

}
 
Example 19
Project: ProjectAres   File: TimeUtils.java   View Source Code Vote up 4 votes
public static boolean isEqualOrAfterNow(Instant now, Instant instant) {
    return !instant.isBefore(now);
}
 
Example 20
Project: rskj   File: HashRateCalculator.java   View Source Code Vote up 4 votes
private boolean checkBlockTimeRange(BlockHeaderElement element, Instant from, Instant upto) {
    Instant ts = Instant.ofEpochSecond(element.getBlockHeader().getTimestamp());
    return !ts.isBefore(from) && !ts.isAfter(upto);
}