Java Code Examples for java.time.Instant#isAfter()
The following examples show how to use
java.time.Instant#isAfter() .
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: FederationAuthenticator.java From cxf-fediz with Apache License 2.0 | 6 votes |
protected boolean validateToken(Request request, HttpServletResponse response, FedizContext fedConfig) { Session session = request.getSessionInternal(); if (session != null) { FedizResponse wfRes = (FedizResponse)session.getNote(FEDERATION_NOTE); Instant tokenExpires = wfRes.getTokenExpires(); if (tokenExpires == null) { LOG.debug("Token doesn't expire"); return true; } Instant currentTime = Instant.now(); if (!currentTime.isAfter(tokenExpires)) { return true; } else { LOG.warn("Token already expired. Clean up and redirect"); session.removeNote(FEDERATION_NOTE); session.setPrincipal(null); request.getSession().removeAttribute(SECURITY_TOKEN); } } else { LOG.debug("Session should not be null after authentication"); } return false; }
Example 2
Source File: HazelcastTransactionManager.java From jstarcraft-core with Apache License 2.0 | 6 votes |
@Override protected void unlock(TransactionDefinition definition) { Instant now = Instant.now(); String name = definition.getName(); final IMap<String, HazelcastTransactionDefinition> store = getStore(); try { store.lock(name); HazelcastTransactionDefinition current = store.get(name); if (current == null) { throw new TransactionUnlockException(); } else if (now.isAfter(current.getMost())) { throw new TransactionUnlockException(); } else { store.remove(name); } } finally { store.unlock(name); } }
Example 3
Source File: SiteEmailNotificationAnnc.java From sakai with Educational Community License v2.0 | 6 votes |
/** * @inheritDoc */ public void notify(Notification notification, Event event) { // get the message Reference ref = entityManager.newReference(event.getResource()); AnnouncementMessageEdit msg = (AnnouncementMessageEdit) ref.getEntity(); AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader(); // do not do notification for hidden (draft) messages if (hdr.getDraft()) return; // Put here since if release date after now, do not notify // since scheduled notification has been set. Instant now = Instant.now(); if (now.isAfter(hdr.getInstant())) { super.notify(notification, event); } }
Example 4
Source File: HCSSamplerResult.java From hedera-mirror-node with Apache License 2.0 | 6 votes |
public void validateResponse(T currentResponse) { if (last != null) { Instant lastConsensusInstant = getConsensusInstant(last); Instant currentConsensusInstant = getConsensusInstant(currentResponse); long lastSequenceNumber = getSequenceNumber(last); long currentSequenceNumber = getSequenceNumber(currentResponse); log.trace("Observed message: {}, consensus timestamp: {}, topic sequence number: {}", getMessage(currentResponse), currentConsensusInstant, currentSequenceNumber); if (currentSequenceNumber != lastSequenceNumber + 1) { log.error("Out of order message sequence. Last : {}, current : {}", last, currentResponse); throw new IllegalArgumentException("Out of order message sequence. Expected " + (lastSequenceNumber + 1) + " got " + currentSequenceNumber); } if (!currentConsensusInstant.isAfter(lastConsensusInstant)) { log.error("Out of order message sequence. Last : {}, current : {}", last, currentResponse); throw new IllegalArgumentException("Out of order message timestamp. Expected " + currentConsensusInstant + " to be after " + lastConsensusInstant); } } }
Example 5
Source File: StatsController.java From flow-platform-x with Apache License 2.0 | 5 votes |
private boolean isValidDuration(int from, int to) { Instant f = DateHelper.toInstant(from); Instant t = DateHelper.toInstant(to); if (f.isAfter(t)) { return false; } if (f.plus(MaxDays, ChronoUnit.DAYS).isAfter(t)) { return false; } return true; }
Example 6
Source File: TimeUtil.java From digdag with Apache License 2.0 | 5 votes |
public static String formatTimeWithDiff(Instant now, Instant instant) { String time = FORMATTER.withZone(ZoneId.systemDefault()).format(instant); String diff = formatTimeDiff(now, instant); boolean future = instant.isAfter(now); if (future) { return time + " (in " + diff + ")"; } else { return time + " (" + diff + " ago)"; } }
Example 7
Source File: DimmerSwitchHandler.java From smarthome with Eclipse Public License 2.0 | 5 votes |
@Override protected void doSensorStateChanged(@Nullable HueBridge bridge, FullSensor sensor, Configuration config) { ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime now = ZonedDateTime.now(zoneId), timestamp = now; Object lastUpdated = sensor.getState().get(STATE_LAST_UPDATED); if (lastUpdated != null) { try { timestamp = ZonedDateTime.ofInstant( LocalDateTime.parse(String.valueOf(lastUpdated), DateTimeFormatter.ISO_LOCAL_DATE_TIME), ZoneOffset.UTC, zoneId); } catch (DateTimeParseException e) { // do nothing } } Object buttonState = sensor.getState().get(FullSensor.STATE_BUTTON_EVENT); if (buttonState != null) { String value = String.valueOf(buttonState); updateState(CHANNEL_DIMMER_SWITCH, new DecimalType(value)); Instant then = timestamp.toInstant(); Instant someSecondsEarlier = now.minusNanos(refreshIntervalInNanos).toInstant(); if (then.isAfter(someSecondsEarlier) && then.isBefore(now.toInstant())) { triggerChannel(EVENT_DIMMER_SWITCH, value); } } }
Example 8
Source File: Scheduler.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
public Task createDelayedTask(Instant when, Runnable task) { final Instant now = Instant.now(); if(when.isAfter(Instant.now())) { return createDelayedTask(Duration.between(now, when), task); } else { return createTask(task); } }
Example 9
Source File: JwtToken.java From vipps-developers with MIT License | 5 votes |
private void verifyTimeValidity(Instant now) { boolean earliestTime = now.isBefore(nbf().orElse(authTime().orElse(Instant.EPOCH))); if (earliestTime) { throw new JwtTokenValidationException("JWT not valid yet! " + earliestTime + " " + payload); } if (now.isAfter(exp())) { throw new JwtTokenValidationException("JWT not valid yet! " + exp() + " " + payload); } }
Example 10
Source File: FeedbackSessionAttributes.java From teammates with GNU General Public License v2.0 | 5 votes |
/** * Returns {@code true} if the session is visible; {@code false} if not. * Does not care if the session has started or not. */ public boolean isVisible() { Instant visibleTime = this.sessionVisibleFromTime; if (visibleTime.equals(Const.TIME_REPRESENTS_FOLLOW_OPENING)) { visibleTime = this.startTime; } Instant now = Instant.now(); return now.isAfter(visibleTime) || now.equals(visibleTime); }
Example 11
Source File: Updater.java From osm-lib with BSD 2-Clause "Simplified" License | 5 votes |
/** * This is the main entry point. Give it an OSM database and it will keep it up to date in a new thread. */ public static Thread spawnUpdateThread(OSM osm) { Thread updateThread = new Thread(new Updater(osm)); Instant initialTimestamp = Instant.ofEpochSecond(osm.timestamp.get()); if (initialTimestamp.isBefore(MIN_REPLICATION_INSTANT) || initialTimestamp.isAfter(MAX_REPLICATION_INSTANT)) { LOG.error("OSM database timestamp seems incorrect: {}", initialTimestamp.toString()); LOG.error("Not running the minutely updater thread."); } else { updateThread.start(); } return updateThread; }
Example 12
Source File: LessonBuilderAccessService.java From sakai with Educational Community License v2.0 | 5 votes |
protected boolean isAvailable(ContentEntity entity) { Instant now = Instant.now(); Instant releaseDate = entity.getReleaseInstant(); if (releaseDate != null && ! releaseDate.isBefore(now)) return false; Instant retractDate = entity.getRetractInstant(); if (retractDate != null && ! retractDate.isAfter(now)) return false; ContentEntity parent = (ContentEntity)entity.getContainingCollection(); if (parent != null) return isAvailable(parent); else return true; }
Example 13
Source File: JwtUtils.java From cxf with Apache License 2.0 | 5 votes |
public static void validateJwtIssuedAt(JwtClaims claims, int timeToLive, int clockOffset, boolean claimRequired) { Long issuedAtInSecs = claims.getIssuedAt(); if (issuedAtInSecs == null) { if (claimRequired) { throw new JwtException("Invalid issuedAt"); } return; } Instant createdDate = Instant.ofEpochMilli(issuedAtInSecs * 1000L); Instant validCreation = Instant.now(); if (clockOffset != 0) { validCreation = validCreation.plusSeconds(clockOffset); } // Check to see if the IssuedAt time is in the future if (createdDate.isAfter(validCreation)) { throw new JwtException("Invalid issuedAt"); } if (timeToLive > 0) { // Calculate the time that is allowed for the message to travel validCreation = validCreation.minusSeconds(timeToLive); // Validate the time it took the message to travel if (createdDate.isBefore(validCreation)) { throw new JwtException("Invalid issuedAt"); } } }
Example 14
Source File: SimpleRegionNormalizer.java From hbase with Apache License 2.0 | 4 votes |
/** * Return {@code true} when {@code regionInfo} has a creation date that is old * enough to be considered for a merge operation, {@code false} otherwise. */ private boolean isOldEnoughForMerge(final RegionInfo regionInfo) { final Instant currentTime = Instant.ofEpochMilli(EnvironmentEdgeManager.currentTime()); final Instant regionCreateTime = Instant.ofEpochMilli(regionInfo.getRegionId()); return currentTime.isAfter(regionCreateTime.plus(mergeMinRegionAge)); }
Example 15
Source File: AbstractRequestAssertionConsumerHandler.java From cxf with Apache License 2.0 | 4 votes |
protected boolean isStateExpired(long stateCreatedAt, long expiresAt) { Instant currentTime = Instant.now(); return expiresAt > 0 && currentTime.isAfter(Instant.ofEpochMilli(stateCreatedAt + expiresAt)); }
Example 16
Source File: PlayerListener.java From ProjectAres with GNU Affero General Public License v3.0 | 4 votes |
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onLogin(UserLoginEvent event) { final User user = event.getUser(); final Player player = event.getPlayer(); final Audience audience = audiences.get(player); audience.sendMessage(Components.blank()); audience.sendMessage( new HeaderComponent( new Component(GREEN).translate("welcome", generalFormatter.brandName()) ) ); audience.sendMessage( new Component(DARK_AQUA) .translate( "welcome.instructions", new Component(AQUA).translate("servers.lobby"), new Component(GOLD).translate("welcome.sign"), new Component(GREEN).translate("navigator.title") ) ); if(user.trial_expires_at() != null) { final Instant expires = TimeUtils.toInstant(user.trial_expires_at()); final Instant now = Instant.now(); if(expires.isAfter(now)) { long days = TimeUtils.daysRoundingUp(Duration.between(now, expires)); final String key; if(days <= 1) { key = "trial.remaining.singular"; days = 1; } else { key = "trial.remaining.plural"; } audience.sendMessage( new Component(DARK_PURPLE) .translate( key, new Component(LIGHT_PURPLE).translate("trial.freeTrial"), new Component(days, LIGHT_PURPLE) ) .extra(" ") .translate( "trial.details", new Component(LIGHT_PURPLE).translate("trial.joinFull"), new Component(LIGHT_PURPLE).translate("trial.chooseTeam") ) .extra(" ") .translate( "trial.upgrade", Links.shopLink() ) ); } } audience.sendMessage(new HeaderComponent( new Component(ChatColor.GREEN) .translate( "welcome.visitWebsite", Links.homeLink() ) )); }
Example 17
Source File: Archiver.java From Openfire with Apache License 2.0 | 4 votes |
/** * Returns an estimation on how long it takes for all data that arrived before a certain instant will have become * available in the data store. When data is immediately available, 'zero', is returned; * * This method is intended to be used to determine if it's safe to construct an answer (based on database * content) to a request for archived data. Such response should only be generated after all data that was * queued before the request arrived has been written to the database. * * This method performs a check on the local cluster-node only, unlike {@link #availabilityETA(Instant)}. * * @param instant The timestamp of the data that should be available (cannot be null). * @return A period of time, zero when the requested data is already available. */ public Duration availabilityETAOnLocalNode( final Instant instant ) { if ( instant == null ) { throw new IllegalArgumentException( "Argument 'instant' cannot be null." ); } final Instant now = Instant.now(); // If the date of interest is in the future, data might still arrive. if ( instant.isAfter( now ) ) { final Duration result = Duration.between( now, instant ).plus( gracePeriod ); Log.debug( "The timestamp that's requested ({}) is in the future. It's unpredictable if more data will become available. Data writes cannot have finished until the requested timestamp plus the grace period, which is in {}", instant, result ); return result; } // If the last message that's processed is newer than the instant that we're after, all of the // data that is of interest must have been written. if ( lastProcessed != null && lastProcessed.isAfter( instant ) ) { Log.debug( "Creation date of last logged data ({}) is younger than the timestamp that's requested ({}). Therefor, all data must have already been written.", lastProcessed, instant ); return Duration.ZERO; } // If the date of interest is not in the future, the queue is empty, and // no data is currently being worked on, then all data has been written. if ( queue.isEmpty() && workQueue.isEmpty() ) { Log.debug( "The timestamp that's requested ({}) is not in the future. All data must have already been received. There's no data queued or being worked on. Therefor, all data must have already been written.", instant ); return Duration.ZERO; } if ( queue.isEmpty() ) { Log.trace( "Cannot determine with certainty if all data that arrived before {} has been written. The queue of pending writes is empty. Unless new data becomes available, the next write should occur within {}", instant, gracePeriod ); return gracePeriod; } else { Log.trace( "Cannot determine with certainty if all data that arrived before {} has been written. The queue of pending writes contains data, which can be an indication of high load. A write should have occurred within {}", instant, maxPurgeInterval ); return maxPurgeInterval; } }
Example 18
Source File: TimeRoutedAlias.java From lucene-solr with Apache License 2.0 | 4 votes |
@Override public void validateRouteValue(AddUpdateCommand cmd) throws SolrException { final Instant docTimestamp = parseRouteKey(cmd.getSolrInputDocument().getFieldValue(getRouteField())); // FUTURE: maybe in some cases the user would want to ignore/warn instead? if (docTimestamp.isAfter(Instant.now().plusMillis(getMaxFutureMs()))) { throw new SolrException(BAD_REQUEST, "The document's time routed key of " + docTimestamp + " is too far in the future given " + ROUTER_MAX_FUTURE + "=" + getMaxFutureMs()); } // Although this is also checked later, we need to check it here too to handle the case in Dimensional Routed // aliases where one can legally have zero collections for a newly encountered category and thus the loop later // can't catch this. // SOLR-13760 - we need to fix the date math to a specific instant when the first document arrives. // If we don't do this DRA's with a time dimension have variable start times across the other dimensions // and logic gets much to complicated, and depends too much on queries to zookeeper. This keeps life simpler. // I have to admit I'm not terribly fond of the mutation during a validate method however. Instant startTime; try { startTime = Instant.parse(start); } catch (DateTimeParseException e) { startTime = DateMathParser.parseMath(new Date(), start).toInstant(); SolrCore core = cmd.getReq().getCore(); ZkStateReader zkStateReader = core.getCoreContainer().getZkController().zkStateReader; Aliases aliases = zkStateReader.getAliases(); Map<String, String> props = new HashMap<>(aliases.getCollectionAliasProperties(aliasName)); start = DateTimeFormatter.ISO_INSTANT.format(startTime); props.put(ROUTER_START, start); // This could race, but it only occurs when the alias is first used and the values produced // should all be identical and who wins won't matter (baring cases of Date Math involving seconds, // which is pretty far fetched). Putting this in a separate thread to ensure that any failed // races don't cause documents to get rejected. core.runAsync(() -> zkStateReader.aliasesManager.applyModificationAndExportToZk( (a) -> aliases.cloneWithCollectionAliasProperties(aliasName, props))); } if (docTimestamp.isBefore(startTime)) { throw new SolrException(BAD_REQUEST, "The document couldn't be routed because " + docTimestamp + " is before the start time for this alias " +start+")"); } }
Example 19
Source File: BasicExpiringValue.java From hono with Eclipse Public License 2.0 | 4 votes |
@Override public boolean isExpired(final Instant now) { Objects.requireNonNull(now); return now.isAfter(expirationTime); }
Example 20
Source File: CredentialsObject.java From hono with Eclipse Public License 2.0 | 3 votes |
/** * Checks if a given instant of time falls into a secret's validity period. * * @param secret The secret to check against. * @param instant The instant of time. * @return {@code true} if the instant falls into the secret's validity period. */ public static boolean isInValidityPeriod(final JsonObject secret, final Instant instant) { final Instant notBefore = CredentialsObject.getNotBefore(secret); final Instant notAfter = CredentialsObject.getNotAfter(secret); return (notBefore == null || instant.isAfter(notBefore)) && (notAfter == null || instant.isBefore(notAfter)); }