Java Code Examples for java.time.ZonedDateTime#plus()

The following examples show how to use java.time.ZonedDateTime#plus() . 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: ExpChartController.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * グラフデータを読み込み
 * 
 * @param type 種類
 * @param scale 期間
 * @param min 期間の最小(自身を含む)
 * @param max 期間の最大(自身を含まない)
 * @return グラフデータ
 */
private Map<ZonedDateTime, Double> load(TypeOption type, ScaleOption scale, ZonedDateTime min, ZonedDateTime max) {
    Map<ZonedDateTime, Double> map = new LinkedHashMap<>();
    // 空のデータを作る
    ZonedDateTime current = min;
    while (current.compareTo(max) < 0) {
        map.put(current, 0D);
        current = current.plus(scale.getTick());
    }
    // ログから読み込み
    Instant minInstant = min.toInstant();
    Instant maxInstant = max.toInstant();

    List<SimpleBattleLog> logs = BattleLogs.readSimpleLog(log -> {
        Instant a = log.getDate().toInstant();
        return a.compareTo(minInstant) >= 0 && a.compareTo(maxInstant) < 0;
    });
    map.putAll(logs.stream()
            .collect(Collectors.groupingBy(log -> scale.convert(log.getDate(), type),
                    Collectors.summingDouble(type::convert))));
    return map;
}
 
Example 2
Source File: WalkForward.java    From ta4j-origins with MIT License 6 votes vote down vote up
/**
 * Returns a new time series which is a view of a subset of the current series.
 * <p>
 * The new series has begin and end indexes which correspond to the bounds of the sub-set into the full series.<br>
 * The tick of the series are shared between the original time series and the returned one (i.e. no copy).
 * @param series the time series to get a sub-series of
 * @param beginIndex the begin index (inclusive) of the time series
 * @param duration the duration of the time series
 * @return a constrained {@link TimeSeries time series} which is a sub-set of the current series
 */
public static TimeSeries subseries(TimeSeries series, int beginIndex, Duration duration) {

    // Calculating the sub-series interval
    ZonedDateTime beginInterval = series.getTick(beginIndex).getEndTime();
    ZonedDateTime endInterval = beginInterval.plus(duration);

    // Checking ticks belonging to the sub-series (starting at the provided index)
    int subseriesNbTicks = 0;
    int endIndex = series.getEndIndex();
    for (int i = beginIndex; i <= endIndex; i++) {
        // For each tick...
        ZonedDateTime tickTime = series.getTick(i).getEndTime();
        if (tickTime.isBefore(beginInterval) || !tickTime.isBefore(endInterval)) {
            // Tick out of the interval
            break;
        }
        // Tick in the interval
        // --> Incrementing the number of ticks in the subseries
        subseriesNbTicks++;
    }

    return new BaseTimeSeries(series, beginIndex, beginIndex + subseriesNbTicks - 1);
}
 
Example 3
Source File: ScheduledTaskTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testNextFormattedRuntime() {
    final Long millisecondsToNextRun = 10000L;
    ZonedDateTime currentUTCTime = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime expectedDateTime = currentUTCTime.plus(millisecondsToNextRun, ChronoUnit.MILLIS);
    int seconds = expectedDateTime.getSecond();
    if (seconds >= 30) {
        expectedDateTime = expectedDateTime.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
    } else {
        expectedDateTime = expectedDateTime.truncatedTo(ChronoUnit.MINUTES);
    }
    String expectedNextRunTime = expectedDateTime.format(DateTimeFormatter.ofPattern(ScheduledTask.FORMAT_PATTERN)) + " UTC";

    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.getDelay(TimeUnit.MILLISECONDS)).thenReturn(millisecondsToNextRun);
    task.scheduleExecution(validCronExpression);
    Optional<String> nextRunTime = task.getFormatedNextRunTime();
    assertTrue(nextRunTime.isPresent());
    String nextTime = nextRunTime.get();
    assertEquals(expectedNextRunTime, nextTime);
}
 
