java.time.temporal.ChronoUnit Java Examples

The following examples show how to use java.time.temporal.ChronoUnit. 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: ExecutionTest.java    From failsafe with Apache License 2.0 7 votes vote down vote up
public void shouldFallbackWaitTimeFromComputedToBackoffDelay() {
  Execution exec = new Execution(new RetryPolicy<>().withMaxAttempts(10)
      .withBackoff(1, 10, ChronoUnit.NANOS)
      .withDelay((r, f, ctx) -> Duration.ofNanos(ctx.getAttemptCount() % 2 == 0 ? ctx.getAttemptCount() * 2 : -1)));
  assertEquals(exec.getWaitTime().toNanos(), 0);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 1);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 4);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 2);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 8);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 4);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 12);
  exec.recordFailure(e);
  assertEquals(exec.getWaitTime().toNanos(), 8);
}
 
Example #2
Source File: EncodeGorillaTest.java    From gorilla-tsc with Apache License 2.0 6 votes vote down vote up
@Test
void simpleEncodeAndDecodeTest() throws Exception {
    long now = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS)
            .toInstant(ZoneOffset.UTC).toEpochMilli();

    Pair[] pairs = {
            new Pair(now + 10, Double.doubleToRawLongBits(1.0)),
            new Pair(now + 20, Double.doubleToRawLongBits(-2.0)),
            new Pair(now + 28, Double.doubleToRawLongBits(-2.5)),
            new Pair(now + 84, Double.doubleToRawLongBits(65537)),
            new Pair(now + 400, Double.doubleToRawLongBits(2147483650.0)),
            new Pair(now + 2300, Double.doubleToRawLongBits(-16384)),
            new Pair(now + 16384, Double.doubleToRawLongBits(2.8)),
            new Pair(now + 16500, Double.doubleToRawLongBits(-38.0))
    };

    comparePairsToCompression(now, pairs);
}
 
Example #3
Source File: TokenlessClientLogger.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    final String authorization = req.headers().get(HttpHeaderNames.AUTHORIZATION);
    if (authorization == null || !PATTERN.matcher(authorization).matches()) {
        final InetSocketAddress raddr = ctx.remoteAddress();
        final String ip = raddr.getAddress().getHostAddress();
        final Instant now = Instant.now(clock);
        final Instant lastReport = reportedAddresses.putIfAbsent(ip, now);
        final boolean report;
        if (lastReport == null) {
            report = true;
        } else if (ChronoUnit.DAYS.between(lastReport, now) >= 1) {
            report = reportedAddresses.replace(ip, lastReport, now);
        } else {
            report = false;
        }

        if (report) {
            report(raddr.getHostString(), ip);
        }
    }

    return unwrap().serve(ctx, req);
}
 
Example #4
Source File: ChattersTest.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Test
@DisplayName("Check that an expired mute is removed")
void expiredPlayerMutesAreExpunged() {
  when(session.getId()).thenReturn("session-id");
  final var chatterSession = buildChatterSession(session);
  chatters.connectPlayer(chatterSession);
  chatters.mutePlayer(
      chatterSession.getChatParticipant().getPlayerChatId(),
      20,
      Clock.fixed(now, ZoneOffset.UTC),
      messageBroadcaster);

  // current time is after the mute expiry, we expect the mute to be expunged
  chatters.getPlayerMuteExpiration(
      chatterSession.getIp(), Clock.fixed(now.plus(21, ChronoUnit.MINUTES), ZoneOffset.UTC));

  assertThat(
      "Querying for the mute again, this time with current time before the mute."
          + "Normally this would be a condition for a mute, but we expunged the mute."
          + "Given the mute is expunged, we expect an empty result.",
      chatters.getPlayerMuteExpiration(
          chatterSession.getIp(), Clock.fixed(now, ZoneOffset.UTC)),
      isEmpty());
}
 
Example #5
Source File: RegularDataEncoderLongTest.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
private List<String> getBetweenDateWithTwoSecond(String start, String end) {
  TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  List<String> list = new ArrayList<>();
  LocalDateTime startDate = LocalDateTime.parse(start);
  LocalDateTime endDate = LocalDateTime.parse(end);

  long distance = ChronoUnit.SECONDS.between(startDate, endDate);
  if (distance < 1) {
    return list;
  }
  Stream.iterate(startDate, d -> {
    return d.plusSeconds(2);
  }).limit((distance / 2) + 1).forEach(f -> {
    list.add(f.format(formatter));
  });
  return list;
}
 
