Java Code Examples for java.time.Instant.minus()

The following are Jave code examples for showing how to use minus() of the java.time.Instant class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: swblocks-decisiontree   File: DatedTreeNodeTest.java   View Source Code Vote up 6 votes
@Test
public void addNodeUpdatesDateRangeStart() {
    final TreeNode root = createDatedTreeNode("Root", Instant.MIN, Instant.MAX);

    final Instant start = NOW.minus(Period.ofWeeks(5));
    final Instant end = NOW.plus(Period.ofWeeks(5));

    final TreeNode node = createDatedTreeNode("Test1", start, end);
    root.addNode(node);

    final TreeNode other = createDatedTreeNode("Test1", start.minus(Period.ofWeeks(1)), end);
    root.addNode(other);

    final Range<Instant> range = new Range<>(start.minus(Period.ofWeeks(1)), end);
    assertEquals(range, node.getDateRange());
}
 
Example 2
Project: swblocks-decisiontree   File: DatedEvaluatorTest.java   View Source Code Vote up 6 votes
@Test
public void testFiveRules() {
    final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder = ruleSetBuilder();
    final Instant now = Instant.now();
    final Instant start = now.minus(Period.ofWeeks(1));
    final Instant finish = now.plus(Period.ofWeeks(4));

    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "*", "CME", "*", "*", "INDEX", start, finish, 1L, "1.1");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "*", "CME", "S&P", "*", "INDEX", start, finish, 2L, "1.2");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "VOICE", "CME", "ED", "*", "RATE", start, finish, 3L, "1.4");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "VOICE", "*", "*", "US", "*", start, finish, 4L, "1.5");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "*", "*", "*", "US", "*", start, finish, 5L, "1.2");

    final DecisionTreeRuleSet ruleSet = ruleSetBuilder.build();
    final TreeNode node = constructTree(ruleSet);
    Assert.assertNotNull(node);

    checkMatch(inputA, now, node, 3L);
    checkMatch(inputB, now, node, 4L);
    checkMatch(inputC, now, node, 4L);
    checkMatch(inputE, now, node, 5L);

    checkNoMatch(inputD, now, node);
    checkNoMatch(inputF, now, node);
}
 
Example 3
Project: swblocks-decisiontree   File: DatedEvaluatorTest.java   View Source Code Vote up 6 votes
@Test
public void testFourRules() {
    final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder = ruleSetBuilder();
    final Instant now = Instant.now();
    final Instant start = now.minus(Period.ofWeeks(1));
    final Instant finish = now.plus(Period.ofWeeks(4));

    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "*", "CME", "*", "*", "INDEX", start, finish, 1L, "1.1");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "*", "CME", "S&P", "*", "INDEX", start, finish, 2L, "1.2");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "VOICE", "CME", "ED", "*", "RATE", start, finish, 3L, "1.4");
    CommisionRuleSetSupplier.addRule(ruleSetBuilder, "VOICE", "*", "*", "US", "*", start, finish, 4L, "1.5");

    final DecisionTreeRuleSet ruleSet = ruleSetBuilder.build();
    final TreeNode node = constructTree(ruleSet);
    Assert.assertNotNull(node);

    checkMatch(inputA, now, node, 3L);
    checkMatch(inputB, now, node, 4L);
    checkMatch(inputC, now, node, 4L);

    checkNoMatch(inputD, now, node);
    checkNoMatch(inputE, now, node);
    checkNoMatch(inputF, now, node);
}
 
Example 4
Project: pure-bliss-with-pure-java-functions   File: OfflineDevicesJobTests.java   View Source Code Vote up 6 votes
@Test
public void thatPushNotificationIsSentWhenSingleThresholdWasPassedAndLastNotificationWasSentBeforeDeviceDisconnected() throws Exception {
    Duration threshold = Duration.ofDays(1);
    Instant disconnectInstant = Instant.parse("2010-10-10T10:10:00.00Z");
    Instant lastOfflineNotificationInstant = disconnectInstant.minus(1, ChronoUnit.DAYS);
    Instant jobRunInstant = disconnectInstant.plus(threshold).plusSeconds(1);

    when(pushNotificationService.getLastOfflineNotificationInstant(any(Device.class))).thenReturn(Optional.of(lastOfflineNotificationInstant));

    when(clock.instant()).thenReturn(disconnectInstant);

    offlineDevicesJob.onConfigurationUpdate(Collections.singletonList(threshold));
    offlineDevicesJob.onDeviceDisconnect(new Device(UUID.randomUUID()));

    when(clock.instant()).thenReturn(jobRunInstant);

    offlineDevicesJob.run();

    verify(pushNotificationService, times(1)).sendOfflineNotification(any(Device.class));
}
 
