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

The following examples show how to use java.time.Duration#isZero() . 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
void incrementPayDirtMined()
{
	Instant now = Instant.now();

	lastPayDirtMined = now;
	++totalMined;

	if (recentMined == 0)
	{
		recentPayDirtMined = now;
	}
	++recentMined;

	Duration timeSinceStart = Duration.between(recentPayDirtMined, now);
	if (!timeSinceStart.isZero())
	{
		perHour = (int) ((double) recentMined * (double) HOUR.toMillis() / (double) timeSinceStart.toMillis());
	}
}
 
Example 2
/**
 * Sets time-to-live for those schema types that support it
 *
 * @param type
 * @param duration Note that only 'seconds' granularity is supported
 */
@Override
public void setTTL(final TitanSchemaType type,
                   final Duration duration) {
    if (!graph.getBackend().getStoreFeatures().hasCellTTL())
        throw new UnsupportedOperationException("The storage engine does not support TTL");
    if (type instanceof VertexLabelVertex) {
        Preconditions.checkArgument(((VertexLabelVertex) type).isStatic(), "must define vertex label as static to allow setting TTL");
    } else {
        Preconditions.checkArgument(type instanceof EdgeLabelVertex || type instanceof PropertyKeyVertex, "TTL is not supported for type " + type.getClass().getSimpleName());
    }
    Preconditions.checkArgument(type instanceof TitanSchemaVertex);

    Integer ttlSeconds = (duration.isZero()) ?
            null :
            (int) duration.getSeconds();

    setTypeModifier(type, ModifierType.TTL, ttlSeconds);
}
 
Example 3
Source Project: incubator-heron   File: Config.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Registers a timer event that executes periodically
 * @param conf the map with the existing topology configs
 * @param name the name of the timer
 * @param interval the frequency in which to run the task
 * @param task the task to run
 */
@SuppressWarnings("unchecked")
public static void registerTopologyTimerEvents(Map<String, Object> conf,
                                               String name, Duration interval,
                                               Runnable task) {
  if (interval.isZero() || interval.isNegative()) {
    throw new IllegalArgumentException("Timer duration needs to be positive");
  }
  if (!conf.containsKey(Config.TOPOLOGY_TIMER_EVENTS)) {
    conf.put(Config.TOPOLOGY_TIMER_EVENTS, new HashMap<String, Pair<Duration, Runnable>>());
  }

  Map<String, Pair<Duration, Runnable>> timers
      = (Map<String, Pair<Duration, Runnable>>) conf.get(Config.TOPOLOGY_TIMER_EVENTS);

  if (timers.containsKey(name)) {
    throw new IllegalArgumentException("Timer with name " + name + " already exists");
  }
  timers.put(name, Pair.of(interval, task));
}
 
Example 4
public ResetPeriodicallyCounter(Duration resetInterval, Clock clock) {
    if (resetInterval.isNegative() || resetInterval.isZero()) {
        throw new IllegalArgumentException("intervalBetweenChunkResetting must be a positive duration");
    }
    this.resetIntervalMillis = resetInterval.toMillis();
    this.clock = clock;
    this.nextResetTimeMillisRef = new AtomicLong(clock.currentTimeMillis() + resetIntervalMillis);
}
 
Example 5
/**
 * Creates a {@link ClockGlobalRateLimiter} with a specified interval and number of
 * permits per tick.
 *
 * @param permitsPerTick the max number of requests per tick
 * @param interval the interval between two ticks
 */
public ClockGlobalRateLimiter(int permitsPerTick, Duration interval, Scheduler scheduler) {
    if ((Objects.requireNonNull(interval)).isNegative() || interval.isZero()) {
        throw new IllegalArgumentException("interval must be a non-zero positive duration");
    }
    this.limitedUntil = new AtomicLong();
    this.permitsRemaining = new AtomicInteger();
    this.permitsResetAfter = new AtomicLong();
    Flux.interval(interval, scheduler)
            .doOnNext(tick -> permitsRemaining.set(permitsPerTick))
            .doOnNext(tick -> permitsResetAfter.set(System.nanoTime() + interval.toNanos()))
            .subscribe();
}
 
