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

The following are Jave code examples for showing how to use isAfter() 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.
Example 1
Project: ProjectAres   File: QuotaMatchModule.java   Source Code and License Vote up 6 votes
public QuotaStatus getQuotaStatus(MatchPlayer player, Quota quota, Instant now) {
    Duration interval = quota.interval();

    QuotaStatus status = new QuotaStatus(quota, now);
    status.matchesPlayed = 0;
    status.earliestJoinTime = now;

    // Note that this list is reverse-chrono order
    for(Instant joinTime : player.recentMatchCommitments()) {
        Instant expireTime = joinTime.plus(interval);
        if(expireTime.isAfter(now)) {
            if(++status.matchesPlayed == quota.maximum()) {
                status.earliestJoinTime = expireTime;
            }
        } else {
            break;
        }
    }

    return status;
}
 
Example 2
Project: trellis-rosid-file   File: RDFPatch.java   Source Code and License Vote up 6 votes
private void tryAdvance() {
    Instant time = null;
    while (allLines.hasNext()) {
        final String line = allLines.next();
        if (line.startsWith(MODIFIED_HEADER)) {
            time = modifiedToInstant(line);
            hasUserTriples = false;
        } else if (isUserTripleQuad(line)) {
            hasUserTriples = true;
        } else if (line.startsWith(TX_COMMIT) && hasUserTriples && nonNull(time)) {
            if (nonNull(from)) {
                if (time.isAfter(from.truncatedTo(MILLIS))) {
                    buffer = new VersionRange(from, time);
                    from = time;
                }
                return;
            }
            from = time;
        }
    }
    buffer = null;
}
 
Example 3
Project: swblocks-decisiontree   File: DatedTreeNode.java   Source Code and License 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 4
Project: ProjectAres   File: RestartListener.java   Source Code and License Vote up 6 votes
private boolean canRestart(int playerCount) {
    // If server is on public DNS, it cannot restart
    if(localServer.dns_enabled()) {
        logger.info("Deferring restart because server is on public DNS");
        return false;
    }

    // If we are still waiting for the server to empty, it cannot restart
    final Instant deadline = localServer.dns_toggled_at().plus(config.emptyTimeout());
    if(playerCount > 0 && deadline.isAfter(Instant.now())) {
        logger.info("Deferring restart until the server empties or until " + deadline + ", whichever is first");
        task.schedule(Task.Parameters.fromInstant(deadline));
        return false;
    }

    // If we have given up waiting for the server to empty, it can restart.
    // However, the kick-limit enforced by RestartManager may still prevent it from restarting.
    return true;
}
 
Example 5
Project: trading4j   File: M15.java   Source Code and License 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 6
Project: fernet-java8   File: ProtocolBuffersExampleIT.java   Source Code and License Vote up 5 votes
/**
 * Renew a session 
 *
 * @param sessionId the existing session ID
 * @param tokenString a current valid Fernet token
 * @return a new Fernet token with the updated session state embedded
 */
@PUT
@Path("/api/sessions/{sessionId}/renewal")
public String renew(@PathParam("sessionId") final String sessionId, final String tokenString,
        @Context final HttpServletResponse servletResponse) {
    final Token inputToken = Token.fromString(tokenString);
    final Session session = inputToken.validateAndDecrypt(key, validator);
    if (!Objects.equals(sessionId, session.getSessionId())) {
        throw new BadRequestException("SessionID mismatch.");
    }

    final Instant lastRenewed = Instant.ofEpochSecond(session.getLastRenewalTime());
    if (session.hasLastRenewalTime() && lastRenewed.isAfter(Instant.now().minus(Duration.ofMinutes(1)))) {
        // prevent denial-of-service
        // if token was renewed less than a minute ago, tell the client to back off
        servletResponse.addHeader("Retry-After", "60");
        // Too Many Requests: https://tools.ietf.org/html/rfc6585#section-4
        throw new WebApplicationException("Try again in a minute", 429);
    }

    // The token and session are valid, now update the session
    final Builder builder = Session.newBuilder(session);
    builder.setRenewalCount(session.getRenewalCount() + 1);
    builder.setLastRenewalTime(Instant.now().getEpochSecond());
    final Session updatedSession = builder.build();
    // store the updated session in a new Fernet token
    final Token retval = Token.generate(random, key, updatedSession.toByteArray());
    return retval.serialise();
}
 
Example 7
Project: tsc-reload   File: ReloadableConfig.java   Source Code and License Vote up 5 votes
@Override
public synchronized void notifyChanged(Instant now) {
    ConfigWithTimestamps current = configWithTimestamps;
    if (now.isAfter(current.getLastCheck().plus(checkInterval))) {
        optionalLastModified()
                .filter(lastModified -> lastModified.isAfter(current.getLastModified()))
                .map(lastModifiedAfterCurrent -> invalidateCache(lastModifiedAfterCurrent, now))
                .orElseGet(() -> {
                    configWithTimestamps = current.withLastCheck(now);
                    return null;
                });
    }
}
 