Example 4
Source File: ScheduledTask.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
public Optional<String> getFormatedNextRunTime() {
    Optional<Long> msToNextRun = getMillisecondsToNextRun();
    if (msToNextRun.isPresent()) {

        ZonedDateTime currentUTCTime = ZonedDateTime.now(ZoneOffset.UTC);
        ZonedDateTime nextRunTime = currentUTCTime.plus(msToNextRun.get(), ChronoUnit.MILLIS);
        int seconds = nextRunTime.getSecond();
        if (seconds >= 30) {
            nextRunTime = nextRunTime.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
        } else {
            nextRunTime = nextRunTime.truncatedTo(ChronoUnit.MINUTES);
        }
        String formattedString = nextRunTime.format(DateTimeFormatter.ofPattern(FORMAT_PATTERN));
        return Optional.of(formattedString + " UTC");
    }
    return Optional.empty();
}
 
Example 5
Source File: PlusTimeFilter.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Override
public Object filter(
  Object var,
  JinjavaInterpreter interpreter,
  Object[] args,
  Map<String, Object> kwargs
) {
  long diff = parseDiffAmount(interpreter, args);
  ChronoUnit chronoUnit = parseChronoUnit(interpreter, args);

  if (var instanceof ZonedDateTime) {
    ZonedDateTime dateTime = (ZonedDateTime) var;
    return new PyishDate(dateTime.plus(diff, chronoUnit));
  } else if (var instanceof PyishDate) {
    PyishDate pyishDate = (PyishDate) var;
    return new PyishDate(pyishDate.toDateTime().plus(diff, chronoUnit));
  } else if (var instanceof Number) {
    Number timestamp = (Number) var;
    ZonedDateTime zonedDateTime = Functions.getDateTimeArg(timestamp, ZoneOffset.UTC);
    return new PyishDate(zonedDateTime.plus(diff, chronoUnit));
  }

  return var;
}
 
Example 6
Source File: Calendar.java    From calendar-component with Apache License 2.0 6 votes vote down vote up
private void setActionsForEachHalfHour(Map<CalendarDateRange, Set<Action>> actionMap,
                                       ZonedDateTime start, ZonedDateTime end, Action.Handler actionHandler) {

    ZonedDateTime actionTime = start;
    while (actionTime.isBefore(end)) {

        ZonedDateTime endTime = actionTime.plus(30, ChronoUnit.MINUTES);

        CalendarDateRange range = new CalendarDateRange(actionTime, endTime);

        Action[] actions = actionHandler.getActions(range, this);
        if (actions != null) {
            Set<Action> actionSet = new LinkedHashSet<>(Arrays.asList(actions));
            actionMap.put(range, actionSet);
        }

        actionTime = endTime;
    }
}
 
Example 7
Source File: RangeBasicTests.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "ZonedDateTimeRanges")
public void testRangeOfZonedDateTimes(ZonedDateTime start, ZonedDateTime end, Duration step, boolean parallel) {
    final Range<ZonedDateTime> range = Range.of(start, end, step);
    final Array<ZonedDateTime> array = range.toArray(parallel);
    final boolean ascend = start.isBefore(end);
    final int expectedLength = (int)Math.ceil(Math.abs((double)ChronoUnit.SECONDS.between(start, end)) / (double)step.getSeconds());
    Assert.assertEquals(array.length(), expectedLength);
    Assert.assertEquals(array.typeCode(), ArrayType.ZONED_DATETIME);
    Assert.assertTrue(!array.style().isSparse());
    Assert.assertEquals(range.start(), start, "The range start");
    Assert.assertEquals(range.end(), end, "The range end");
    ZonedDateTime expected = null;
    for (int i=0; i<array.length(); ++i) {
        final ZonedDateTime actual = array.getValue(i);
        expected = expected == null ? start : ascend ? expected.plus(step) : expected.minus(step);
        Assert.assertEquals(actual, expected, "Value matches at " + i);
        Assert.assertTrue(ascend ? actual.compareTo(start) >=0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + i);
    }
}
 
