Java Code Examples for java.time.Duration#between()

The following examples show how to use java.time.Duration#between() . 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: StatsCallBack.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
private void completeCheck() {
    final long messageCount = counters.values().stream().mapToLong(Number::longValue).sum();
    logger.debug("Number of messages sent so far: {}", messageCount);

    if ((messageCount >= DurationCount.WARM_UP_COUNT) && !warmUpReached) {
        logger.info("The warm-up count has been reached: {} of {}",
                messageCount, DurationCount.WARM_UP_COUNT);
        warmUpReached = true;

        stop();
    }
    else {
        final int maxDuration = 3;
        Instant now = Instant.now();

        Duration elapsed = Duration.between(now, executor.getStartTime());
        if (elapsed.getSeconds() > (Duration.ofMinutes(maxDuration).getSeconds())) {
            logger.warn("Stopping the warm-up because the maximum duration was reached");
            stop();
        }
    }
}
 
Example 2
Source File: WintertodtPlugin.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void checkActionTimeout()
{
	if (currentActivity == WintertodtActivity.IDLE)
	{
		return;
	}

	int currentAnimation = client.getLocalPlayer() != null ? client.getLocalPlayer().getAnimation() : -1;
	if (currentAnimation != IDLE || lastActionTime == null)
	{
		return;
	}

	Duration actionTimeout = Duration.ofSeconds(3);
	Duration sinceAction = Duration.between(lastActionTime, Instant.now());

	if (sinceAction.compareTo(actionTimeout) >= 0)
	{
		log.debug("Activity timeout!");
		currentActivity = WintertodtActivity.IDLE;
	}
}
 
Example 3
Source File: AgilitySession.java    From plugins with GNU General Public License v3.0 6 votes vote down vote up
void calculateLapsPerHour()
{
	Instant now = Instant.now();

	if (lastLapCompleted != null)
	{
		Duration timeSinceLastLap = Duration.between(lastLapCompleted, now);

		if (!timeSinceLastLap.isNegative())
		{
			lastLapTimes.add(timeSinceLastLap);

			Duration sum = Duration.ZERO;
			for (Duration lapTime : lastLapTimes)
			{
				sum = sum.plus(lapTime);
			}

			Duration averageLapTime = sum.dividedBy(lastLapTimes.size());
			lapsPerHour = (int) (Duration.ofHours(1).toMillis() / averageLapTime.toMillis());
		}
	}

	lastLapCompleted = now;
}
 
Example 4
Source File: ReportButtonPlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private String getLoginTime()
{
	if (loginTime == null)
	{
		return "Report";
	}

	Duration duration = Duration.between(loginTime, Instant.now());
	LocalTime time = LocalTime.ofSecondOfDay(duration.getSeconds());
	return time.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
}
 
Example 5
Source File: Launcher.java    From datakernel with Apache License 2.0 5 votes vote down vote up
@JmxAttribute
@Nullable
public final Duration getDurationOfStop() {
	if (instantOfStop == null) {
		return null;
	}
	return Duration.between(instantOfStop, instantOfComplete == null ? Instant.now() : instantOfComplete);
}
 
Example 6
Source File: ArchiverTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * The archiver is expected to wait for a certain amount of time, before
 * writing data to the store (this is intended to allow the archiver to batch
 * work). This test verifies that the data is written to the storage only
 * after the 'grace period' has ended.
 */
@Test
public void testArchiverWaitForGrace() throws Exception
{
    // Setup fixture.
    final int maxWorkQueueSize = 100;
    final Duration maxPurgeInterval = Duration.ofMillis( 5000 );
    final Duration gracePeriod = Duration.ofMillis( 250 );
    final DummyArchiver archiver = new DummyArchiver( "test", maxWorkQueueSize, maxPurgeInterval, gracePeriod );
    final Thread thread = new Thread( archiver );

    try
    {
        // Execute system under test.
        thread.start();
        archiver.archive( 1 );

        // Verify result.
        waitUntilArchivingIsDone( archiver, 1 );

        assertFalse( archiver.store.isEmpty() );
        final Duration timeUntilLogged = Duration.between( archiver.getStarted(), archiver.store.get( 1 ) );
        assertTrue( timeUntilLogged.compareTo( gracePeriod ) >= 0 );
    }
    finally
    {
        // Teardown fixture.
        archiver.stop();
    }
}
 