Example 6
public boolean mute(Player player, Duration t) {
    if (t.isNegative() || t.isZero()) return false;
    // t>30 => (t!=30 && t>=30) => (t!=30 && t-30>=0) => (t!=30 && !(t-30<0))
    if (t.toDays() != 30 && !(t.minus(THIRTY_DAYS).isNegative())) return false; // t>30
    this.muteConfig.set(player.getName().toLowerCase(), Timestamp.valueOf(LocalDateTime.now().plus(t)).getTime() / 1000);
    this.muteConfig.save();
    return true;
}
 
Example 7
/**
 * A (localized) interval phrase like "X seconds" or "X minutes". Uses the largest unit that can
 * represent the interval precisely. This is useful when the interval is expected to be a "round"
 * value. The interval must be non-zero.
 */
public static Component briefNaturalPrecise(Duration duration) {
  if (duration.isZero() || duration.isNegative()) {
    throw new IllegalArgumentException("Duration must be positive");
  }

  long ms = duration.toMillis();
  for (TemporalUnit unit : UNITS) {
    if (ms % unit.getDuration().toMillis() == 0) {
      return formatPeriod(unit, periodAmount(unit, duration));
    }
  }
  throw new IllegalStateException();
}
 
Example 8
Source Project: diirt   File: IntegrateFormulaFunction.java    License: MIT License 5 votes vote down vote up
static double integrate(Instant start, Instant end, VNumber value, VNumber nextValue) {
    Instant actualStart = Collections.max(Arrays.asList(start, value.getTimestamp()));
    Instant actualEnd = end;
    if (nextValue != null) {
        actualEnd = Collections.min(Arrays.asList(end, nextValue.getTimestamp()));
    }
    Duration duration = Duration.between(actualStart, actualEnd);
    if (!duration.isNegative() && !duration.isZero()) {
        return TimeDuration.toSecondsDouble(duration.multipliedBy(value.getValue().longValue()));
    } else {
        return 0;
    }
}
 
Example 9
Source Project: datakernel   File: StringFormatUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String formatDuration(Duration value) {
	if (value.isZero()) {
		return "0 seconds";
	}
	String result = "";
	long days, hours, minutes, seconds, nano, milli;
	days = value.toDays();
	if (days != 0) {
		result += days + " days ";
	}
	hours = value.toHours() - days * 24;
	if (hours != 0) {
		result += hours + " hours ";
	}
	minutes = value.toMinutes() - days * 1440 - hours * 60;
	if (minutes != 0) {
		result += minutes + " minutes ";
	}
	seconds = value.getSeconds() - days * 86400 - hours * 3600 - minutes * 60;
	if (seconds != 0) {
		result += seconds + " seconds ";
	}
	nano = value.getNano();
	milli = (nano - nano % 1000000) / 1000000;
	if (milli != 0) {
		result += milli + " millis ";
	}
	nano = nano % 1000000;
	if (nano != 0) {
		result += nano + " nanos ";
	}
	return result.trim();
}
 
Example 10
@Command(
    aliases = {"offlineban", "offban"},
    usage = "<player> <reason> -t (length)",
    desc = "Ban an offline player from the server",
    flags = "t",
    perms = Permissions.BAN)