Example 8
Source File: RangeFilterTests.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "ZonedDateTimeRanges")
public void testRangeOfZonedDateTimes(ZonedDateTime start, ZonedDateTime end, Duration step, boolean parallel) {
    final boolean ascend = start.isBefore(end);
    final Range<ZonedDateTime> range = Range.of(start, end, step, v -> v.getHour() == 6);
    final Array<ZonedDateTime> array = range.toArray(parallel);
    final ZonedDateTime first = array.first(v -> true).map(ArrayValue::getValue).get();
    final ZonedDateTime last = array.last(v -> true).map(ArrayValue::getValue).get();
    Assert.assertEquals(array.typeCode(), ArrayType.ZONED_DATETIME);
    Assert.assertTrue(!array.style().isSparse());
    Assert.assertEquals(range.start(), start, "The range start");
    Assert.assertEquals(range.end(), end, "The range end");
    int index = 0;
    ZonedDateTime value = first;
    while (ascend ? value.isBefore(last) : value.isAfter(last)) {
        final ZonedDateTime actual = array.getValue(index);
        Assert.assertEquals(actual, value, "Value matches at " + index);
        Assert.assertTrue(ascend ? actual.compareTo(start) >= 0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + index);
        value = ascend ? value.plus(step) : value.minus(step);
        while (value.getHour() == 6) value = ascend ? value.plus(step) : value.minus(step);
        index++;
    }
}
 