Example 5
Project: SensorThingsProcessor   File: ValidatorAfter.java   View Source Code Vote up 5 votes
@Override
public void configure(JsonElement config, SensorThingsService context, Object edtCtx) {
    getConfigEditor(context, edtCtx).setConfig(config);
    Instant now = Instant.now();
    refTime = now.minus(Days.of(editorDays.getValue()));
    refTime = refTime.minus(Minutes.of(editorMinutes.getValue()));
}
 
Example 6
Project: ProjectAres   File: InactivePlayerListener.java   View Source Code Vote up 5 votes
@Override
public void tick() {
    final Duration timeout = config.timeout();
    final Duration warning = config.warning();

    Instant now = Instant.now();
    Instant kickTime = now.minus(timeout);
    Instant warnTime = warning == null ? null : now.minus(warning);
    Instant lastWarnTime = warning == null || lastCheck == null ? null : lastCheck.minus(warning);

    // Iterate over a copy, because kicking players while iterating the original
    // OnlinePlayerMapAdapter throws a ConcurrentModificationException
    for(Map.Entry<Player, Instant> entry : lastActivity.entrySetCopy()) {
        Player player = entry.getKey();
        Instant time = entry.getValue();

        if(time.isBefore(kickTime)) {
            playerServerChanger.kickPlayer(player, CommonsTranslations.get().t("afk.kick", player));
        } else if(warnTime != null && time.isAfter(lastWarnTime) && !time.isAfter(warnTime)) {
            player.playSound(player.getLocation(), Sound.BLOCK_NOTE_PLING, 1, 1);
            player.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD + CommonsTranslations.get().t(
                "afk.warn", player,
                ChatColor.AQUA.toString() + ChatColor.BOLD +
                    timeout.minus(warning).getSeconds() +
                    ChatColor.RED + ChatColor.BOLD
            ));
        }
    }

    lastCheck = now;
}
 
Example 7
Project: rskj   File: HashRateCalculator.java   View Source Code Vote up 5 votes
protected BigInteger calculateHashRate(Predicate<BlockHeaderElement> countCondition, Duration period) {
    if (hasBestBlock()) {
        Instant upto = Clock.systemUTC().instant();
        Instant from = upto.minus(period);
        return this.hashRate(getHeaderElement(blockStore.getBestBlock().getHash()), countCondition, b -> checkBlockTimeRange(b, from, upto));
    }
    return BigInteger.ZERO;
}
 
Example 8
Project: verify-matching-service-adapter   File: DurationNotExceededValidatorTest.java   View Source Code Vote up 5 votes
@Test
public void validationAddsErrorWhenMaximumDurationToNowIsExceeded() {
    Messages messages = messages();
    Instant now = Instant.now();
    DurationNotExceededValidator<Object> validator = new DurationNotExceededValidator<>(DEFAULT_MESSAGE, context -> now.minus(6, MINUTES), Duration.parse("PT5M"));

    Messages returnedMessages = validator.validate(null, messages);
    assertThat(returnedMessages, sameInstance(messages));
    assertThat(returnedMessages.hasErrorLike(DEFAULT_MESSAGE), is(true));
}
 
Example 9
Project: swblocks-jbl   File: DateRangeTest.java   View Source Code Vote up 5 votes
@Test
public void testRangeCheck() {
    final Instant now = Instant.now();
    final Instant start = now.minus(5, ChronoUnit.DAYS);
    final Instant end = now.plus(5, ChronoUnit.DAYS);

    final DateRange dateRange = new DateRange(start, end);
    assertTrue(DateRange.RANGE_CHECK.test(dateRange, now));
    assertTrue(DateRange.RANGE_CHECK.test(dateRange, start));

    // End date is not considered part of the range.
    assertFalse(DateRange.RANGE_CHECK.test(dateRange, end));
}
 
