Java Code Examples for java.time.Instant#isBefore()
The following examples show how to use
java.time.Instant#isBefore() .
These examples are extracted from open source projects.
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 Project: plugins File: GrandExchangePlugin.java License: GNU General Public License v3.0 | 5 votes |
private void setLimitResetTime(int itemId) { Instant lastDateTime = configManager.getConfiguration(GrandExchangeConfig.CONFIG_GROUP, BUY_LIMIT_KEY + client.getUsername().toLowerCase() + "." + itemId, Instant.class); if (lastDateTime == null || lastDateTime.isBefore(Instant.now())) { configManager.setConfiguration(GrandExchangeConfig.CONFIG_GROUP, BUY_LIMIT_KEY + client.getUsername().toLowerCase() + "." + itemId, Instant.now().plus(BUY_LIMIT_RESET)); } }
Example 2
Source Project: sakai File: LessonBuilderAccessService.java License: 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 3
Source Project: vipps-developers File: JwtToken.java License: 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 4
Source Project: spring-analysis-note File: DefaultServerWebExchange.java License: MIT License | 5 votes |
private boolean validateIfUnmodifiedSince(Instant lastModified) { if (lastModified.isBefore(Instant.EPOCH)) { return false; } long ifUnmodifiedSince = getRequestHeaders().getIfUnmodifiedSince(); if (ifUnmodifiedSince == -1) { return false; } // We will perform this validation... Instant sinceInstant = Instant.ofEpochMilli(ifUnmodifiedSince); this.notModified = sinceInstant.isBefore(lastModified.truncatedTo(ChronoUnit.SECONDS)); return true; }
Example 5
Source Project: hono File: ValidityOnlyTrustManagerFactory.java License: Eclipse Public License 2.0 | 5 votes |
@Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { if (chain == null) { throw new NullPointerException("certificate chain must not be null"); } else if (chain.length < 1) { throw new IllegalArgumentException("certificate chain must not be empty"); } else { final X509Certificate deviceCert = chain[0]; final Instant notBefore = deviceCert.getNotBefore().toInstant(); final Instant notAfter = deviceCert.getNotAfter().toInstant(); final Instant now = Instant.now(); if (now.isBefore(notBefore)) { throw new CertificateNotYetValidException(); } else if (now.isAfter(notAfter)) { throw new CertificateExpiredException(); } else { // certificate is valid, defer further checks to application layer // where the certificate's signature should be validated using the // tenant's root CA certificate if (LOG.isDebugEnabled()) { LOG.debug("accepting client certificate [not before: {}, not after: {}, issuer DN: {}]", notBefore, notAfter, deviceCert.getIssuerX500Principal().getName(X500Principal.RFC2253)); } } } }
Example 6
Source Project: smarthome File: DimmerSwitchHandler.java License: 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 7
Source Project: taskana File: TaskCleanupJob.java License: Apache License 2.0 | 5 votes |
private Instant getNextDueForTaskCleanupJob() { Instant nextRunAt = firstRun; while (nextRunAt.isBefore(Instant.now())) { nextRunAt = nextRunAt.plus(runEvery); } LOGGER.info("Scheduling next run of the TaskCleanupJob for {}", nextRunAt); return nextRunAt; }
Example 8
Source Project: ProjectAres File: MonostableFilter.java License: GNU Affero General Public License v3.0 | 5 votes |
boolean matches(F filterable, boolean response) { if(response) { final Instant now = match.getInstantNow(); final Instant end = endTimes.computeIfAbsent(filterable, f -> { invalidate(filterable); return now.plus(duration); }); return now.isBefore(end); } else { if(endTimes.remove(filterable) != null) { invalidate(filterable); } return false; } }
Example 9
Source Project: ts-reaktive File: MaterializerActor.java License: MIT License | 5 votes |
public CreateWorker(Instant timestamp, Option<Instant> endTimestamp) { this.timestamp = timestamp; this.endTimestamp = endTimestamp; for (Instant end: endTimestamp) { if (!timestamp.isBefore(end)) { throw new IllegalArgumentException("endTimestamp must be after timestamp if given"); } } }
Example 10
Source Project: taskana File: WorkbasketCleanupJob.java License: Apache License 2.0 | 5 votes |
private Instant getNextDueForWorkbasketCleanupJob() { Instant nextRunAt = firstRun; while (nextRunAt.isBefore(Instant.now())) { nextRunAt = nextRunAt.plus(runEvery); } LOGGER.info("Scheduling next run of the WorkbasketCleanupJob for {}", nextRunAt); return nextRunAt; }
Example 11
Source Project: styx File: KubernetesDockerRunner.java License: Apache License 2.0 | 5 votes |
private boolean isNonDeletePeriodExpired(ContainerStatus cs) { final ContainerStateTerminated t = cs.getState().getTerminated(); if (t.getFinishedAt() == null) { return true; } final Instant finishedAt; try { finishedAt = Instant.parse(t.getFinishedAt()); } catch (DateTimeParseException e) { LOG.warn("Failed to parse container state terminated finishedAt: '{}'", t.getFinishedAt(), e); return true; } final Instant deadline = time.get().minus(podDeletionDelay); return finishedAt.isBefore(deadline); }
Example 12
Source Project: ts-reaktive File: MaterializerWorkers.java License: MIT License | 5 votes |
/** * Applies a worker reporting back timestamp progress. * * @param timestamp The timestamp that the worker has completed processing on. * * @return An event to emit with the new restart indexes. In case the worker was done, it will * be absent from the emitted event. */ // FIXME inject Now() into this as a parameter public MaterializerActorEvent onWorkerProgress(UUID workerId, Instant timestamp) { int index = workers.map(Worker::getId).indexOf(toProtobuf(workerId)); if (index == -1) { log.warn("Progress for unknown worker: {}, ignoring.", workerId); return unchanged(); } Worker worker = workers.apply(index); if (worker.hasEndTimestamp() && timestamp.toEpochMilli() >= worker.getEndTimestamp()) { return toEvent(workers.removeAt(index)); } else if (timestamp.toEpochMilli() <= worker.getTimestamp()) { // New timestamp is in the past -> ignore it return unchanged(); } else { // We're now positively done with timestamp [o]. // If [o] is long enough ago, we can start with [o+1] next time. Otherwise, we start again at now() minus rollback. Instant now = Instant.now(); long newTimestamp; if (timestamp.isBefore(now.minus(rollback))) { newTimestamp = timestamp.toEpochMilli() + 1; } else { newTimestamp = now.minus(rollback).toEpochMilli(); } if (index < workers.size() - 1 && newTimestamp >= workers.apply(index + 1).getTimestamp()) { // We're done after all, since we're beyond the next worker's start timestamp return toEvent(workers.removeAt(index)); } return toEvent(workers.update(index, worker.toBuilder() .setTimestamp(newTimestamp) .build() )); } }
Example 13
Source Project: ProjectAres File: TimeUtils.java License: GNU Affero General Public License v3.0 | 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 14
Source Project: openjdk-8 File: TCKInstant.java License: GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=NullPointerException.class) public void test_isBefore_ObjectNull() { Instant a = Instant.ofEpochSecond(0L, 0); a.isBefore(null); }
Example 15
Source Project: airsonic-advanced File: MultipleCredsMatchingAuthenticationProvider.java License: GNU General Public License v3.0 | 4 votes |
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials().toString(); String encoderSpecialization = (authentication.getCredentials() instanceof SaltToken) ? SALT_TOKEN_MECHANISM_SPECIALIZATION : ""; if (!UserDetail.class.isAssignableFrom(userDetails.getClass())) { throw new InternalAuthenticationServiceException("Retrieved user does not match expected class"); } UserDetail userDetail = (UserDetail) userDetails; Optional<UserCredential> matchedCred = userDetail.getCredentials().parallelStream() .filter(c -> getPasswordEncoder().matches(presentedPassword, "{" + c.getEncoder() + encoderSpecialization + "}" + c.getCredential())) .findAny(); if (!matchedCred.isPresent()) { logger.debug("Authentication failed: password does not match any stored values"); throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } Instant expiration = matchedCred.map(UserCredential::getExpiration).orElse(null); if (expiration != null && expiration.isBefore(Instant.now())) { logger.debug("User account credentials have expired"); throw new CredentialsExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } // perform upgrade if needed for password-based auth if ("".equals(encoderSpecialization) && getPasswordEncoder().upgradeEncoding("{" + matchedCred.get().getEncoder() + "}" + matchedCred.get().getCredential())) { UserCredential upgraded = new UserCredential(matchedCred.get()); upgraded.setCredential(authentication.getCredentials().toString()); if (!securityService.updateCredentials(matchedCred.get(), upgraded, upgraded.getComment() + " | Automatically upgraded by system", true)) { logger.debug("Password needs to be upgraded, but failed"); } } }
Example 16
Source Project: sakai File: ConnectorHelper.java License: Educational Community License v2.0 | 4 votes |
public List getAssignments(){ Vector returnAssignmentList = new Vector(); if(!userKnown) return new Vector(); Iterator siteIterator = sites.iterator(); while(siteIterator.hasNext()){ String placementId = null; Site thisSite = (Site) siteIterator.next(); List thisSitePages = thisSite.getPages(); boolean assignmentToolNotFound = true; Iterator pageIterator = thisSitePages.iterator(); while(pageIterator.hasNext() && assignmentToolNotFound){ SitePage thisPage = (SitePage) pageIterator.next(); List sitePageTools = thisPage.getTools(); Iterator sitePageToolIterator = sitePageTools.iterator(); while(sitePageToolIterator.hasNext() && assignmentToolNotFound){ ToolConfiguration thisToolConfiguration = (ToolConfiguration) sitePageToolIterator.next(); if(thisToolConfiguration.getToolId().equalsIgnoreCase(ASSIGNMENT_TOOL_ID)){ assignmentToolNotFound = false; placementId = thisToolConfiguration.getId(); } } } if(!securityService.unlock(loggedInUserId, "site.upd", "/site/" + thisSite.getId())){ log.info("Assignment - no show"+loggedInUserEid+" is not an instructor."); return returnAssignmentList; } java.util.Date now = new java.util.Date(); for (Assignment thisAssignment : assignmentService.getAssignmentsForContext(thisSite.getId())) { Instant thisAssignmentCloseTime = thisAssignment.getCloseDate(); boolean assignmentClosed = true; if(thisAssignmentCloseTime!=null){ if(thisAssignmentCloseTime.isBefore(Instant.now())){ assignmentClosed=false; } }else{ assignmentClosed=false; } if(thisAssignment.getDraft() | assignmentClosed ) continue; StringBuffer assignmentUrlBuildBuffer = new StringBuffer(); /* assignmentUrlBuildBuffer.append("/portal/tool/"); assignmentUrlBuildBuffer.append(placementId+"?"); assignmentUrlBuildBuffer.append("assignmentReference=/assignment/a/"); assignmentUrlBuildBuffer.append(thisAssignment.getContext()+"/"); assignmentUrlBuildBuffer.append(thisAssignment.getId()); assignmentUrlBuildBuffer.append("&panel=Main&sakai_action=doView_submission"); */ assignmentUrlBuildBuffer.append("/direct/assignment/"); assignmentUrlBuildBuffer.append(thisAssignment.getId()); String[] thisAssignmentDescriptor = new String[2]; thisAssignmentDescriptor[0] = "Assignment in site:"+thisSite.getTitle()+" - "+thisAssignment.getTitle(); thisAssignmentDescriptor[1] = assignmentUrlBuildBuffer.toString(); log.info("Adding assignment:"+assignmentUrlBuildBuffer.toString()); returnAssignmentList.add(thisAssignmentDescriptor); } } return returnAssignmentList; }
Example 17
Source Project: GriefDefender File: CommandClaimAbandon.java License: MIT License | 4 votes |
@CommandAlias("abandon|abandonclaim") @Description("Abandons a claim") @Subcommand("abandon claim") public void execute(Player player) { final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAt(player.getLocation()); final UUID ownerId = claim.getOwnerUniqueId(); GDPermissionUser user = null; if (ownerId != null) { user = PermissionHolderCache.getInstance().getOrCreateUser(ownerId); } else { user = PermissionHolderCache.getInstance().getOrCreateUser(player); } final GDPlayerData playerData = user.getInternalPlayerData(); final boolean isAdmin = playerData.canIgnoreClaim(claim); final boolean isTown = claim.isTown(); if (claim.isWilderness()) { GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().ABANDON_CLAIM_MISSING); return; } else if (!isAdmin && !player.getUniqueId().equals(ownerId) && claim.isUserTrusted(player, TrustTypes.MANAGER)) { if (claim.parent == null) { // Managers can only abandon child claims GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_NOT_YOURS); return; } } else if (!isAdmin && (claim.allowEdit(player) != null || (!claim.isAdminClaim() && !player.getUniqueId().equals(ownerId)))) { GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_NOT_YOURS); return; } else { if (this.abandonTopClaim && claim.children.size() > 0) { if (claim.isTown() || claim.isAdminClaim()) { Set<Claim> invalidClaims = new HashSet<>(); for (Claim child : claim.getChildren(true)) { if (child.getOwnerUniqueId() == null || !child.getOwnerUniqueId().equals(ownerId)) { //return CommandResult.empty(); invalidClaims.add(child); } } if (!invalidClaims.isEmpty()) { GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().ABANDON_TOWN_CHILDREN); CommandHelper.showClaims(player, invalidClaims, 0, true); return; } } } } final int abandonDelay = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Integer.class), user, Options.ABANDON_DELAY, claim); if (abandonDelay > 0) { final Instant localNow = Instant.now(); final Instant dateCreated = claim.getInternalClaimData().getDateCreated(); final Instant delayExpires = dateCreated.plus(Duration.ofDays(abandonDelay)); final boolean delayActive = !delayExpires.isBefore(localNow); if (delayActive) { TextAdapter.sendComponent(player, MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.ABANDON_CLAIM_DELAY_WARNING, ImmutableMap.of("date", Date.from(delayExpires)))); return; } } final boolean autoSchematicRestore = GriefDefenderPlugin.getActiveConfig(player.getWorld().getUID()).getConfig().claim.claimAutoSchematicRestore; final Component confirmationText = TextComponent.builder() .append(autoSchematicRestore ? MessageCache.getInstance().SCHEMATIC_ABANDON_RESTORE_WARNING : MessageCache.getInstance().ABANDON_WARNING) .append(TextComponent.builder() .append("\n[") .append(MessageCache.getInstance().LABEL_CONFIRM.color(TextColor.GREEN)) .append("]\n") .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(player, createConfirmationConsumer(player, user, claim, this.abandonTopClaim), true))) .hoverEvent(HoverEvent.showText(MessageCache.getInstance().UI_CLICK_CONFIRM)).build()) .build(); TextAdapter.sendComponent(player, confirmationText); }
Example 18
Source Project: GriefDefender File: CommandClaimAbandon.java License: MIT License | 4 votes |
@CommandAlias("abandon|abandonclaim") @Description("Abandons a claim") @Subcommand("abandon claim") public void execute(Player player) { final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAt(player.getLocation()); final UUID ownerId = claim.getOwnerUniqueId(); GDPermissionUser user = null; if (ownerId != null) { user = PermissionHolderCache.getInstance().getOrCreateUser(ownerId); } else { user = PermissionHolderCache.getInstance().getOrCreateUser(player); } final GDPlayerData playerData = user.getInternalPlayerData(); final boolean isAdmin = playerData.canIgnoreClaim(claim); final boolean isTown = claim.isTown(); if (claim.isWilderness()) { GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().ABANDON_CLAIM_MISSING); return; } else if (!isAdmin && !player.getUniqueId().equals(ownerId) && claim.isUserTrusted(player, TrustTypes.MANAGER)) { if (claim.parent == null) { // Managers can only abandon child claims GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_NOT_YOURS); return; } } else if (!isAdmin && (claim.allowEdit(player) != null || (!claim.isAdminClaim() && !player.getUniqueId().equals(ownerId)))) { GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_NOT_YOURS); return; } else { if (this.abandonTopClaim && claim.children.size() > 0) { if (claim.isTown() || claim.isAdminClaim()) { Set<Claim> invalidClaims = new HashSet<>(); for (Claim child : claim.getChildren(true)) { if (child.getOwnerUniqueId() == null || !child.getOwnerUniqueId().equals(ownerId)) { //return CommandResult.empty(); invalidClaims.add(child); } } if (!invalidClaims.isEmpty()) { GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().ABANDON_TOWN_CHILDREN); CommandHelper.showClaims(player, invalidClaims, 0, true); return; } } } } final int abandonDelay = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Integer.class), user, Options.ABANDON_DELAY, claim); if (abandonDelay > 0) { final Instant localNow = Instant.now(); final Instant dateCreated = claim.getInternalClaimData().getDateCreated(); final Instant delayExpires = dateCreated.plus(Duration.ofDays(abandonDelay)); final boolean delayActive = !delayExpires.isBefore(localNow); if (delayActive) { TextAdapter.sendComponent(player, MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.ABANDON_CLAIM_DELAY_WARNING, ImmutableMap.of("date", Date.from(delayExpires)))); return; } } final boolean autoSchematicRestore = GriefDefenderPlugin.getActiveConfig(player.getWorld().getProperties()).getConfig().claim.claimAutoSchematicRestore; final Component confirmationText = TextComponent.builder() .append(autoSchematicRestore ? MessageCache.getInstance().SCHEMATIC_ABANDON_RESTORE_WARNING : MessageCache.getInstance().ABANDON_WARNING) .append(TextComponent.builder() .append("\n[") .append(MessageCache.getInstance().LABEL_CONFIRM.color(TextColor.GREEN)) .append("]\n") .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(player, createConfirmationConsumer(player, user, claim, this.abandonTopClaim), true))) .hoverEvent(HoverEvent.showText(MessageCache.getInstance().UI_CLICK_CONFIRM)).build()) .build(); TextAdapter.sendComponent(player, confirmationText); }
Example 19
Source Project: ProjectAres File: TimeUtils.java License: GNU Affero General Public License v3.0 | 4 votes |
public static boolean isEqualOrAfterNow(Instant now, Instant instant) { return !instant.isBefore(now); }
Example 20
Source Project: mug File: RetryerTest.java License: Apache License 2.0 | 4 votes |
boolean pending(Instant now) { return now.isBefore(time); }