Example 9
Source File: DaylightSavingTimeJavaTimeExamplesUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
    ZoneId italianZoneId = ZoneId.of("Europe/Rome");

    LocalDateTime localDateTimeBeforeDST = LocalDateTime.of(2018, 3, 25, 1, 55);
    System.out.println(localDateTimeBeforeDST);
    assertThat(localDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55");

    ZonedDateTime zonedDateTimeBeforeDST = localDateTimeBeforeDST.atZone(italianZoneId);
    prettyPrint(zonedDateTimeBeforeDST);
    assertThat(zonedDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55+01:00[Europe/Rome]");

    ZonedDateTime zonedDateTimeAfterDST = zonedDateTimeBeforeDST.plus(10, ChronoUnit.MINUTES);
    prettyPrint(zonedDateTimeAfterDST);
    assertThat(zonedDateTimeAfterDST.toString()).isEqualTo("2018-03-25T03:05+02:00[Europe/Rome]");

    Long deltaBetweenDatesInMinutes = ChronoUnit.MINUTES.between(zonedDateTimeBeforeDST, zonedDateTimeAfterDST);
    assertThat(deltaBetweenDatesInMinutes).isEqualTo(10);

}
 
Example 10
Source File: MetricsServiceImpl.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Intended to be used at the startup of the MetricsServiceImpl to ensure we have enough tables for processing
 */
public void verifyAndCreateTempTables() {
    ZonedDateTime currentBlock = ZonedDateTime.ofInstant(Instant.ofEpochMilli(DateTimeService.now.get().getMillis()), UTC)
            .with(DateTimeService.startOfPreviousEvenHour());

    ZonedDateTime lastStartupBlock = currentBlock.plus(6, ChronoUnit.HOURS);
    verifyAndCreateTempTables(currentBlock, lastStartupBlock).await();
}
 
Example 11
Source File: WalkForward.java    From ta4j-origins with MIT License 5 votes vote down vote up
/**
 * Builds a list of split indexes from splitDuration.
 * @param series the time series to get split begin indexes of
 * @param splitDuration the duration between 2 splits
 * @return a list of begin indexes after split
 */
public static List<Integer> getSplitBeginIndexes(TimeSeries series, Duration splitDuration) {
    ArrayList<Integer> beginIndexes = new ArrayList<>();

    int beginIndex = series.getBeginIndex();
    int endIndex = series.getEndIndex();
    
    // Adding the first begin index
    beginIndexes.add(beginIndex);

    // Building the first interval before next split
    ZonedDateTime beginInterval = series.getFirstTick().getEndTime();
    ZonedDateTime endInterval = beginInterval.plus(splitDuration);

    for (int i = beginIndex; i <= endIndex; i++) {
        // For each tick...
        ZonedDateTime tickTime = series.getTick(i).getEndTime();
        if (tickTime.isBefore(beginInterval) || !tickTime.isBefore(endInterval)) {
            // Tick out of the interval
            if (!endInterval.isAfter(tickTime)) {
                // Tick after the interval
                // --> Adding a new begin index
                beginIndexes.add(i);
            }

            // Building the new interval before next split
            beginInterval = endInterval.isBefore(tickTime) ? tickTime : endInterval;
            endInterval = beginInterval.plus(splitDuration);
        }
    }
    return beginIndexes;
}
 
Example 12
Source File: FindResult.java    From find with MIT License 5 votes vote down vote up
@SuppressWarnings("TypeMayBeWeakened")
private ZonedDateTime parseRelativeTime(final ZonedDateTime timeNow, final int timeAmount, final String timeUnit) {
    TemporalUnit temporalUnit = ChronoUnit.SECONDS;
    switch (timeUnit) {
        case "minute":
        case "minutes":
            temporalUnit = ChronoUnit.MINUTES;
            break;

        case "hour":
        case "hours":
            temporalUnit = ChronoUnit.HOURS;
            break;

        case "day":
        case "days":
            temporalUnit = ChronoUnit.DAYS;
            break;

        case "month":
        case "months":
            temporalUnit = ChronoUnit.MONTHS;
            break;

        case "year":
        case "years":
            temporalUnit = ChronoUnit.YEARS;
            break;
    }

    return timeNow.plus(timeAmount, temporalUnit);
}
 
Example 13
Source File: CoreSocketFactoryTest.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
private String createEphemeralCert(Duration shiftIntoPast)
    throws GeneralSecurityException, ExecutionException, IOException {
  Duration validFor = Duration.ofHours(1);
  ZonedDateTime notBefore = ZonedDateTime.now().minus(shiftIntoPast);
  ZonedDateTime notAfter = notBefore.plus(validFor);

  CertificateValidity interval =
      new CertificateValidity(Date.from(notBefore.toInstant()), Date.from(notAfter.toInstant()));

  X509CertInfo info = new X509CertInfo();
  info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
  info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(1));
  info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get("SHA1withRSA")));
  info.set(X509CertInfo.SUBJECT, new X500Name("C = US, O = Google\\, Inc, CN=temporary-subject"));
  info.set(X509CertInfo.KEY, new CertificateX509Key(Futures.getDone(clientKeyPair).getPublic()));
  info.set(X509CertInfo.VALIDITY, interval);
  info.set(
      X509CertInfo.ISSUER,
      new X500Name("C = US, O = Google\\, Inc, CN=Google Cloud SQL Signing CA foo:baz"));

  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec keySpec =
      new PKCS8EncodedKeySpec(decodeBase64StripWhitespace(TestKeys.SIGNING_CA_PRIVATE_KEY));
  PrivateKey signingKey = keyFactory.generatePrivate(keySpec);

  X509CertImpl cert = new X509CertImpl(info);
  cert.sign(signingKey, "SHA1withRSA");

  StringBuilder sb = new StringBuilder();
  sb.append("-----BEGIN CERTIFICATE-----\n");
  sb.append(Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})", "$1\n"));
  sb.append("\n");
  sb.append("-----END CERTIFICATE-----\n");

  return sb.toString();
}
 
Example 14
Source File: CsvTradesLoader.java    From ta4j-origins with MIT License 5 votes vote down vote up
/**
 * Builds a list of empty ticks.
 * @param beginTime the begin time of the whole period
 * @param endTime the end time of the whole period
 * @param duration the tick duration (in seconds)
 * @return the list of empty ticks
 */
private static List<Tick> buildEmptyTicks(ZonedDateTime beginTime, ZonedDateTime endTime, int duration) {

    List<Tick> emptyTicks = new ArrayList<>();

    Duration tickDuration = Duration.ofSeconds(duration);
    ZonedDateTime tickEndTime = beginTime;
    do {
        tickEndTime = tickEndTime.plus(tickDuration);
        emptyTicks.add(new BaseTick(tickDuration, tickEndTime));
    } while (tickEndTime.isBefore(endTime));

    return emptyTicks;
}
 