Example 10
Project: swblocks-jbl   File: RangeTest.java   View Source Code Vote up 5 votes
@Test
public void testInstanceCheck() {
    final Instant now = Instant.now();
    final Instant start = now.minus(5, ChronoUnit.DAYS);
    final Instant end = now.plus(5, ChronoUnit.DAYS);

    final Range<Instant> instantRange = new Range<>(start, end);
    assertTrue(Range.RANGE_CHECK.test(instantRange, now));
    assertTrue(Range.RANGE_CHECK.test(instantRange, start));

    // End date is not considered part of the range.
    assertFalse(Range.RANGE_CHECK.test(instantRange, end));
}
 
Example 11
Project: verify-matching-service-adapter   File: DurationNotExceededValidatorTest.java   View Source Code Vote up 5 votes
@Test
public void validationAddsErrorWhenMaximumDurationIsExceeded() {
    Messages messages = messages();
    Instant now = Instant.now();
    DurationNotExceededValidator<Object> validator = new DurationNotExceededValidator<>(DEFAULT_MESSAGE, context -> now.minus(6, MINUTES), context -> now, Duration.parse("PT5M"));

    Messages returnedMessages = validator.validate(null, messages);
    assertThat(returnedMessages, sameInstance(messages));
    assertThat(returnedMessages.hasErrorLike(DEFAULT_MESSAGE), is(true));
}
 
Example 12
Project: swblocks-decisiontree   File: DatedEvaluatorTest.java   View Source Code Vote up 4 votes
@Test
public void testAlternativePathsFailurePathsAndValueGroups() {
    final Instant now = Instant.now();
    final Instant start = now.minus(Period.ofWeeks(1));
    final Instant finish = now.plus(Period.ofWeeks(4));

    final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder = RuleSetBuilder.creator(Arrays.asList(
            "MARKUP_CODE", "CLIENT_ACCOUNT", "CLIENT_SPN", "ADVISOR_SPN", "EXECUTION_VENUE", "MEMBERSHIP",
            "SECURITY_TYPE", "CONTRACT", "FEE_GROUP", "PRODUCT_GROUP", "EXCHANGE", "REGION"));

    ruleSetBuilder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("CLM", "*", "VG:AdVG1589CLM:0152035:03227805:0521659",
                    "VG:VG1589CLM:0151488:4679563:7888805", "*", "*", "*", "*", "381", "Equity indices",
                    "VG:IFEU:IFLL", "ER"))
            .with(RuleBuilder::start, start)
            .with(RuleBuilder::end, finish)
            .with(RuleBuilder::setId, new UUID(0, 1L)));

    ruleSetBuilder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("CLM", "*", "VG:AdVG1589CLM:0152035:03227805:0521659",
                    "VG:VG1589CLM:0151488:4679563:7888805", "*", "*", "*", "*", "*", "*", "VG:IFEU:IFLL", "ER"))
            .with(RuleBuilder::start, start)
            .with(RuleBuilder::end, finish)
            .with(RuleBuilder::setId, new UUID(0, 2L)));

    ruleSetBuilder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("CLM", "*", "VG:AdVG1589CLM:0152035:03227805:0521659",
                    "VG:AdVG1589CLM:0151488:3679563:6888805", "*", "*", "*", "*", "*", "*", "VG:IFEU:IFLL", "ER"))
            .with(RuleBuilder::start, start)
            .with(RuleBuilder::end, finish)
            .with(RuleBuilder::setId, new UUID(0, 3L)));

    ruleSetBuilder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("CLM", "*", "VG:AdVG1589CLM:0152035:03227805:0521659",
                    "VG:VG1589CLM:0151488:4679563:7888805", "ELEC", "NMEM", "*", "*", "123", "Equity indices",
                    "VG:IFEU:IFLL", "ER"))
            .with(RuleBuilder::start, start)
            .with(RuleBuilder::end, finish)
            .with(RuleBuilder::setId, new UUID(0, 4L)));

    final DecisionTreeRuleSet ruleSet = ruleSetBuilder.build();
    final TreeNode node = constructTree(ruleSet);
    Assert.assertNotNull(node);

    final List<String> inputs = Arrays.asList("CLM", "A102059551", "0152035", "0151488",
            "ELEC", "NMEM", "FUTURE", "Y2", "381", "Equity indices", "IFLL", "ER");
    final Optional<UUID> result = Evaluator.singleEvaluate(inputs, now, node);
    assertTrue(result.isPresent());
    assertEquals(new UUID(0, 1L), result.get());
}
 