Example 8
Project: aws-sdk-java-v2   File: StsCredentialsProviderTestBase.java   Source Code and License Vote up 5 votes
@Test
public void distantExpiringCredentialsUpdatedInBackground() throws InterruptedException {
    callClientWithCredentialsProvider(Instant.now().plusSeconds(90), 2);

    Instant endCheckTime = Instant.now().plus(Duration.ofSeconds(5));
    while (Mockito.mockingDetails(stsClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) {
        Thread.sleep(100);
    }

    callClient(verify(stsClient, times(2)), Mockito.any());
}
 
Example 9
Project: CalendarFX   File: IntervalTree.java   Source Code and License Vote up 5 votes
public TimeInterval(Instant startTime, Instant endTime) {
    requireNonNull(startTime);
    requireNonNull(endTime);

    if (startTime.isAfter(endTime)) {
        throw new IllegalArgumentException(
                "start time can not be after end time, start = " //$NON-NLS-1$
                        + startTime + ", end = " + endTime); //$NON-NLS-1$
    }

    this.startTime = startTime;
    this.endTime = endTime;
}
 
Example 10
Project: ProjectAres   File: InactivePlayerListener.java   Source Code and License 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 11
Project: trading4j   File: M30.java   Source Code and License 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() % 30);

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

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 12
Project: trading4j   File: H1.java   Source Code and License Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localStart = instant1.atOffset(UTC).withMinute(0).withSecond(0).withNano(0);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusHours(1).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 13
Project: trading4j   File: M1.java   Source Code and License Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localStart = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(1).toInstant();
    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 14
Project: trading4j   File: D1.java   Source Code and License Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {

    final ZonedDateTime britishTime = instant1.atZone(BRITISH_TIME_ZONE);
    final DayOfWeek britishDay = britishTime.getDayOfWeek();

    final ZonedDateTime localBase = britishTime.withHour(0).withMinute(0).withSecond(0).withNano(0);

    final ZonedDateTime start;
    final ZonedDateTime end;

    if (britishDay == SUNDAY) {
        if (britishTime.isBefore(localBase.withHour(22))) {
            start = localBase;
            end = localBase.withHour(22);
        } else {
            start = localBase.withHour(22);
            end = localBase.plusDays(2);
        }
    } else if (britishDay == MONDAY) {
        start = localBase.minusDays(1).withHour(22);
        end = localBase.plusDays(1);
    } else {
        start = localBase;
        end = localBase.plusDays(1);
    }

    return instant2.equals(start.toInstant())
            || (instant2.isAfter(start.toInstant()) && instant2.isBefore(end.toInstant()));
}
 
Example 15
Project: sample.microservices.security.jwt   File: JwtUserDetails.java   Source Code and License Vote up 5 votes
@Override
public boolean isCredentialsNonExpired() {
    //consider the credentials as expired once the token expiry time has passed
    //remember to keep all times in UTC, and optionally allow an extra amount
    //to accomodate clock drift.

    Instant now = Instant.now();

    //for now, assume issued AND expiry are set, we do control the jwt creation =)
    Instant expiry = Instant.ofEpochSecond(jwt.getClaims().getExpiration());
    Instant issuedAt = Instant.ofEpochSecond(jwt.getClaims().getIssuedAt());

    return now.isAfter(issuedAt) && now.isBefore(expiry);
}
 
Example 16
Project: EpiStats   File: DataCollection.java   Source Code and License Vote up 4 votes
public synchronized void add(Map<String, Map<String, Double>> stats, UUID id, String name, String guild, Instant date) {
	if (this.size >= this.capacity)
		throw new IndexOutOfBoundsException("Capacity: " + this.capacity);
	if (this.startDates != null)
		throw new UnsupportedOperationException();
	if (id == null || name == null || date == null)
		throw new IllegalArgumentException();
	if (this.players.containsKey(id))
		throw new IllegalArgumentException("Already added");

	this.players.put(id, this.size);

	if (stats != null) {
		for (Entry<String, Map<String, Double>> e : stats.entrySet()) {
			Map<String, DoubleList> section = this.stats.get(e.getKey());
			if (section == null) {
				section = new HashMap<>();
				this.stats.put(e.getKey(), section);
			}

			for (Entry<String, Double> stat : e.getValue().entrySet()) {
				DoubleList list = section.get(stat.getKey());
				if (list == null) {
					list = new DoubleList(this.capacity);
					section.put(stat.getKey(), list);
				}

				list.set(this.size, stat.getValue());
			}
		}
	}

	this.ids.add(id);
	this.names.add(name);
	this.guilds.add(guild);
	this.endDates.add(date);

	if (this.minEndDate == null || date.isBefore(this.minEndDate))
		this.minEndDate = date;
	if (this.maxEndDate == null || date.isAfter(this.maxEndDate))
		this.maxEndDate = date;

	this.size++;
}
 
Example 17
Project: openjdk-jdk10   File: TCKInstant.java   Source Code and License Vote up 4 votes
@Test(expectedExceptions=NullPointerException.class)
public void test_isAfter_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.isAfter(null);
}
 
Example 18
Project: cryptotrader   File: TraderImpl.java   Source Code and License Vote up 4 votes
@VisibleForTesting
Duration calculateInterval(Instant target) {

    if (target == null) {
        return Duration.ZERO;
    }

    Instant now = propertyManager.getNow();

    if (now.isAfter(target)) {
        return Duration.ZERO;
    }

    return Duration.between(now, target);

}
 
Example 19
Project: jdk8u-jdk   File: TCKInstant.java   Source Code and License Vote up 4 votes
@Test(expectedExceptions=NullPointerException.class)
public void test_isAfter_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.isAfter(null);
}
 
Example 20
Project: ProjectAres   File: TimeUtils.java   Source Code and License Vote up 4 votes
public static boolean isEqualOrBeforeNow(Instant now, Instant instant) {
    return !instant.isAfter(now);
}