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

The following examples show how to use java.time.Duration#isNegative() . 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: SummarizerJob.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@Override
public Duration startIn() {
    /*
     * Trigger next Sunday, around 6am.
     * Sunday is chosen as there are no large amounts of transactions expected.
     * 6am is important, since it's long after midnight, when Zonky recalculates.
     * Triggering any such code during recalculation is likely to bring some strange inconsistent values.
     */
    final LocalDateTime date = DateUtil.localNow()
        .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
        .withHour(6)
        .truncatedTo(ChronoUnit.HOURS);
    final Duration untilSunday6am = Duration.between(DateUtil.localNow(), date);
    final Duration untilNextSunday6am = untilSunday6am.isNegative() ? untilSunday6am.plusDays(7) : untilSunday6am;
    final int loadBalancingRandomMinutesOffset = RandomUtil.getNextInt(30) - 15;
    return untilNextSunday6am.plusMinutes(loadBalancingRandomMinutesOffset);
}
 
Example 2
Source File: UndoManagerImpl.java    From UndoFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public UndoManagerImpl(
        ChangeQueue<C> queue,
        Function<? super C, ? extends C> invert,
        Consumer<C> apply,
        BiFunction<C, C, Optional<C>> merge,
        Predicate<C> isIdentity,
        EventStream<C> changeSource,
        Duration preventMergeDelay) {
    this.queue = queue;
    this.invert = invert;
    this.apply = apply;
    this.merge = merge;
    this.isIdentity = isIdentity;
    this.mark = queue.getCurrentPosition();

    Subscription mainSub = changeSource.subscribe(this::changeObserved);

    if (preventMergeDelay.isZero() || preventMergeDelay.isNegative()) {
        subscription = mainSub;
    } else {
        Subscription sub2 = changeSource.successionEnds(preventMergeDelay).subscribe(ignore -> preventMerge());
        subscription = mainSub.and(sub2);
    }
}
 
Example 3
Source File: SpringHibernateTransactionOperations.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public <R> R execute(@NonNull TransactionDefinition definition, @NonNull TransactionCallback<Connection, R> callback) {
    ArgumentUtils.requireNonNull("callback", callback);
    ArgumentUtils.requireNonNull("definition", definition);

    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setReadOnly(definition.isReadOnly());
    def.setIsolationLevel(definition.getIsolationLevel().getCode());
    def.setPropagationBehavior(definition.getPropagationBehavior().ordinal());
    def.setName(definition.getName());
    final Duration timeout = definition.getTimeout();
    if (!timeout.isNegative()) {
        def.setTimeout((int) timeout.getSeconds());
    }
    TransactionTemplate template = new TransactionTemplate(transactionManager, def);
    return template.execute(status -> {
                try {
                    return callback.call(new JpaTransactionStatus(status));
                } catch (RuntimeException | Error ex) {
                    throw ex;
                } catch (Exception e) {
                    throw new UndeclaredThrowableException(e, "TransactionCallback threw undeclared checked exception");
                }
            }
    );
}
 
Example 4
Source File: TopBuilder.java    From rolling-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Top configured with this strategy will be cleared at all after each {@code intervalBetweenResetting} elapsed.
 *
 * <p>
 *     If You use this strategy inside JEE environment,
 *     then it would be better to call {@code ResilientExecutionUtil.getInstance().shutdownBackgroundExecutor()}
 *     once in application shutdown listener,
 *     in order to avoid leaking reference to classloader through the thread which this library creates for resetting of top in background.
 * </p>
 *
 * @param intervalBetweenResetting specifies how often need to reset the top
 * @return this builder instance
 */
public TopBuilder resetAllPositionsPeriodically(Duration intervalBetweenResetting) {
    if (intervalBetweenResetting == null) {
        throw new IllegalArgumentException("intervalBetweenResetting should not be null");
    }
    if (intervalBetweenResetting.isNegative()) {
        throw new IllegalArgumentException("intervalBetweenResetting should not be negative");
    }
    long intervalBetweenResettingMillis = intervalBetweenResetting.toMillis();
    if (intervalBetweenResettingMillis < MIN_CHUNK_RESETTING_INTERVAL_MILLIS) {
        String msg = "interval between resetting one chunk should be >= " + MIN_CHUNK_RESETTING_INTERVAL_MILLIS + " millis";
        throw new IllegalArgumentException(msg);
    }
    this.factory = resetByChunks(intervalBetweenResettingMillis, 0);
    return this;
}
 