Example 13
Project: openjdk-jdk10   File: TCKInstant.java   View Source Code Vote up 4 votes
@Test(expectedExceptions=DateTimeException.class)
public void minus_Duration_overflowTooBig() {
    Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999);
    i.minus(Duration.ofSeconds(-1, 999999999));
}
 
Example 14
Project: jdk8u-jdk   File: TCKInstant.java   View Source Code Vote up 4 votes
@Test(expectedExceptions=DateTimeException.class)
public void minus_Duration_overflowTooSmall() {
    Instant i = Instant.ofEpochSecond(MIN_SECOND);
    i.minus(Duration.ofSeconds(0, 1));
}
 
Example 15
Project: aws-sdk-java-v2   File: HttpCredentialsProvider.java   View Source Code Vote up 4 votes
private Instant getStaleTime(Instant expiration) {
    return expiration == null ? null
                              : expiration.minus(Duration.ofMinutes(1));
}
 
Example 16
Project: openjdk-jdk10   File: TCKInstant.java   View Source Code Vote up 4 votes
@Test(expectedExceptions=DateTimeException.class)
public void minus_Duration_overflowTooSmall() {
    Instant i = Instant.ofEpochSecond(MIN_SECOND);
    i.minus(Duration.ofSeconds(0, 1));
}
 
Example 17
Project: bitflyer4j   File: ThrottlerImpl.java   View Source Code Vote up 2 votes
@Override
public void run() {

    try {

        while (!executor.isShutdown()) {

            Instant now = environment.getNow();

            Duration interval = environment.getHttpLimitInterval();

            Instant cutoff = now.minus(interval);

            log.trace("Cleaning : Now=[{}] Interval=[{}] Cutoff=[{}]", now, interval, cutoff);

            SortedSet<Instant> times = new TreeSet<>();

            queues.forEach((k, v) -> {

                while (!v.isEmpty()) {

                    Instant time = v.peek().get();

                    if (time == null) {
                        break; // Race Condition with "AtomicLong#set(long)"
                    }

                    if (time.isAfter(cutoff)) {

                        times.add(time);

                        break; // Not expired yet.

                    }

                    v.remove();

                    log.trace("Cleared : {} - {} ", k, time);

                }

            });

            Instant earliest = times.isEmpty() ? now : times.first();

            Duration sleep = Duration.between(now, earliest.plus(interval));

            log.trace("Scheduling next clean : {}", sleep);

            NANOSECONDS.sleep(sleep.toNanos());

        }

    } catch (InterruptedException e) {

        log.warn("Cleaning interrupted.");

    }

}
 
Example 18
Project: cryptotrader   File: VwapEstimator.java   View Source Code Vote up 2 votes
protected Estimation estimate(Context context, Key key) {

        Instant now = key.getTimestamp();

        Instant from = now.minus(getDuration());

        List<Trade> trades = trimToEmpty(context.listTrades(key, from)).stream()
                .filter(Objects::nonNull)
                .filter(t -> t.getTimestamp() != null)
                .filter(t -> Objects.nonNull(t.getPrice()))
                .filter(t -> Objects.nonNull(t.getSize()))
                .filter(t -> t.getSize().signum() > 0)
                .sorted(COMPARATOR)
                .collect(Collectors.toList());

        if (trades.size() == 0) {
            return BAIL; // Cannot calculate returns if less than 2 points.
        }

        if (trades.size() == 1) {

            BigDecimal price = trades.get(trades.size() - 1).getPrice();

            return Estimation.builder().price(price).confidence(ZERO).build();

        }

        double vwap = calculateVwap(trades, now);

        double deviation = calculateDeviation(trades);

        double sigma = new TDistribution(trades.size() - 1).inverseCumulativeProbability(PROBABILITY);

        double last = trades.get(trades.size() - 1).getPrice().doubleValue();

        double drift = Math.min(1, Math.abs(Math.log(last / vwap)) / (deviation * sigma));

        BigDecimal p = BigDecimal.valueOf(vwap).setScale(SCALE, HALF_UP);

        BigDecimal c = Double.isNaN(drift) ? ZERO : BigDecimal.valueOf(1 - drift).setScale(SCALE, HALF_UP);

        log.debug("Estimated : {} (confidence=[{}] points=[{}] sigma=[{}] deviation=[{}])",
                p, c, trades.size(), sigma, deviation);

        return Estimation.builder().price(p).confidence(c).build();

    }
 