Example 7
Source File: Java8TestPeriodDuration.java    From javase with MIT License 5 votes vote down vote up
public void testDuration(){
   LocalTime time1 = LocalTime.now();
   Duration twoHours = Duration.ofHours(2);
		
   LocalTime time2 = time1.plus(twoHours);
   Duration duration = Duration.between(time1, time2);
		
   System.out.println("Duration: " + duration);
}
 
Example 8
Source File: AbstractMetricsEndpoint.java    From promregator with Apache License 2.0 5 votes vote down vote up
public String handleRequest(@Null Predicate<? super String> applicationIdFilter, @Null Predicate<? super Instance> instanceFilter) throws ScrapingException {
	log.debug("Received request to a metrics endpoint");
	Instant start = Instant.now();
	
	this.up.clear();
	
	List<Instance> instanceList = this.cfDiscoverer.discover(applicationIdFilter, instanceFilter);
	
	if (instanceList == null || instanceList.isEmpty()) {
		throw new ScrapingException("Unable to determine any instance to scrape");
	}
	
	List<MetricsFetcher> callablesPrep = this.createMetricsFetchers(instanceList);
	
	List<Future<HashMap<String, MetricFamilySamples>>> futures = this.startMetricsFetchers(callablesPrep);
	log.debug(String.format("Fetching metrics from %d distinct endpoints", futures.size()));
	
	MergableMetricFamilySamples mmfs = waitForMetricsFetchers(futures);
	
	Instant stop = Instant.now();
	Duration duration = Duration.between(start, stop);
	this.handleScrapeDuration(this.requestRegistry, duration);
	
	if (this.isIncludeGlobalMetrics()) {
		// also add our own (global) metrics
		mmfs.merge(this.gmfspr.determineEnumerationOfMetricFamilySamples(this.collectorRegistry));
	}
	
	// add also our own request-specific metrics
	mmfs.merge(this.gmfspr.determineEnumerationOfMetricFamilySamples(this.requestRegistry));
	
	return mmfs.toType004String();
}
 
Example 9
Source File: SelfSignedCertificate.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public X509CertificateHolder build()
    throws SCMSecurityException, IOException {
  Preconditions.checkNotNull(key, "Key cannot be null");
  Preconditions.checkArgument(Strings.isNotBlank(subject), "Subject " +
      "cannot be blank");
  Preconditions.checkArgument(Strings.isNotBlank(clusterID), "Cluster ID " +
      "cannot be blank");
  Preconditions.checkArgument(Strings.isNotBlank(scmID), "SCM ID cannot " +
      "be blank");

  Preconditions.checkArgument(beginDate.isBefore(endDate), "Certificate " +
      "begin date should be before end date");

  // We just read the beginDate and EndDate as Start of the Day and
  // confirm that we do not violate the maxDuration Config.
  Duration certDuration = Duration.between(beginDate.atStartOfDay(),
      endDate.atStartOfDay());
  Duration maxDuration = config.getMaxCertificateDuration();
  if (certDuration.compareTo(maxDuration) > 0) {
    throw new SCMSecurityException("The cert duration violates the " +
        "maximum configured value. Please check the hdds.x509.max" +
        ".duration config key. Current Value: " + certDuration +
        " config: " + maxDuration);
  }

  SelfSignedCertificate rootCertificate =
      new SelfSignedCertificate(this.subject,
          this.scmID, this.clusterID, this.beginDate, this.endDate,
          this.config, key);
  try {
    return rootCertificate.generateCertificate(isCA);
  } catch (OperatorCreationException | CertIOException e) {
    throw new CertificateException("Unable to create root certificate.",
        e.getCause());
  }
}
 
Example 10
Source File: AbstractFileEditor.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@FxThread
public void notifyHided() {

    final Duration duration = Duration.between(showedTime, LocalTime.now());
    final int seconds = (int) duration.getSeconds();

    final EditorDescription description = getDescription();

    GAnalytics.sendTiming(GAEvent.Category.EDITOR, GAEvent.Label.WORKING_ON_AN_EDITOR,
            seconds, description.getEditorId());
}
 
Example 11
Source File: Timer.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String getText()
{
	Duration timeLeft = Duration.between(Instant.now(), endTime);

	int seconds = (int) (timeLeft.toMillis() / 1000L);

	int minutes = (seconds % 3600) / 60;
	int secs = seconds % 60;

	return String.format("%d:%02d", minutes, secs);
}
 
Example 12
Source File: DpsMember.java    From runelite with BSD 2-Clause "Simplified" License 4 votes vote down vote up
Duration elapsed()
{
	return Duration.between(start, end == null ? Instant.now() : end);
}
 