Example 5
Source File: ParameterValidation.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
/**
 * Validates that the passed duration is not {@code null} and strictly positive.
 *
 * @param duration the duration
 * @param name the name of the parameter, must not be {@code null}
 * @return the duration is the validation passes.
 */
public static Duration validate(Duration duration, String name) {
    nonNull(name, "name");
    if (duration == null) {
        throw new IllegalArgumentException(String.format("`%s` must not be `null`", name));
    }
    if (duration.isZero() || duration.isNegative()) {
        throw new IllegalArgumentException(String.format("`%s` must be greater than zero`", name));
    }
    return duration;
}
 
Example 6
Source File: ExpiryPolicyBuilder.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Get a time-to-live (TTL) {@link ExpiryPolicy} instance for the given {@link Duration}.
 *
 * @param timeToLive the TTL duration
 * @return a TTL expiry
 */
public static ExpiryPolicy<Object, Object> timeToLiveExpiration(Duration timeToLive) {
  Objects.requireNonNull(timeToLive, "TTL duration cannot be null");
  if (timeToLive.isNegative()) {
    throw new IllegalArgumentException("TTL duration cannot be negative");
  }
  return new TimeToLiveExpiryPolicy(timeToLive);
}
 
Example 7
Source File: NpcAggroAreaPlugin.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void loadConfig()
{
	safeCenters[0] = configManager.getConfiguration(NpcAggroAreaConfig.CONFIG_GROUP, NpcAggroAreaConfig.CONFIG_CENTER1, WorldPoint.class);
	safeCenters[1] = configManager.getConfiguration(NpcAggroAreaConfig.CONFIG_GROUP, NpcAggroAreaConfig.CONFIG_CENTER2, WorldPoint.class);
	lastPlayerLocation = configManager.getConfiguration(NpcAggroAreaConfig.CONFIG_GROUP, NpcAggroAreaConfig.CONFIG_LOCATION, WorldPoint.class);

	Duration timeLeft = configManager.getConfiguration(NpcAggroAreaConfig.CONFIG_GROUP, NpcAggroAreaConfig.CONFIG_DURATION, Duration.class);
	if (timeLeft != null && !timeLeft.isNegative())
	{
		createTimer(timeLeft);
	}
}
 
Example 8
Source File: PoisonPlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private static String getFormattedTime(Duration timeLeft)
{
	if (timeLeft.isNegative())
	{
		return "Now!";
	}

	int seconds = (int) (timeLeft.toMillis() / 1000L);
	int minutes = seconds / 60;
	int secs = seconds % 60;

	return String.format("%d:%02d", minutes, secs);
}
 
Example 9
Source File: TestUtils.java    From enmasse with Apache License 2.0 5 votes vote down vote up
/**
 * Wait for condition, return result.
 * <p>
 * This will check will put a priority on checking the condition, and only wait, when there is
 * remaining time budget left.
 *
 * @param condition The condition to check, returning {@code true} means success.
 * @param delay The delay between checks.
 * @return {@code true} if the condition was met, {@code false otherwise}.
 */