public void offlineBan(
    CommandSender sender,
    MatchManager manager,
    String target,
    @Text String reason,
    @Switch('t') Duration duration)
    throws CommandException {
  boolean tempBan = duration != null && !duration.isZero();
  PunishmentType type = tempBan ? PunishmentType.TEMP_BAN : PunishmentType.BAN;
  Component punisher = UsernameFormatUtils.formatStaffName(sender, manager.getMatch(sender));

  banPlayer(target, reason, punisher, tempBan ? Instant.now().plus(duration) : null);
  broadcastPunishment(
      type,
      manager.getMatch(sender),
      sender,
      TextComponent.of(target, TextColor.DARK_AQUA),
      reason,
      true,
      duration);

  // Check if target is online, cache and kick after ban
  Player player = Bukkit.getPlayerExact(target);
  if (player != null) {
    cacheRecentBan(player, punisher);
    player.kickPlayer(formatPunishmentScreen(type, punisher, reason, tempBan ? duration : null));
  }
}
 
Example 11
private BaseWindowedBolt withSlidingInterval(Duration duration) {
  if (duration == null) {
    throw new IllegalArgumentException("Sliding interval cannot be set null");
  }
  if (duration.isNegative() || duration.isZero()) {
    throw new IllegalArgumentException("Sliding interval must be positive [" + duration + "]");
  }
  windowConfiguration.put(WindowingConfigs.TOPOLOGY_BOLTS_SLIDING_INTERVAL_DURATION_MS,
      duration.toMillis());
  return this;
}
 
Example 12
Source Project: jphp   File: DateFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static Memory localtime(Environment env, TraceInfo traceInfo, long time, boolean isAssociative) {
    ZoneId zone = zoneId(env, traceInfo);

    Instant instant = Instant.ofEpochSecond(time);
    ZonedDateTime dateTime = instant.atZone(zone);

    Memory[] ret = new Memory[9];

    ret[0] = LongMemory.valueOf(dateTime.getSecond());
    ret[1] = LongMemory.valueOf(dateTime.getMinute());
    ret[2] = LongMemory.valueOf(dateTime.getHour());
    ret[3] = LongMemory.valueOf(dateTime.getDayOfMonth());
    ret[4] = LongMemory.valueOf(dateTime.getMonthValue() - 1);
    ret[5] = LongMemory.valueOf(dateTime.getYear() - 1900);
    ret[6] = LongMemory.valueOf(dateTime.getDayOfWeek().getValue());
    ret[7] = LongMemory.valueOf(dateTime.getDayOfYear() - 1);
    Duration ds = zone.getRules().getDaylightSavings(instant);
    ret[8] = ds.isZero() ? Memory.CONST_INT_0 : Memory.CONST_INT_1;

    if (isAssociative) {
        Memory[] struct = LocaltimeStructureHolder.VALUE;
        ArrayMemory array = ArrayMemory.createHashed(ret.length);
        for (int i = 0; i < struct.length; i++) {
            array.put(struct[i], ret[i]);
        }

        return array;
    }

    return ArrayMemory.of(ret);
}
 
Example 13
/**
 * Remove SOTD timer and update stamina timer when equipment is changed.
 */
@Subscribe
void onItemContainerChanged(ItemContainerChanged itemContainerChanged)
{
	if (itemContainerChanged.getContainerId() != InventoryID.EQUIPMENT.getId())
	{
		return;
	}

	ItemContainer container = itemContainerChanged.getItemContainer();
	Item weapon = container.getItem(EquipmentInventorySlot.WEAPON.getSlotIdx());
	if (weapon == null ||
		(weapon.getId() != ItemID.STAFF_OF_THE_DEAD &&
			weapon.getId() != ItemID.TOXIC_STAFF_OF_THE_DEAD &&
			weapon.getId() != ItemID.STAFF_OF_LIGHT &&
			weapon.getId() != ItemID.TOXIC_STAFF_UNCHARGED))
	{
		// remove sotd timer if the staff has been unwielded
		removeGameTimer(STAFF_OF_THE_DEAD);
	}

	if (wasWearingEndurance)
	{
		Item ring = container.getItem(EquipmentInventorySlot.RING.getSlotIdx());

		// when using the last ring charge the ring changes to the uncharged version, ignore that and don't
		// halve the timer
		if (ring == null || (ring.getId() != ItemID.RING_OF_ENDURANCE && ring.getId() != ItemID.RING_OF_ENDURANCE_UNCHARGED_24844))
		{
			wasWearingEndurance = false;
			if (staminaTimer != null)
			{
				// Remaining duration gets divided by 2
				Duration remainingDuration = Duration.between(Instant.now(), staminaTimer.getEndTime()).dividedBy(2);
				// This relies on the chat message to be removed, which could be after the timer has been culled;
				// so check there is still remaining time
				if (!remainingDuration.isNegative() && !remainingDuration.isZero())
				{
					log.debug("Halving stamina timer");
					staminaTimer.setDuration(remainingDuration);
				}
			}
		}
	}
}
 
