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

The following examples show how to use java.time.Instant#isBefore() . 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: DimmerSwitchHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@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 2
Source File: TimeUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
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 3
Source File: MaterializerWorkers.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * 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 4
Source File: KubernetesDockerRunner.java    From styx with Apache License 2.0 5 votes vote down vote up
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 5
Source File: WorkbasketCleanupJob.java    From taskana with Apache License 2.0 5 votes vote down vote up
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 6
Source File: MaterializerActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
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 7
Source File: MonostableFilter.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
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 8
Source File: TaskCleanupJob.java    From taskana with Apache License 2.0 5 votes vote down vote up
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 9
Source File: ValidityOnlyTrustManagerFactory.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@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 10
Source File: DefaultServerWebExchange.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 11
Source File: JwtToken.java    From vipps-developers with MIT License 5 votes vote down vote up
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 12
Source File: LessonBuilderAccessService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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: GrandExchangePlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
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 14
Source File: CommandClaimAbandon.java    From GriefDefender with MIT License 4 votes vote down vote up
@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 15
Source File: CommandClaimAbandon.java    From GriefDefender with MIT License 4 votes vote down vote up
@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 16
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_isBefore_ObjectNull() {
    Instant a = Instant.ofEpochSecond(0L, 0);
    a.isBefore(null);
}
 
Example 17
Source File: ConnectorHelper.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
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 18
Source File: MultipleCredsMatchingAuthenticationProvider.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
@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 19
Source File: TimeUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean isEqualOrAfterNow(Instant now, Instant instant) {
    return !instant.isBefore(now);
}
 
Example 20
Source File: RetryerTest.java    From mug with Apache License 2.0 4 votes vote down vote up
boolean pending(Instant now) {
  return now.isBefore(time);
}