public static boolean waitUntilCondition(final BooleanSupplier condition, final Duration timeout, final Duration delay) {

    Objects.requireNonNull(condition);
    Objects.requireNonNull(timeout);
    Objects.requireNonNull(delay);

    final Instant deadline = Instant.now().plus(timeout);

    while (true) {

        // test first

        if (condition.getAsBoolean()) {
            return true;
        }

        // if the timeout has expired ... stop

        final Duration remaining = Duration.between(deadline, Instant.now());
        if (!remaining.isNegative()) {
            return false;
        }

        // otherwise sleep

        log.debug("next iteration, remaining time: {}", remaining);
        try {
            Thread.sleep(delay.toMillis());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

}
 
Example 10
Source File: ResetPeriodicallyCounter.java    From rolling-metrics with Apache License 2.0 5 votes vote down vote up
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 11
Source File: MemoryMailQueueFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
private ZonedDateTime calculateNextDelivery(Duration delay) {
    if (!delay.isNegative()) {
        try {
            return ZonedDateTime.now().plus(delay);
        } catch (DateTimeException | ArithmeticException e) {
            return Instant.ofEpochMilli(Long.MAX_VALUE).atZone(ZoneId.of("UTC"));
        }
    }

    return ZonedDateTime.now();
}
 
Example 12
Source File: Require.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static Duration nonNegative(String argName, Duration arg) {
  if (arg == null) {
    throw new IllegalArgumentException(argName + " must be set");
  }
  if (arg.isNegative()) {
    throw new IllegalArgumentException(argName + " must be set to 0 or more");
  }
  return arg;
}
 
Example 13
Source File: LockConfiguration.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
private LockConfiguration(@NonNull Instant createdAt, @NonNull String name, @NonNull Duration lockAtMostFor, @NonNull Duration lockAtLeastFor) {
    this.createdAt = Objects.requireNonNull(createdAt);
    this.name = Objects.requireNonNull(name);
    this.lockAtMostFor = Objects.requireNonNull(lockAtMostFor);
    this.lockAtLeastFor = Objects.requireNonNull(lockAtLeastFor);
    if (lockAtLeastFor.compareTo(lockAtMostFor) > 0) {
        throw new IllegalArgumentException("lockAtLeastFor is longer than lockAtMostFor for lock '" + name + "'.");
    }
    if (lockAtMostFor.isNegative()) {
        throw new IllegalArgumentException("lockAtMostFor is negative '" + name + "'.");
    }
    if (name.isEmpty()) {
        throw new IllegalArgumentException("lock name can not be empty");
    }
}
 
Example 14
Source File: TopBuilder.java    From rolling-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the latency threshold. The queries having latency which shorter than threshold, will not be tracked in the top.
 * The default value is zero {@link #DEFAULT_LATENCY_THRESHOLD}, means that all queries can be recorded independent of its latency.
 *
 * Specify this parameter when you want not to track queries which fast,
 * in other words when you want see nothing when all going well.
 * 
 * @param latencyThreshold
 * @return this builder instance
 */
public TopBuilder withLatencyThreshold(Duration latencyThreshold) {
    if (latencyThreshold == null) {
        throw new IllegalArgumentException("latencyThreshold should not be null");
    }
    if (latencyThreshold.isNegative()) {
        throw new IllegalArgumentException("latencyThreshold should not be negative");
    }
    this.latencyThreshold = latencyThreshold;
    return this;
}
 
Example 15
Source File: DiffDateExpressionProcessor.java    From vividus with Apache License 2.0 4 votes vote down vote up
private Optional<String> processNegative(Duration duration, String durationAsString)
{
    return duration.isNegative()
            ? Optional.of(MINUS_SIGN + durationAsString.replace(MINUS_SIGN, StringUtils.EMPTY))
            : Optional.of(durationAsString);
}
 
Example 16
Source File: TimersPlugin.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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 17
Source File: SkinModel.java    From ChangeSkin with MIT License 4 votes vote down vote up
public boolean isOutdated(Duration autoUpdateDiff) {
    Duration difference = Duration.between(Instant.ofEpochMilli(timestamp), Instant.now());
    return !autoUpdateDiff.isNegative() && difference.compareTo(autoUpdateDiff) >= 0;
}
 
Example 18
Source File: DurationIs.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void validate(Duration value, @Nullable Node node) throws InvalidXMLException {
    if(value.isNegative()) {
        throw new InvalidXMLException("Time cannot be negative", node);
    }
}
 
Example 19
Source File: Recording.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Determines how far back data is kept in the disk repository.
 * <p>
 * To control the amount of recording data stored on disk, the maximum length of
 * time to retain the data can be specified. Data stored on disk that is older
 * than the specified length of time is removed by the Java Virtual Machine (JVM).
 * <p>
 * If neither maximum limit or the maximum age is set, the size of the
 * recording may grow indefinitely.
 *
 * @param maxAge the length of time that data is kept, or {@code null} if infinite
 *
 * @throws IllegalArgumentException if <code>maxAge</code> is negative
 *
 * @throws IllegalStateException if the recording is in the {@code CLOSED} state
 */
public void setMaxAge(Duration maxAge) {
    if (maxAge != null && maxAge.isNegative()) {
        throw new IllegalArgumentException("Max age of recording can't be negative");
    }
    internal.setMaxAge(maxAge);
}
 
Example 20
Source File: TemplateAdviser.java    From cryptotrader with GNU Affero General Public License v3.0 2 votes vote down vote up
@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;

}