Example 14
Source Project: reactor-core   File: MonoCacheTime.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void signalCached(Signal<T> signal) {
	Signal<T> signalToPropagate = signal;
	if (STATE.compareAndSet(main, this, signal)) {
		Duration ttl = null;
		try {
			ttl = main.ttlGenerator.apply(signal);
		}
		catch (Throwable generatorError) {
			signalToPropagate = Signal.error(generatorError);
			STATE.set(main, signalToPropagate);
			if (signal.isOnError()) {
				//noinspection ThrowableNotThrown
				Exceptions.addSuppressed(generatorError, signal.getThrowable());
			}
		}

		if (ttl != null) {
			if (ttl.isZero()) {
				//immediate cache clear
				main.run();
			}
			else if (!ttl.equals(DURATION_INFINITE)) {
				main.clock.schedule(main, ttl.toNanos(), TimeUnit.NANOSECONDS);
			}
			//else TTL is Long.MAX_VALUE, schedule nothing but still cache
		}
		else {
			//error during TTL generation, signal != updatedSignal, aka dropped
			if (signal.isOnNext()) {
				Operators.onNextDropped(signal.get(), currentContext());
			}
			//if signal.isOnError(), avoid dropping the error. it is not really dropped but already suppressed
			//in all cases, unless nextDropped hook throws, immediate cache clear
			main.run();
		}
	}

	for (Operators.MonoSubscriber<T, T> inner : SUBSCRIBERS.getAndSet(this, TERMINATED)) {
		if (signalToPropagate.isOnNext()) {
			inner.complete(signalToPropagate.get());
		}
		else if (signalToPropagate.isOnError()) {
			inner.onError(signalToPropagate.getThrowable());
		}
		else {
			inner.onComplete();
		}
	}
}
 
Example 15
@VisibleForTesting
BigDecimal calculateConfidence(Instant time, Instant now) {

    Duration duration = Duration.between(time, now);

    if (duration.isZero() || duration.isNegative()) {
        return ONE;
    }

    // Number from 0 to 29 (= 100 years)
    double scaled = Math.log(duration.toMillis());

    // Number from 0.00 to 0.79
    double multiplied = scaled * Math.E / 100;

    // Number from 100.00 to 0.21
    double confidence = 1 - multiplied;

    // Sanitize in case if +3000 years...
    return BigDecimal.valueOf(confidence).max(ZERO).setScale(SCALE, HALF_UP);

}
 