Example #6
Source File: TestChronologyPerf.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_chronologyGetAvailablePerf() {
    long start = System.nanoTime();
    Set<Chronology> chronos = Chronology.getAvailableChronologies();
    long end = System.nanoTime();
    Duration d = Duration.of(end - start, ChronoUnit.NANOS);
    System.out.printf(" Cold Duration of Chronology.getAvailableChronologies(): %s%n", d);

    start = System.nanoTime();
    chronos = Chronology.getAvailableChronologies();
    end = System.nanoTime();
    d = Duration.of(end - start, ChronoUnit.NANOS);
    System.out.printf(" Warm Duration of Chronology.getAvailableChronologies(): %s%n", d);

    start = System.nanoTime();
    HijrahChronology.INSTANCE.date(1434, 1, 1);
    end = System.nanoTime();
    d = Duration.of(end - start, ChronoUnit.NANOS);
    System.out.printf(" Warm Duration of HijrahDate.date(1434, 1, 1): %s%n", d);
}
 
Example #7
Source File: PrometheusBasedResourceLimitChecks.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Calculates the period for which the resource usage like volume of used data, connection duration etc. 
 * is to be retrieved from the Prometheus server based on the mode defined by 
 * {@link TenantConstants#FIELD_PERIOD_MODE}.
 *
 * @param effectiveSince The point of time on which the resource limit came into effect.
 * @param currentDateTime The current date and time used for the resource usage period calculation.
 * @param mode The mode of the period defined by {@link TenantConstants#FIELD_PERIOD_MODE}.
 * @param periodInDays The number of days defined by {@link TenantConstants#FIELD_PERIOD_NO_OF_DAYS}. 
 * @return The period in days for which the resource usage is to be calculated.
 */
long calculateResourceUsagePeriod(
        final OffsetDateTime effectiveSince,
        final OffsetDateTime currentDateTime,
        final PeriodMode mode,
        final long periodInDays) {
    final long inclusiveDaysBetween = ChronoUnit.DAYS.between(effectiveSince, currentDateTime) + 1;
    switch (mode) {
    case DAYS:
        if (inclusiveDaysBetween > 0 && periodInDays > 0) {
            final long dataUsagePeriodInDays = inclusiveDaysBetween % periodInDays;
            return dataUsagePeriodInDays == 0 ? periodInDays : dataUsagePeriodInDays;
        }
        return 0L;
    case MONTHLY:
        if (YearMonth.from(currentDateTime).equals(YearMonth.from(effectiveSince))
                && effectiveSince.getDayOfMonth() != 1) {
            return inclusiveDaysBetween;
        }
        return currentDateTime.getDayOfMonth();
    default:
        return 0L;
    }
}
 
Example #8
Source File: TCKWeekFields.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="weekFields")
public void test_rangeWeekOfWeekBasedYear(DayOfWeek firstDayOfWeek, int minDays) {
    WeekFields weekFields = WeekFields.of(firstDayOfWeek, minDays);
    TemporalField dowField = weekFields.dayOfWeek();
    TemporalField wowByField = weekFields.weekOfWeekBasedYear();

    LocalDate day1 = LocalDate.of(2012, 1, weekFields.getMinimalDaysInFirstWeek());
    day1 = day1.with(wowByField, 1).with(dowField, 1);

    LocalDate day2 = LocalDate.of(2013, 1, weekFields.getMinimalDaysInFirstWeek());
    day2 = day2.with(wowByField, 1).with(dowField, 1);

    int expectedWeeks = (int)ChronoUnit.DAYS.between(day1, day2) / 7;

    ValueRange range = day1.range(wowByField);
    assertEquals(range.getMaximum(), expectedWeeks, "Range incorrect");
}
 
Example #9
Source File: ChronoLocalDateImpl.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    Objects.requireNonNull(endExclusive, "endExclusive");
    ChronoLocalDate end = getChronology().date(endExclusive);
    if (unit instanceof ChronoUnit) {
        switch ((ChronoUnit) unit) {
            case DAYS: return daysUntil(end);
            case WEEKS: return daysUntil(end) / 7;
            case MONTHS: return monthsUntil(end);
            case YEARS: return monthsUntil(end) / 12;
            case DECADES: return monthsUntil(end) / 120;
            case CENTURIES: return monthsUntil(end) / 1200;
            case MILLENNIA: return monthsUntil(end) / 12000;
            case ERAS: return end.getLong(ERA) - getLong(ERA);
        }
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    Objects.requireNonNull(unit, "unit");
    return unit.between(this, end);
}
 
Example #10
Source File: FilterFluxTest.java    From influxdb-client-java with MIT License 6 votes vote down vote up
@Test
void filterDoubleAndRegexpValue() {

    Restrictions restriction = Restrictions.and(
            Restrictions.tag("instance_type").equal(Pattern.compile("/prod/")),
            Restrictions.field().greater(10.5D),
            Restrictions.time().lessOrEqual(new TimeInterval(-15L, ChronoUnit.HOURS))
    );

    Flux flux = Flux
            .from("telegraf")
            .filter(restriction)
            .range(-4L, 2L, ChronoUnit.HOURS)
            .count();

    String expected = "from(bucket:\"telegraf\") |> filter(fn: (r) => (r[\"instance_type\"]==/prod/ and r[\"_field\"] > 10.5 and r[\"_time\"] <= -15h)) |> "
            + "range(start:-4h, stop:2h) |> count()";

    Assertions.assertThat(flux.toString()).isEqualToIgnoringWhitespace(expected);
}
 
Example #11
Source File: TCKLocalDate.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_isSupported_TemporalUnit() {
    assertEquals(TEST_2007_07_15.isSupported((TemporalUnit) null), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.NANOS), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MICROS), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MILLIS), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.SECONDS), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MINUTES), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.HOURS), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.HALF_DAYS), false);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.DAYS), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.WEEKS), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MONTHS), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.YEARS), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.DECADES), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.CENTURIES), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MILLENNIA), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.ERAS), true);
    assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.FOREVER), false);
}
 
