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 Project: failsafe Author: jhalterman File: ExecutionTest.java License: Apache License 2.0 | 7 votes |
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 Project: triplea Author: triplea-game File: ChattersTest.java License: GNU General Public License v3.0 | 6 votes |
@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 #3
Source Project: incubator-iotdb Author: apache File: RegularDataEncoderLongTest.java License: Apache License 2.0 | 6 votes |
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 #4
Source Project: hottub Author: dsrg-uoft File: TestChronologyPerf.java License: GNU General Public License v2.0 | 6 votes |
@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 #5
Source Project: TencentKona-8 Author: Tencent File: TCKWeekFields.java License: GNU General Public License v2.0 | 6 votes |
@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 #6
Source Project: JDKSourceCode1.8 Author: wupeixuan File: ChronoLocalDateImpl.java License: MIT License | 6 votes |
@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 #7
Source Project: influxdb-client-java Author: influxdata File: FilterFluxTest.java License: MIT License | 6 votes |
@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 #8
Source Project: TencentKona-8 Author: Tencent File: TCKLocalDate.java License: GNU General Public License v2.0 | 6 votes |
@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 #9
Source Project: flowable-engine Author: flowable File: DurationTimeTimerEventTest.java License: Apache License 2.0 | 6 votes |
@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 #10
Source Project: gorilla-tsc Author: burmanm File: EncodeGorillaTest.java License: Apache License 2.0 | 6 votes |
@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 #11
Source Project: bisq Author: bisq-network File: TradesChartsViewModel.java License: GNU Affero General Public License v3.0 | 6 votes |
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 #12
Source Project: centraldogma Author: line File: TokenlessClientLogger.java License: Apache License 2.0 | 6 votes |
@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 #13
Source Project: hono Author: eclipse File: PrometheusBasedResourceLimitChecks.java License: Eclipse Public License 2.0 | 6 votes |
/** * 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 #14
Source Project: openjdk-jdk8u-backup Author: AdoptOpenJDK File: TCKYearMonth.java License: GNU General Public License v2.0 | 5 votes |
@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 #15
Source Project: nitmproxy Author: chhsiao90 File: CertUtil.java License: MIT License | 5 votes |
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 #16
Source Project: concursus Author: opencredo File: InMemoryEventIndexTest.java License: MIT License | 5 votes |
@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 #17
Source Project: spring-analysis-note Author: Vip-Augus File: ResponseEntityResultHandlerTests.java License: MIT License | 5 votes |
@Test public void handleReturnValueLastModified() throws Exception { Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS); Instant oneMinAgo = currentTime.minusSeconds(60); long timestamp = currentTime.toEpochMilli(); MockServerWebExchange exchange = MockServerWebExchange.from(get("/path").ifModifiedSince(timestamp)); ResponseEntity<String> entity = ok().lastModified(oneMinAgo.toEpochMilli()).body("body"); MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class)); HandlerResult result = handlerResult(entity, returnType); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, null, oneMinAgo); }
Example #18
Source Project: jdk8u60 Author: chenghanpeng File: TCKDuration.java License: GNU General Public License v2.0 | 5 votes |
@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 #19
Source Project: tutorials Author: eugenp File: RangeDatesIterationUnitTest.java License: MIT License | 5 votes |
@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 #20
Source Project: sophia_scaffolding Author: SophiaLeo File: UserServiceImpl.java License: Apache License 2.0 | 5 votes |
@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; }
Example #21
Source Project: extension-kafka Author: AxonFramework File: DefaultProducerFactoryTest.java License: Apache License 2.0 | 5 votes |
@Test void testConfiguringInvalidTimeout() { assertThrows( AxonConfigurationException.class, () -> builder().configuration(minimal(kafkaBroker)).closeTimeout(-1, ChronoUnit.SECONDS).build() ); }
Example #22
Source Project: java-technology-stack Author: codeEngraver File: HttpEntityMethodProcessorMockTests.java License: MIT License | 5 votes |
@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 #23
Source Project: retry4j Author: elennick File: CallExecutorTest.java License: MIT License | 5 votes |
@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 #24
Source Project: jdk8u_jdk Author: JetBrains File: TCKJapaneseChronology.java License: GNU General Public License v2.0 | 5 votes |
@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 #25
Source Project: anomaly-detection Author: opendistro-for-elasticsearch File: AnomalyDetectorTests.java License: Apache License 2.0 | 5 votes |
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 #26
Source Project: jdk8u-jdk Author: frohoff File: TCKOffsetTime.java License: GNU General Public License v2.0 | 5 votes |
@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 #27
Source Project: openjdk-jdk8u-backup Author: AdoptOpenJDK File: ChronoLocalDateTimeImpl.java License: GNU General Public License v2.0 | 5 votes |
@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 #28
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: TCKPeriod.java License: GNU General Public License v2.0 | 5 votes |
@DataProvider(name="GoodTemporalUnit") Object[][] data_goodTemporalUnit() { return new Object[][] { {2, ChronoUnit.DAYS}, {2, ChronoUnit.MONTHS}, {2, ChronoUnit.YEARS}, }; }
Example #29
Source Project: redisson Author: redisson File: RedissonReactiveStreamCommands.java License: Apache License 2.0 | 5 votes |
@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 #30
Source Project: jdk8u-jdk Author: lambdalab-mirror File: TCKDayOfWeek.java License: GNU General Public License v2.0 | 5 votes |
@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}, }; }