Example 16
@Override
protected SandboxedSpawn prepareSpawn(Spawn spawn, SpawnExecutionContext context)
    throws IOException {
  Path tmpDir = createActionTemp(execRoot);
  Path commandTmpDir = tmpDir.getRelative("work");
  commandTmpDir.createDirectory();
  ImmutableMap<String, String> environment =
      localEnvProvider.rewriteLocalEnv(
          spawn.getEnvironment(), binTools, commandTmpDir.getPathString());

  SandboxInputs readablePaths =
      helpers.processInputFiles(
          context.getInputMapping(
              getSandboxOptions().symlinkedSandboxExpandsTreeArtifactsInRunfilesTree),
          spawn,
          context.getArtifactExpander(),
          execRoot);

  readablePaths.materializeVirtualInputs(execRoot);

  ImmutableSet.Builder<Path> writablePaths = ImmutableSet.builder();
  writablePaths.addAll(getWritableDirs(execRoot, environment));
  for (ActionInput output : spawn.getOutputFiles()) {
    writablePaths.add(execRoot.getRelative(output.getExecPath()));
  }

  Duration timeout = context.getTimeout();

  if (!readablePaths.getSymlinks().isEmpty()) {
    throw new IOException(
        "Windows sandbox does not support unresolved symlinks yet ("
            + Joiner.on(", ").join(readablePaths.getSymlinks().keySet())
            + ")");
  }

  WindowsSandboxUtil.CommandLineBuilder commandLineBuilder =
      WindowsSandboxUtil.commandLineBuilder(windowsSandbox, spawn.getArguments())
          .setWritableFilesAndDirectories(writablePaths.build())
          .setReadableFilesAndDirectories(readablePaths.getFiles())
          .setInaccessiblePaths(getInaccessiblePaths())
          .setUseDebugMode(getSandboxOptions().sandboxDebug)
          .setKillDelay(timeoutKillDelay);

  if (!timeout.isZero()) {
    commandLineBuilder.setTimeout(timeout);
  }

  return new WindowsSandboxedSpawn(execRoot, environment, commandLineBuilder.build());
}
 
Example 17
private static boolean shouldExpireWithin(@Nullable Duration ttl) {
	return ttl != null && !ttl.isZero() && !ttl.isNegative();
}
 
Example 18
Source Project: ditto   File: BaseClientActor.java    License: Eclipse Public License 2.0 4 votes vote down vote up
private static Predicate<Duration> isLowerThanOrEqual(final Duration otherDuration) {
    return arg -> {
        final Duration minus = arg.minus(otherDuration);
        return minus.isNegative() || minus.isZero();
    };
}
 
Example 19
@Override
protected SandboxedSpawn prepareSpawn(Spawn spawn, SpawnExecutionContext context)
    throws IOException, ExecException {
  // Each invocation of "exec" gets its own sandbox base, execroot and temporary directory.
  Path sandboxPath =
      sandboxBase.getRelative(getName()).getRelative(Integer.toString(context.getId()));
  sandboxPath.getParentDirectory().createDirectory();
  sandboxPath.createDirectory();

  // b/64689608: The execroot of the sandboxed process must end with the workspace name, just like
  // the normal execroot does.
  Path sandboxExecRoot = sandboxPath.getRelative("execroot").getRelative(execRoot.getBaseName());
  sandboxExecRoot.getParentDirectory().createDirectory();
  sandboxExecRoot.createDirectory();

  ImmutableMap<String, String> environment =
      localEnvProvider.rewriteLocalEnv(spawn.getEnvironment(), binTools, "/tmp");

  SandboxInputs inputs =
      helpers.processInputFiles(
          context.getInputMapping(
              getSandboxOptions().symlinkedSandboxExpandsTreeArtifactsInRunfilesTree),
          spawn,
          context.getArtifactExpander(),
          execRoot);
  SandboxOutputs outputs = helpers.getOutputs(spawn);

  Duration timeout = context.getTimeout();

  UUID uuid = UUID.randomUUID();

  String baseImageName = dockerContainerFromSpawn(spawn).orElse(this.defaultImage);
  if (baseImageName.isEmpty()) {
    throw new UserExecException(
        createFailureDetail(
            String.format(
                "Cannot execute %s mnemonic with Docker, because no image could be found in the"
                    + " remote_execution_properties of the platform and no default image was set"
                    + " via --experimental_docker_image",
                spawn.getMnemonic()),
            Code.NO_DOCKER_IMAGE));
  }

  String customizedImageName = getOrCreateCustomizedImage(baseImageName);
  if (customizedImageName == null) {
    throw new UserExecException(
        createFailureDetail(
            "Could not prepare Docker image for execution",
            Code.DOCKER_IMAGE_PREPARATION_FAILURE));
  }

  DockerCommandLineBuilder cmdLine = new DockerCommandLineBuilder();
  cmdLine
      .setProcessWrapper(processWrapper)
      .setDockerClient(dockerClient)
      .setImageName(customizedImageName)
      .setCommandArguments(spawn.getArguments())
      .setSandboxExecRoot(sandboxExecRoot)
      .setAdditionalMounts(getSandboxOptions().sandboxAdditionalMounts)
      .setPrivileged(getSandboxOptions().dockerPrivileged)
      .setEnvironmentVariables(environment)
      .setCreateNetworkNamespace(
          !(allowNetwork
              || Spawns.requiresNetwork(spawn, getSandboxOptions().defaultSandboxAllowNetwork)))
      .setCommandId(commandId)
      .setUuid(uuid);
  // If uid / gid are -1, we are on an operating system that doesn't require us to set them on the
  // Docker invocation. If they're 0, it means we are running as root and don't need to set them.
  if (uid > 0) {
    cmdLine.setUid(uid);
  }
  if (gid > 0) {
    cmdLine.setGid(gid);
  }
  if (!timeout.isZero()) {
    cmdLine.setTimeout(timeout);
  }

  // If we were interrupted, it is possible that "docker run" gets killed in exactly the moment
  // between the create and the start call, leaving behind a container that is created but never
  // ran. This means that Docker won't automatically clean it up (as --rm only affects the start
  // phase and has no effect on the create phase of "docker run").
  // We register the container UUID for cleanup, but remove the UUID if the process ran
  // successfully.
  containersToCleanup.add(uuid);
  return new CopyingSandboxedSpawn(
      sandboxPath,
      sandboxExecRoot,
      cmdLine.build(),
      cmdEnv.getClientEnv(),
      inputs,
      outputs,
      ImmutableSet.of(),
      treeDeleter,
      /*statisticsPath=*/ null,
      () -> containersToCleanup.remove(uuid));
}
 