Example #12
Source File: TradesChartsViewModel.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
Date roundToTick(Date time, TickUnit tickUnit) {
    ZonedDateTime zdt = time.toInstant().atZone(ZoneId.systemDefault());
    LocalDateTime tradeLocal = zdt.toLocalDateTime();

    switch (tickUnit) {
        case YEAR:
            return Date.from(tradeLocal.withMonth(1).withDayOfYear(1).withHour(0).withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
        case MONTH:
            return Date.from(tradeLocal.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
        case WEEK:
            int dayOfWeek = tradeLocal.getDayOfWeek().getValue();
            LocalDateTime firstDayOfWeek = ChronoUnit.DAYS.addTo(tradeLocal, 1 - dayOfWeek);
            return Date.from(firstDayOfWeek.withHour(0).withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
        case DAY:
            return Date.from(tradeLocal.withHour(0).withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
        case HOUR:
            return Date.from(tradeLocal.withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
        case MINUTE_10:
            return Date.from(tradeLocal.withMinute(tradeLocal.getMinute() - tradeLocal.getMinute() % 10).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
        default:
            return Date.from(tradeLocal.atZone(ZoneId.systemDefault()).toInstant());
    }
}
 
Example #13
Source File: DurationTimeTimerEventTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testVariableExpressionBoundaryTimerEvent() {
    HashMap<String, Object> variables = new HashMap<>();
    variables.put("duration", Duration.ofSeconds(100));

    Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
    processEngineConfiguration.getClock().setCurrentTime(Date.from(yesterday));
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("testDurationExpressionOnBoundaryTimer", variables);

    TimerJobQuery jobQuery = managementService.createTimerJobQuery().processInstanceId(pi.getId());
    List<Job> jobs = jobQuery.list();
    assertThat(jobs).hasSize(1);
    assertThat(simpleDateFormat.format(jobs.get(0).getDuedate())).isEqualTo(simpleDateFormat.format(Date.from(yesterday.plus(100, ChronoUnit.SECONDS))));
    processEngineConfiguration.getClock().setCurrentTime(Date.from(yesterday.plus(200, ChronoUnit.SECONDS)));

    waitForJobExecutorToProcessAllJobs(10000L, 25L);
    assertThat(jobQuery.count()).isZero();

    assertProcessEnded(pi.getId());
    processEngineConfiguration.getClock().reset();
}
 
Example #14
Source File: ConsistentKeyLockerTest.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
/**
 * Test locker when first attempt to write to the store takes too long (but
 * succeeds). Expected behavior is to call mutate on the store, adding a
 * column with a new timestamp and deleting the column with the old
 * (too-slow-to-write) timestamp.
 *
 * @throws com.thinkaurelius.titan.diskstorage.BackendException shouldn't happen
 */
@Test
public void testWriteLockRetriesAfterOneStoreTimeout() throws BackendException {
    expect(lockState.has(defaultTx, defaultLockID)).andReturn(false);
    recordSuccessfulLocalLock();
    StaticBuffer firstCol = recordSuccessfulLockWrite(5, ChronoUnit.SECONDS, null).col; // too slow
    LockInfo secondLI = recordSuccessfulLockWrite(1, ChronoUnit.NANOS, firstCol); // plenty fast
    recordSuccessfulLocalLock(secondLI.tsNS);
    lockState.take(eq(defaultTx), eq(defaultLockID), eq(secondLI.stat));
    ctrl.replay();

    locker.writeLock(defaultLockID, defaultTx); // SUT
}
 
Example #15
Source File: TCKDuration.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test()
public void test_getUnit() {
    Duration test = Duration.ofSeconds(2000, 1000);
    long seconds = test.get(ChronoUnit.SECONDS);
    assertEquals(seconds, 2000, "duration.get(SECONDS)");
    long nanos = test.get(ChronoUnit.NANOS);
    assertEquals(nanos, 1000, "duration.get(NANOS)");
}
 
Example #16
Source File: RedissonReactiveStreamCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ReactiveRedisConnection.CommandResponse<PendingRecordsCommand, PendingMessages>> xPending(Publisher<PendingRecordsCommand> publisher) {
    return execute(publisher, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getGroupName(), "Group name must not be null!");

        byte[] k = toByteArray(command.getKey());

        List<Object> params = new ArrayList<>();
        params.add(k);

        params.add(((Range.Bound<String>)command.getRange().getLowerBound()).getValue().orElse("-"));
        params.add(((Range.Bound<String>)command.getRange().getUpperBound()).getValue().orElse("+"));

        if (command.getCount() != null) {
            params.add(command.getCount());
        }
        if (command.getConsumerName() != null) {
            params.add(command.getConsumerName());
        }

        Mono<List<PendingEntry>> m = write(k, StringCodec.INSTANCE, RedisCommands.XPENDING_ENTRIES, params.toArray());
        return m.map(list -> {
            List<PendingMessage> msgs = list.stream().map(v -> new PendingMessage(RecordId.of(v.getId().toString()),
                    Consumer.from(command.getGroupName(), v.getConsumerName()),
                    Duration.of(v.getIdleTime(), ChronoUnit.MILLIS),
                    v.getLastTimeDelivered())).collect(Collectors.toList());
            PendingMessages s = new PendingMessages(command.getGroupName(), command.getRange(), msgs);
            return new ReactiveRedisConnection.CommandResponse<>(command, s);
        });
    });
}
 
Example #17
Source File: TCKDayOfWeek.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {DayOfWeek.FRIDAY, TemporalQueries.chronology(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.zoneId(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.precision(), ChronoUnit.DAYS},
            {DayOfWeek.FRIDAY, TemporalQueries.zone(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.offset(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.localDate(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.localTime(), null},
    };
}
 
Example #18
Source File: RangeDatesIterationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
    LocalDate start = LocalDate.now();
    LocalDate end = start.plus(10L, ChronoUnit.DAYS);

    RangeDatesIteration iteration = new RangeDatesIteration();

    iteration.iterateBetweenDatesJava8(start, end);
}
 
Example #19
Source File: ChronoLocalDateTimeImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    Objects.requireNonNull(endExclusive, "endExclusive");
    @SuppressWarnings("unchecked")
    ChronoLocalDateTime<D> end = (ChronoLocalDateTime<D>) getChronology().localDateTime(endExclusive);
    if (unit instanceof ChronoUnit) {
        if (unit.isTimeBased()) {
            long amount = end.getLong(EPOCH_DAY) - date.getLong(EPOCH_DAY);
            switch ((ChronoUnit) unit) {
                case NANOS: amount = Math.multiplyExact(amount, NANOS_PER_DAY); break;
                case MICROS: amount = Math.multiplyExact(amount, MICROS_PER_DAY); break;
                case MILLIS: amount = Math.multiplyExact(amount, MILLIS_PER_DAY); break;
                case SECONDS: amount = Math.multiplyExact(amount, SECONDS_PER_DAY); break;
                case MINUTES: amount = Math.multiplyExact(amount, MINUTES_PER_DAY); break;
                case HOURS: amount = Math.multiplyExact(amount, HOURS_PER_DAY); break;
                case HALF_DAYS: amount = Math.multiplyExact(amount, 2); break;
            }
            return Math.addExact(amount, time.until(end.toLocalTime(), unit));
        }
        ChronoLocalDate endDate = end.toLocalDate();
        if (end.toLocalTime().isBefore(time)) {
            endDate = endDate.minus(1, ChronoUnit.DAYS);
        }
        return date.until(endDate, unit);
    }
    Objects.requireNonNull(unit, "unit");
    return unit.between(this, end);
}
 
Example #20
Source File: InMemoryEventIndexTest.java    From concursus with MIT License 5 votes vote down vote up
@Test public void
newerValuesOverwriteOlderValues() {
    StreamTimestamp now = StreamTimestamp.now();
    StreamTimestamp earlier = now.minus(1, ChronoUnit.MILLIS);
    StreamTimestamp later = now.plus(1, ChronoUnit.MILLIS);

    index.accept(Event.of(
            id1,
            now,
            CREATED,
            eventSchema.make(
                    name.of("Arthur Putey"),
                    age.of(42),
                    favouriteColour.of("orange"))));

    index.accept(Event.of(
            id1,
            earlier,
            CREATED,
            eventSchema.make(
                    name.of("Arthur Daley"),
                    age.of(42),
                    favouriteColour.of("orange"))));

    assertThat(index.findAggregates("name", "Arthur Daley"), hasSize(0));
    assertThat(index.findAggregates("name", "Arthur Putey"), contains(id1));

    index.accept(Event.of(
            id1,
            later,
            CREATED,
            eventSchema.make(
                    name.of("Arthur Mumby"),
                    age.of(42),
                    favouriteColour.of("orange"))));

    assertThat(index.findAggregates("name", "Arthur Putey"), hasSize(0));
    assertThat(index.findAggregates("name", "Arthur Mumby"), contains(id1));
}
 
Example #21
Source File: TCKYearMonth.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {TEST_2008_06, TemporalQueries.chronology(), IsoChronology.INSTANCE},
            {TEST_2008_06, TemporalQueries.zoneId(), null},
            {TEST_2008_06, TemporalQueries.precision(), ChronoUnit.MONTHS},
            {TEST_2008_06, TemporalQueries.zone(), null},
            {TEST_2008_06, TemporalQueries.offset(), null},
            {TEST_2008_06, TemporalQueries.localDate(), null},
            {TEST_2008_06, TemporalQueries.localTime(), null},
    };
}
 
Example #22
Source File: TCKDayOfWeek.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {DayOfWeek.FRIDAY, TemporalQueries.chronology(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.zoneId(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.precision(), ChronoUnit.DAYS},
            {DayOfWeek.FRIDAY, TemporalQueries.zone(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.offset(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.localDate(), null},
            {DayOfWeek.FRIDAY, TemporalQueries.localTime(), null},
    };
}
 
Example #23
Source File: DefaultProducerFactoryTest.java    From extension-kafka with Apache License 2.0 5 votes vote down vote up
@Test
void testConfiguringInvalidTimeout() {
    assertThrows(
            AxonConfigurationException.class,
            () -> builder().configuration(minimal(kafkaBroker)).closeTimeout(-1, ChronoUnit.SECONDS).build()
    );
}
 
Example #24
Source File: HttpEntityMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void shouldNotFailPreconditionForPutRequests() throws Exception {
	servletRequest.setMethod("PUT");
	ZonedDateTime dateTime = ofEpochMilli(new Date().getTime()).atZone(GMT);
	servletRequest.addHeader(HttpHeaders.IF_UNMODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));

	long justModified = dateTime.plus(1, ChronoUnit.SECONDS).toEpochSecond() * 1000;
	ResponseEntity<String> returnValue = ResponseEntity.ok()
			.lastModified(justModified).body("body");
	initStringMessageConversion(TEXT_PLAIN);
	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);

	assertConditionalResponse(HttpStatus.OK, null, null, justModified);
}
 
Example #25
Source File: CallExecutorTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void verifySpecificSuperclassExceptionThrowsUnexpectedException() throws Exception {
    Callable<Boolean> callable = () -> {
        throw new Exception();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnSpecificExceptions(IOException.class)
            .withMaxNumberOfTries(1)
            .withDelayBetweenTries(0, ChronoUnit.SECONDS)
            .withFixedBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #26
Source File: CertUtil.java    From nitmproxy with MIT License 5 votes vote down vote up
public static Certificate newCert(String parentCertFile, String keyFile, String host) {
    try {
        Date before = Date.from(Instant.now());
        Date after = Date.from(Year.now().plus(3, ChronoUnit.YEARS).atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());

        X509CertificateHolder parent = readPemFromFile(parentCertFile);
        PEMKeyPair pemKeyPair = readPemFromFile(keyFile);
        KeyPair keyPair = new JcaPEMKeyConverter()
                .setProvider(PROVIDER)
                .getKeyPair(pemKeyPair);

        X509v3CertificateBuilder x509 = new JcaX509v3CertificateBuilder(
                parent.getSubject(),
                new BigInteger(64, new SecureRandom()),
                before,
                after,
                new X500Name("CN=" + host),
                keyPair.getPublic());

        ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());

        JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter()
                .setProvider(PROVIDER);

        return new Certificate(
                keyPair,
                x509CertificateConverter.getCertificate(x509.build(signer)),
                x509CertificateConverter.getCertificate(parent));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #27
Source File: TCKJapaneseChronology.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_periodUntilUnit() {
    JapaneseDate mdate1 = JapaneseDate.of(1970, 1, 1);
    JapaneseDate mdate2 = JapaneseDate.of(1971, 2, 2);
    long months = mdate1.until(mdate2, ChronoUnit.MONTHS);
    assertEquals(months, 13);
}
 
Example #28
Source File: AnomalyDetectorTests.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void testEmptyFeatures() throws IOException {
    AnomalyDetector detector = TestHelpers
        .randomAnomalyDetector(ImmutableList.of(), null, Instant.now().truncatedTo(ChronoUnit.SECONDS));
    String detectorString = TestHelpers.xContentBuilderToString(detector.toXContent(TestHelpers.builder(), ToXContent.EMPTY_PARAMS));
    AnomalyDetector parsedDetector = AnomalyDetector.parse(TestHelpers.parser(detectorString));
    assertEquals(0, parsedDetector.getFeatureAttributes().size());
}
 
Example #29
Source File: TCKOffsetTime.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {TEST_11_30_59_500_PONE, TemporalQueries.chronology(), null},
            {TEST_11_30_59_500_PONE, TemporalQueries.zoneId(), null},
            {TEST_11_30_59_500_PONE, TemporalQueries.precision(), ChronoUnit.NANOS},
            {TEST_11_30_59_500_PONE, TemporalQueries.zone(), OFFSET_PONE},
            {TEST_11_30_59_500_PONE, TemporalQueries.offset(), OFFSET_PONE},
            {TEST_11_30_59_500_PONE, TemporalQueries.localDate(), null},
            {TEST_11_30_59_500_PONE, TemporalQueries.localTime(), LocalTime.of(11, 30, 59, 500)},
    };
}
 
Example #30
Source File: UserServiceImpl.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Transactional(rollbackFor = CommonException.class)
@CacheEvict(value = GlobalsConstants.REDIS_USER_CACHE, key = "T(com.scaffolding.sophia.common.base.constants.GlobalsConstants).USER_KEY_PREFIX.concat(T(String).valueOf(#userDto.id))")
@Override
public boolean updateUser(UserDto userDto) {
    if (StringUtils.isBlank(userDto.getUserId())) {
        userDto.setUserId(UserUtils.getLoginUser().getId());
    }
    User user = new User();
    user.buildBo(userDto);
    User ckUser = baseMapper.selectById(user.getId());
    if (StringUtils.isNotBlank(userDto.getPassword())) {
        // 判断密码是否被修改
        if (!user.getPassword().equals(ckUser.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
    }
    if (null != user.getBirthday()) {
        user.setAge((int) user.getBirthday().until(LocalDateTime.now(), ChronoUnit.YEARS));
    }
    //TODO 是否修改头像
    user.setUpdateTime(LocalDateTime.now());
    user.setUpdateUser(UserUtils.getLoginUser().getId());
    if (StringUtils.isNotBlank(userDto.getRoleId())) {
        userDto.setId(user.getId());
        this.updateRole(userDto);
    }
    return baseMapper.updateById(user) > 0;
}