Example 15
Source File: HgRepositoryTest.java    From copybara with Apache License 2.0 4 votes vote down vote up
@Test
public void testLog() throws Exception {
  String user = "Copy Bara <[email protected]>";
  ZonedDateTime date = ZonedDateTime.now(ZoneId.of("+11:00")).truncatedTo(ChronoUnit.SECONDS);
  ZonedDateTime date2 = date.plus(1, ChronoUnit.SECONDS);
  ZonedDateTime date3 = date.plus(2, ChronoUnit.SECONDS);
  String desc = "one";
  String desc2 = "two";
  String desc3 = "three\nthree";

  Path newFile = Files.createTempFile(workDir, "foo", ".txt");
  String fileName = newFile.toString();
  repository.hg(workDir, "add", fileName);
  repository.hg(workDir, "commit", "-u", user, "-d", date.toString(), "-m", desc);

  repository.hg(workDir, "branch", "other");
  Files.write(workDir.resolve(fileName), "hello".getBytes(UTF_8));
  repository.hg(workDir, "commit", "-u", user, "-d", date2.toString(), "-m", desc2);

  Path remoteDir = Files.createTempDirectory("remotedir");
  HgRepository remoteRepo = new HgRepository(remoteDir, /*verbose*/false,
      CommandRunner.DEFAULT_TIMEOUT);
  remoteRepo.init();
  Path newFile2 = Files.createTempFile(remoteDir, "bar", ".txt");
  String fileName2 = newFile2.toString();
  remoteRepo.hg(remoteDir, "add", fileName2);
  remoteRepo.hg(remoteDir, "commit", "-u", user, "-d", date3.toString(), "-m", desc3);

  repository.pullAll(remoteDir.toString());

  ImmutableList<HgLogEntry> allCommits = repository.log().run();

  assertThat(allCommits.size()).isEqualTo(3);

  assertThat(allCommits.get(0).getParents()).hasSize(1);
  assertThat(allCommits.get(0).getParents().get(0))
      .isEqualTo("0000000000000000000000000000000000000000");
  assertThat(allCommits.get(1).getParents().get(0))
      .isEqualTo(allCommits.get(2).getGlobalId());
  assertThat(allCommits.get(2).getParents().get(0))
      .isEqualTo("0000000000000000000000000000000000000000");


  assertThat(allCommits.get(0).getUser()).isEqualTo("Copy Bara <[email protected]>");
  assertThat(allCommits.get(0).getUser()).isEqualTo(allCommits.get(1).getUser());
  assertThat(allCommits.get(0).getUser()).isEqualTo(allCommits.get(2).getUser());

  assertThat(allCommits.get(0).getZonedDate()).isEqualTo(date3);
  assertThat(allCommits.get(1).getZonedDate()).isEqualTo(date2);
  assertThat(allCommits.get(2).getZonedDate()).isEqualTo(date);

  assertThat(allCommits.get(0).getBranch()).isEqualTo("default");
  assertThat(allCommits.get(1).getBranch()).isEqualTo("other");
  assertThat(allCommits.get(2).getBranch()).isEqualTo("default");

  assertThat(allCommits.get(0).getFiles()).containsExactly(newFile2.getFileName().toString());
  assertThat(allCommits.get(1).getFiles()).containsExactly(newFile.getFileName().toString());
  assertThat(allCommits.get(2).getFiles()).containsExactly(newFile.getFileName().toString());

  assertThat(allCommits.get(0).getDescription()).isEqualTo(desc3);
  assertThat(allCommits.get(1).getDescription()).isEqualTo(desc2);
  assertThat(allCommits.get(2).getDescription()).isEqualTo(desc);

  ImmutableList<HgLogEntry> defaultCommits = repository.log()
      .withLimit(5)
      .withBranch("default")
      .run();
  assertThat(defaultCommits).hasSize(2);

  ImmutableList<HgLogEntry> otherCommits = repository.log()
      .withLimit(5)
      .withBranch("other")
      .run();
  assertThat(otherCommits).hasSize(1);
}
 