Example 20
@VisibleForTesting
BigDecimal calculateRecentPrice(Context context, Request request, int signum, List<Composite> products) {

    Duration duration = request.getTradingDuration();

    if (duration.isZero()) {
        return null;
    }

    List<Order.Execution> executions = new ArrayList<>();

    Key key = Key.from(request);

    ofNullable(products)
            .filter(CollectionUtils::isNotEmpty)
            .orElseGet(() -> singletonList(new Composite(key.getSite(), key.getInstrument())))
            .forEach(c -> {

                Key k = Key.build(key).site(c.getSite()).instrument(c.getInstrument()).build();

                Instant cutoff = key.getTimestamp().minus(duration.abs());

                List<Order.Execution> values = context.listExecutions(k);

                trimToEmpty(values).stream()
                        .filter(Objects::nonNull)
                        .filter(t -> t.getTime() != null)
                        .filter(t -> t.getTime().isAfter(cutoff))
                        .filter(t -> t.getPrice() != null)
                        .filter(t -> t.getPrice().signum() != 0)
                        .filter(t -> t.getSize() != null)
                        .filter(t -> t.getSize().signum() == signum)
                        .forEach(executions::add);

            });

    BigDecimal price;

    if (duration.isNegative()) {

        double[] average = {0.0, 0.0, 0.0};

        executions.forEach(t -> {
            average[0] += t.getSize().multiply(t.getPrice()).doubleValue();
            average[1] += t.getSize().doubleValue();
            average[2] += 1;
        });

        price = average[2] > 0 ? BigDecimal.valueOf(average[0] / average[1]).setScale(SCALE, HALF_UP) : null;

    } else {

        Comparator<BigDecimal> comparator = signum == SIGNUM_BUY ? reverseOrder() : naturalOrder();

        price = executions.stream().map(Order.Execution::getPrice).min(comparator).orElse(null);

    }

    log.trace("Recent price : {} (Duration=[{}] Signum=[{}])", price, duration, signum);

    return price;

}