Example 19
Project: cryptotrader   File: TemplateAdviser.java   View Source Code Vote up 2 votes
@VisibleForTesting
BigDecimal calculateDeviation(Context context, Request request) {

    BigDecimal sigma = request.getTradingSigma();

    if (sigma.signum() <= 0) {
        return ZERO;
    }

    double highest = 0.0;

    for (Key key : trimToEmpty(getDeviationProducts(context, request))) {

        Integer samples = trim(request.getTradingSamples(), 0);

        while (samples >= SAMPLES) {

            Duration interval = Duration.between(request.getCurrentTime(), request.getTargetTime());

            Instant to = request.getCurrentTime();

            Instant from = to.minus(interval.toMillis() * samples, MILLIS);

            List<Trade> trades = context.listTrades(key, from.minus(interval));

            NavigableMap<Instant, BigDecimal> prices = collapsePrices(trades, interval, from, to, false);

            NavigableMap<Instant, BigDecimal> returns = calculateReturns(prices);

            SummaryStatistics stats = new SummaryStatistics();

            returns.values().stream().filter(Objects::nonNull).forEach(r -> stats.addValue(r.doubleValue()));

            double average = stats.getMean();

            double deviation = stats.getStandardDeviation() * sigma.doubleValue() + Math.abs(average);

            log.trace("Deviation Candidate : [{}.{}] {} (Samples=[{}] Sigma=[{}])",
                    key.getSite(), key.getInstrument(), deviation, samples, sigma);

            highest = Double.isFinite(deviation) ? Math.max(highest, deviation) : highest;

            samples = samples / 2;

        }

    }

    BigDecimal result = BigDecimal.valueOf(highest).setScale(SCALE, HALF_UP);

    log.trace("Deviation : {}", result);

    return result;

}
 
Example 20
Project: cryptotrader   File: CoincheckContext.java   View Source Code Vote up 2 votes
@VisibleForTesting
boolean appendCache(String id, CoincheckTrade trade) {

    if (trade == null || trade.getTimestamp() == null) {
        return false;
    }

    if (trade.getPrice() == null || trade.getPrice().signum() <= 0) {
        return false;
    }

    if (trade.getSize() == null || trade.getSize().signum() <= 0) {
        return false;
    }

    NavigableMap<Instant, CoincheckTrade> map = trades.get(StringUtils.trimToEmpty(id));

    if (map == null) {
        return false;
    }

    Instant timestamp = trade.getTimestamp().truncatedTo(ChronoUnit.SECONDS);

    CoincheckTrade truncated = CoincheckTrade.builder()
            .id(timestamp.getEpochSecond())
            .timestamp(timestamp)
            .price(trade.getPrice())
            .size(trade.getSize())
            .build();

    map.merge(timestamp, truncated, (t1, t2) -> {

        BigDecimal n1 = t1.getPrice().multiply(t1.getSize());
        BigDecimal n2 = t2.getPrice().multiply(t2.getSize());

        BigDecimal n = n1.add(n2);
        BigDecimal s = t1.getSize().add(t2.getSize());
        BigDecimal p = n.divide(s, SCALE, HALF_UP);

        return CoincheckTrade.builder().id(timestamp.getEpochSecond())
                .timestamp(timestamp).price(p).size(s).build();

    });

    Instant cutoff = timestamp.minus(TRADE_EXPIRY);

    while (true) {

        Map.Entry<Instant, ?> entry = map.firstEntry();

        if (entry == null || entry.getKey().isAfter(cutoff)) {
            break;
        }

        map.remove(entry.getKey());

    }

    return true;

}