Example 16
Source File: OlympicModel2.java    From egads with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void train(final DataSequence data) throws Exception {
    initializeIndices(data, modelStartEpoch);
    
    final long size = data.size();
    ZonedDateTime model_ts = Instant.ofEpochSecond(modelStartEpoch)
            .atZone(zone);
    ZonedDateTime end_ts = model_ts.plus(windowSize, windowUnits);
    int prediction_index = 0;
    final List<WeightedValue> accumulator = Lists.newArrayList();
    
    // start the loop and break once we've filled the model.
    while (true) {
        accumulator.clear();
        for (int i = 0; i < windowTimes.length; i++) {
            if (indices[i] < 0 || indices[i] >= size) {
                continue;
            }
            
            // advance
            windowTimes[i] = windowTimes[i].plus(interval,
                    intervalUnits);
            long interval_end = windowTimes[i].toEpochSecond();
            final List<Double> doubles = Lists.newArrayList();
            long first_ts = -1;
            while (indices[i] < size
                    && data.get(indices[i]).time < interval_end) {
                if (Double.isFinite(data.get(indices[i]).value)) {
                    doubles.add((double) data.get(indices[i]).value);
                }
                if (first_ts < 0) {
                    first_ts = data.get(indices[i]).time;
                }
                indices[i]++;
            }

            if (!doubles.isEmpty()) {
                // TODO - for DST if we jumped back then we may have a
                // period
                // with more than we expect. In that case, depending on the
                // aggregator, we may need to use only part of the data.
                // TODO - potentially other aggregations.
                double sum = 0;
                for (final Double v : doubles) {
                    sum += v;
                }
                accumulator.add(
                        new WeightedValue((sum / doubles.size()), i + 1));
            }
        }

        if (drop_lowest > 0 || drop_highest > 0) {
            if (drop_highest > drop_lowest) {
                WeightedValue.drop(accumulator, drop_highest, true);
                WeightedValue.drop(accumulator, drop_lowest, false);
            } else {
                WeightedValue.drop(accumulator, drop_lowest, false);
                WeightedValue.drop(accumulator, drop_highest, true);
            }
        }
        
        model.add(new Pair<Long, Double>(model_ts.toEpochSecond(),
                WeightedValue.aggregate(accumulator, windowAggregator)));

        model_ts = model_ts.plus(interval, intervalUnits);
        if (model_ts.toEpochSecond() > end_ts.toEpochSecond()) {
            prediction_index++;
            if (prediction_index >= futureWindows) {
                break;
            }
            model_ts = Instant.ofEpochSecond(modelStartEpoch).atZone(zone);
            model_ts = model_ts.plus(
                    (windowDistanceInterval * prediction_index), 
                    windowDistanceIntervalUnits);
            end_ts = model_ts.plus(windowSize, windowUnits);
            for (int i = 0; i < windowTimes.length; i++) {
                windowTimes[i] = null;
                indices[i] = 0;
            }
            initializeIndices(data, model_ts.toEpochSecond());
        }
    }
}
 
Example 17
Source File: ProcessorListener.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public void determineNextResync(ZonedDateTime now) {
  this.nextResync = now.plus(this.resyncPeriodInMillis, ChronoUnit.MILLIS);
}
 
Example 18
Source File: DateExpression.java    From vividus with Apache License 2.0 4 votes vote down vote up
public ZonedDateTime processDuration(ZonedDateTime zonedDateTime)
{
    Duration duration = Duration.parse(DURATION_DESIGNATOR + getDurationString());
    return !hasMinusSign() ? zonedDateTime.plus(duration) : zonedDateTime.minus(duration);
}
 