Example 13
Source File: BusinessCalendarImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected String adoptISOFormat(String timeExpression) {

        try {
            Duration p = null;
            if (DateTimeUtils.isPeriod(timeExpression)) {
                p = Duration.parse(timeExpression);
            } else if (DateTimeUtils.isNumeric(timeExpression)) {
                p = Duration.of(Long.valueOf(timeExpression), ChronoUnit.MILLIS);
            } else {
                OffsetDateTime dateTime = OffsetDateTime.parse(timeExpression, DateTimeFormatter.ISO_DATE_TIME);
                p = Duration.between(OffsetDateTime.now(), dateTime);
            }

            long days = p.toDays();
            long hours = p.toHours() % 24;
            long minutes = p.toMinutes() % 60;
            long seconds = p.getSeconds() % 60;
            long milis = p.toMillis() % 1000;

            StringBuffer time = new StringBuffer();
            if (days > 0) {
                time.append(days + "d");
            }
            if (hours > 0) {
                time.append(hours + "h");
            }
            if (minutes > 0) {
                time.append(minutes + "m");
            }
            if (seconds > 0) {
                time.append(seconds + "s");
            }
            if (milis > 0) {
                time.append(milis + "ms");
            }

            return time.toString();
        } catch (Exception e) {
            return timeExpression;
        }
    }
 
Example 14
Source File: WhisperFormatter.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public void receive(Player viewer, Whisper whisper) {
    final Identity sender = senderIdentity(whisper);
    final Identity recipient = recipientIdentity(whisper);
    final Audience audience = audiences.get(viewer);
    final boolean local = whisper.server_id().equals(localServer._id());

    final Component from = new Component();
    if(!local) {
        // Show sender server if not local. There is an edge case where this reveals nicked players:
        // if a player uses /reply to send a message from their real identity while they are nicked,
        // the recipient will know they are nicked because they are not reported as online, and they
        // will also know what server they are on. The former is unavoidable. The latter could be
        // avoided by saving a flag in the message indicating that the sender was disguised, but
        // that probably isn't worth the trouble. We might do it when we move PMs to the API.
        from.extra(serverFormatter.nameWithDatacenter(serverStore.byId(whisper.server_id()))).extra(" ");
    }
    from.extra(new PlayerComponent(sender, NameStyle.VERBOSE));

    // Show recipient identity if it is nicked OR if it is not the recipient's current identity
    String key = "privateMessage.from";
    if(recipient.getNickname() != null || !recipient.isCurrent()) {
        key += ".to";
    }

    final Duration age = Duration.between(whisper.sent(), Instant.now());
    if(Comparables.greaterThan(age, OLD_MESSAGE)) {
        // If message is old, show the time
        key += ".time";
    } else {
        // If message is new, play a sound
        if(playerSettings.getManager(viewer)
                         .getValue(WhisperSettings.sound(), WhisperSettings.Options.class)
                         .isAllowed(sender.familiarity(viewer))) {
            audience.playSound(MESSAGE_SOUND);
        }
    }

    final Component display = prefix()
        .extra(new TranslatableComponent(key,
                                         from,
                                         new PlayerComponent(recipient, NameStyle.VERBOSE),
                                         new Component(new TranslatableComponent("time.ago", PeriodFormats.briefNaturalApproximate(age)), ChatColor.GOLD)))
        .extra(": ")
        .extra(new Component(new UserTextComponent(whisper.content()), ChatColor.WHITE));

    audience.sendMessage(display);
    if(!local) {
        consoleAudience.sendMessage(display);
    }
}
 
Example 15
Source File: TitheFarmPlant.java    From runelite with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public double getPlantTimeRelative()
{
	Duration duration = Duration.between(planted, Instant.now());
	return duration.compareTo(PLANT_TIME) < 0 ? (double) duration.toMillis() / PLANT_TIME.toMillis() : 1;
}
 