Example 19
Source File: DateExpression.java    From vividus with Apache License 2.0 4 votes vote down vote up
public ZonedDateTime processPeriod(ZonedDateTime zonedDateTime)
{
    Period period = Period.parse(DURATION_DESIGNATOR + getPeriodString());
    return !hasMinusSign() ? zonedDateTime.plus(period) : zonedDateTime.minus(period);
}
 
Example 20
Source File: ZonedDateTimeAxis.java    From constellation with Apache License 2.0 4 votes vote down vote up
@Override
protected List<ZonedDateTime> calculateTickValues(double v, Object range) {
    final Object[] dateTimeRange = (Object[]) range;
    final ZonedDateTime lowerBound = (ZonedDateTime) dateTimeRange[0];
    final ZonedDateTime upperBound = (ZonedDateTime) dateTimeRange[1];

    List<ZonedDateTime> dateTimeList = new ArrayList<>();
    List<ZonedDateTime> previousDateTimeList = new ArrayList<>();
    Interval previousInterval = Interval.values()[0];

    // calculate the gap which should be between two tick marks.
    final double averageTickGap = 100;
    final double averageTicks = v / averageTickGap;

    // starting with the greatest interval, add one of each calendar unit.
    ZonedDateTime datetime = lowerBound;
    for (Interval interval : Interval.values()) {
        datetime = lowerBound;
        dateTimeList.clear();
        previousDateTimeList.clear();
        actualInterval = interval;

        // loop as long we exceeded the upper bound.
        while (datetime.toInstant().toEpochMilli() <= upperBound.toInstant().toEpochMilli()) {
            dateTimeList.add(datetime);
            datetime = datetime.plus(interval.amount, interval.interval);
        }
        // check the size of the list, if it is greater than the amount of ticks, take that list.
        if (dateTimeList.size() > averageTicks) {
            datetime = lowerBound;
            // recheck if the previous interval is better suited.
            while (datetime.toInstant().toEpochMilli() <= upperBound.toInstant().toEpochMilli()) {
                previousDateTimeList.add(datetime);
                datetime = datetime.plus(previousInterval.amount, previousInterval.interval);
            }
            break;
        }

        previousInterval = interval;
    }
    if (previousDateTimeList.size() - averageTicks > averageTicks - dateTimeList.size()) {
        dateTimeList = previousDateTimeList;
        actualInterval = previousInterval;
    }

    // finally, add the upper bound.
    dateTimeList.add(upperBound);

    List<ZonedDateTime> evenDateTimeList = makeDateTimesEven(dateTimeList);
    // if there are at least three datetimes, check if the gap between the lower datetime and the second datetime 
    // is at least half the gap of the second and third datetime, then repeat for the upper bound. 
    // if gaps between datetimes are too small, remove one of them (this can occur, e.g. if the lower bound is 25.12.2013 and years are shown; 
    // then the next year shown would be 2014 (01.01.2014) which would be too narrow to 25.12.2013).
    if (evenDateTimeList.size() > 2) {
        final ZonedDateTime secondDateTime = evenDateTimeList.get(1);
        final ZonedDateTime thirdDateTime = evenDateTimeList.get(2);
        final ZonedDateTime lastDateTime = evenDateTimeList.get(dateTimeList.size() - 2);
        final ZonedDateTime previousLastDateTime = evenDateTimeList.get(dateTimeList.size() - 3);

        // if the second date is too near by the lower bound, remove it.
        if (secondDateTime.toInstant().toEpochMilli() - lowerBound.toInstant().toEpochMilli() < (thirdDateTime.toInstant().toEpochMilli() - secondDateTime.toInstant().toEpochMilli()) / 2) {
            evenDateTimeList.remove(secondDateTime);
        }

        // if difference from the upper bound to the last date is less than the half of the difference of the previous two dates,
        // we better remove the last date, as it comes to close to the upper bound.
        if (upperBound.toInstant().toEpochMilli() - lastDateTime.toInstant().toEpochMilli() < (lastDateTime.toInstant().toEpochMilli() - previousLastDateTime.toInstant().toEpochMilli()) / 2) {
            evenDateTimeList.remove(lastDateTime);
        }
    }

    return evenDateTimeList;
}