Example 16
Source File: CommandHelper.java    From GriefPrevention with MIT License 4 votes vote down vote up
public static void displayClaimBankInfo(CommandSource src, GPClaim claim, boolean checkTown, boolean returnToClaimInfo) {
    final EconomyService economyService = GriefPreventionPlugin.instance.economyService.orElse(null);
    if (economyService == null) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyNotInstalled.toText());
        return;
    }

    if (checkTown && !claim.isInTown()) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.townNotIn.toText());
        return;
    }

    if (!checkTown && (claim.isSubdivision() || claim.isAdminClaim())) {
        return;
    }

    final GPClaim town = claim.getTownClaim();
    Account bankAccount = checkTown ? town.getEconomyAccount().orElse(null) : claim.getEconomyAccount().orElse(null);
    if (bankAccount == null) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyVirtualNotSupported.toText());
        return;
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getPlayerData(claim.getWorld(), claim.getOwnerUniqueId());
    final double claimBalance = bankAccount.getBalance(economyService.getDefaultCurrency()).doubleValue();
    double taxOwed = -1;
    final double playerTaxRate = GPOptionHandler.getClaimOptionDouble(playerData.getPlayerSubject(), claim, GPOptions.Type.TAX_RATE, playerData);
    if (checkTown) {
        if (!town.getOwnerUniqueId().equals(playerData.playerID)) {
            for (Claim playerClaim : playerData.getInternalClaims()) {
                GPClaim playerTown = (GPClaim) playerClaim.getTown().orElse(null);
                if (!playerClaim.isTown() && playerTown != null && playerTown.getUniqueId().equals(claim.getUniqueId())) {
                    taxOwed += playerTown.getClaimBlocks() * playerTaxRate;
                }
            }
        } else {
            taxOwed = town.getClaimBlocks() * playerTaxRate;
        }
    } else {
        taxOwed = claim.getClaimBlocks() * playerTaxRate;
    }

    final GriefPreventionConfig<?> activeConfig = GriefPreventionPlugin.getActiveConfig(claim.getWorld().getProperties());
    final ZonedDateTime withdrawDate = TaskUtils.getNextTargetZoneDate(activeConfig.getConfig().claim.taxApplyHour, 0, 0);
    Duration duration = Duration.between(Instant.now().truncatedTo(ChronoUnit.SECONDS), withdrawDate.toInstant()) ;
    final long s = duration.getSeconds();
    final String timeLeft = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
    final Text message = GriefPreventionPlugin.instance.messageData.claimBankInfo
            .apply(ImmutableMap.of(
            "balance", claimBalance,
            "amount", taxOwed,
            "time_remaining", timeLeft,
            "tax_balance", claim.getData().getEconomyData().getTaxBalance())).build();
    Text transactions = Text.builder()
            .append(Text.of(TextStyles.ITALIC, TextColors.AQUA, "Bank Transactions"))
            .onClick(TextActions.executeCallback(createBankTransactionsConsumer(src, claim, checkTown, returnToClaimInfo)))
            .onHover(TextActions.showText(Text.of("Click here to view bank transactions")))
            .build();
    List<Text> textList = new ArrayList<>();
    if (returnToClaimInfo) {
        textList.add(Text.builder().append(Text.of(
                TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claim info", TextColors.WHITE, "]\n"))
            .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claiminfo", ""))).build());
    }
    textList.add(message);
    textList.add(transactions);
    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList.Builder paginationBuilder = paginationService.builder()
            .title(Text.of(TextColors.AQUA, "Bank Info")).padding(Text.of(TextStyles.STRIKETHROUGH, "-")).contents(textList);
    paginationBuilder.sendTo(src);
}
 
Example 17
Source File: BlastMineRock.java    From runelite with BSD 2-Clause "Simplified" License 4 votes vote down vote up
double getRemainingTimeRelative()
{
	Duration duration = Duration.between(creationTime, Instant.now());
	return duration.compareTo(PLANT_TIME) < 0 ? (double) duration.toMillis() / PLANT_TIME.toMillis() : 1;
}
 
Example 18
Source File: TCKDuration.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_between__TemporalTemporal_endNull() {
    Instant start = Instant.ofEpochSecond(1);
    Duration.between(start, null);
}
 
Example 19
Source File: TCKDuration.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_between__TemporalTemporal_endNull() {
    Instant start = Instant.ofEpochSecond(1);
    Duration.between(start, null);
}
 
Example 20
Source File: FloatingpointDate.java    From finmath-lib with Apache License 2.0 2 votes vote down vote up
/**
 * Convert a given date to a floating point date using a given reference date.
 *
 * @param referenceDate The reference date associated with \( t=0 \).
 * @param date The given date to be associated with the return value \( T \).
 * @return The value T measuring the distance of reference date and date by ACT/365 with SECONDS_PER_DAY seconds used as the smallest time unit and SECONDS_PER_DAY is a constant 365*24*60*60.
 */
public static double getFloatingPointDateFromDate(final LocalDateTime referenceDate, final LocalDateTime date) {
	final Duration duration = Duration.between(referenceDate, date);
	return ((double)duration.getSeconds()) / SECONDS_PER_DAY;
}