Java Code Examples for java.time.Instant
The following examples show how to use
java.time.Instant.
These examples are extracted from open source projects.
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: tutorials Author: eugenp File: AccountResourceIntTest.java License: MIT License | 6 votes |
@Test @Transactional public void testFinishPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset"); user.setEmail("[email protected]"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); }
Example #2
Source Project: sakai Author: sakaiproject File: BaseExternalCalendarSubscriptionTest.java License: Educational Community License v2.0 | 6 votes |
@Test public void testGetCalendarSubscriptionMissing() throws Exception { // Doesn't actually get parsed as we mock out the parser String url = getClass().getResource("/simple.ics").toExternalForm(); String packedUrl = BaseExternalSubscriptionDetails.getIdFromSubscriptionUrl(url+"missing"); String referenceString = BaseExternalSubscriptionDetails.calendarSubscriptionReference("siteId", packedUrl); { Reference ref = mock(Reference.class); when(ref.getContext()).thenReturn("siteId"); when(ref.getId()).thenReturn(packedUrl); when(entityManager.newReference(referenceString)).thenReturn(ref); } Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault()); service.setClock(clock); assertNull(service.getCalendarSubscription(referenceString)); assertNull(service.getCalendarSubscription(referenceString)); // Should only cache a bad response for a short time. service.setClock(Clock.offset(clock, Duration.ofMinutes(2))); assertNull(service.getCalendarSubscription(referenceString)); }
Example #3
Source Project: packagedrone Author: eclipse File: OsgiSitemapGenerator.java License: Eclipse Public License 1.0 | 6 votes |
/** * Find the last modification timestamp of all channels * * @return the latest modification timestamp of all channels */ private Optional<Instant> calcLastMod () { Instant globalLastMod = null; for ( final ChannelInformation ci : this.channelService.list () ) { final Optional<Instant> lastMod = ofNullable ( ci.getState ().getModificationTimestamp () ); if ( globalLastMod == null || lastMod.get ().isAfter ( globalLastMod ) ) { globalLastMod = lastMod.get (); } } return Optional.ofNullable ( globalLastMod ); }
Example #4
Source Project: j2objc Author: google File: TestDateTimeParsing.java License: Apache License 2.0 | 6 votes |
@DataProvider public static Object[][] data_instantZones() { return new Object[][] { {LOCALFIELDS_ZONEID, "2014-06-30 01:02:03 Europe/Paris", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, PARIS)}, {LOCALFIELDS_ZONEID, "2014-06-30 01:02:03 +02:30", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, OFFSET_0230)}, {LOCALFIELDS_OFFSETID, "2014-06-30 01:02:03 +02:30", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, OFFSET_0230)}, {LOCALFIELDS_WITH_PARIS, "2014-06-30 01:02:03", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, PARIS)}, {LOCALFIELDS_WITH_0230, "2014-06-30 01:02:03", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, OFFSET_0230)}, {INSTANT_WITH_PARIS, "2014-06-30T01:02:03Z", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, ZoneOffset.UTC).withZoneSameInstant(PARIS)}, {INSTANT_WITH_0230, "2014-06-30T01:02:03Z", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, ZoneOffset.UTC).withZoneSameInstant(OFFSET_0230)}, {INSTANT_OFFSETID, "2014-06-30T01:02:03Z +02:30", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, ZoneOffset.UTC).withZoneSameInstant(OFFSET_0230)}, {INSTANT_OFFSETSECONDS, "2014-06-30T01:02:03Z 9000", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, ZoneOffset.UTC).withZoneSameInstant(OFFSET_0230)}, {INSTANTSECONDS_WITH_PARIS, "86402", Instant.ofEpochSecond(86402).atZone(PARIS)}, {INSTANTSECONDS_NOS_WITH_PARIS, "86402.123456789", Instant.ofEpochSecond(86402, 123456789).atZone(PARIS)}, {INSTANTSECONDS_OFFSETSECONDS, "86402 9000", Instant.ofEpochSecond(86402).atZone(OFFSET_0230)}, }; }
Example #5
Source Project: ProjectAres Author: OvercastNetwork File: ObjectivePublishingMatchModule.java License: GNU Affero General Public License v3.0 | 6 votes |
@EventHandler(ignoreCancelled = true) public void onFlagCapture(FlagCaptureEvent event) { final Flag flag = event.getGoal(); final Competitor competitor = event.getCarrier().getCompetitor(); final Location location = event.getGoal().getLocation().orElse(null); if(!isActive(flag, competitor, null)) return; objectiveService.update(new Objective.FlagCapture() { final String id = idFactory.newId(); public String net_id() { return event.getNet().id().orElse(null); } public String color() { return flag.getDyeColor().name(); } public String name() { return flag.getName(); } public String feature_id() { return flag.getDocument()._id(); } public Instant date() { return match.getInstantNow(); } public String match_id() { return match.getId(); } public String server_id() { return server._id(); } public String family() { return server.family(); } public Double x() { return location != null ? location.getX() : null; } public Double y() { return location != null ? location.getY() : null; } public Double z() { return location != null ? location.getZ() : null; } public String team() { return competitor != null ? competitor.getName() : null; } public String player() { return event.getCarrier().getPlayerId().player_id(); } public String _id() { return id; } }); }
Example #6
Source Project: outbackcdx Author: nla File: JwtAuthorizerTest.java License: Apache License 2.0 | 6 votes |
@Test public void test() throws Exception { RSAKey rsaJWK = new RSAKeyGenerator(2048).generate(); RSAKey rsaPublicJWK = rsaJWK.toPublicJWK(); JWSSigner signer = new RSASSASigner(rsaJWK); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .claim("permissions", Arrays.asList(RULES_EDIT.toString(), INDEX_EDIT.toString())) .build(); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(), claimsSet); signedJWT.sign(signer); String token = signedJWT.serialize(); JwtAuthorizer authorizer = new JwtAuthorizer(new ImmutableJWKSet<>(new JWKSet(rsaPublicJWK)), "permissions"); Set<Permission> permissions = authorizer.verify("beARer " + token).permissions; assertEquals(EnumSet.of(RULES_EDIT, INDEX_EDIT), permissions); }
Example #7
Source Project: cxf Author: apache File: SPStateManagerTest.java License: Apache License 2.0 | 6 votes |
@Test public void testResponseState() throws Exception { ResponseState responseState = new ResponseState("some-assertion", null, "/", null, Instant.now().toEpochMilli(), SSOConstants.DEFAULT_STATE_TIME); stateManager.setResponseState("some-context-key", responseState); ResponseState retrievedState = stateManager.getResponseState("some-context-key"); assertEquals(retrievedState, responseState); retrievedState = stateManager.removeResponseState("some-context-key"); assertEquals(retrievedState, responseState); // Check we can't remove again retrievedState = stateManager.removeResponseState("some-context-state"); assertNull(retrievedState); retrievedState = stateManager.removeResponseState("some-other-context-state"); assertNull(retrievedState); }
Example #8
Source Project: brooklin Author: linkedin File: DatastreamRestClient.java License: BSD 2-Clause "Simplified" License | 6 votes |
private List<Datastream> getAllDatastreams(GetAllRequest<Datastream> request) { Instant startTime = Instant.now(); List<Datastream> datastreams = PollUtils.poll(() -> { ResponseFuture<CollectionResponse<Datastream>> datastreamResponseFuture = _restClient.sendRequest(request); try { return datastreamResponseFuture.getResponse().getEntity().getElements(); } catch (RemoteInvocationException e) { if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) { LOG.warn("Timeout: getAllDatastreams. May retry...", e); return null; } String errorMessage = "Get All Datastreams failed with error."; ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); return null; // not reachable } }, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new); LOG.info("getAllDatastreams took {} ms", Duration.between(startTime, Instant.now()).toMillis()); return datastreams; }
Example #9
Source Project: prebid-server-java Author: rubicon-project File: VideoHandlerTest.java License: Apache License 2.0 | 6 votes |
@Test public void shouldComputeTimeoutBasedOnRequestProcessingStartTime() { // given given(videoRequestFactory.fromRequest(any(), anyLong())) .willReturn(Future.succeededFuture(givenAuctionContext(identity(), emptyList()))); given(exchangeService.holdAuction(any())) .willReturn(Future.succeededFuture(BidResponse.builder().build())); final Instant now = Instant.now(); given(clock.millis()).willReturn(now.toEpochMilli()).willReturn(now.plusMillis(50L).toEpochMilli()); // when videoHandler.handle(routingContext); // then assertThat(captureAuctionContext().getTimeout().remaining()).isLessThanOrEqualTo(1950L); }
Example #10
Source Project: alchemy Author: binglind File: UserServiceIT.java License: Apache License 2.0 | 5 votes |
@Test @Transactional public void testRemoveNotActivatedUsers() { // custom "now" for audit to use as creation date when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS))); user.setActivated(false); userRepository.saveAndFlush(user); assertThat(userRepository.findOneByLogin(DEFAULT_LOGIN)).isPresent(); userService.removeNotActivatedUsers(); assertThat(userRepository.findOneByLogin(DEFAULT_LOGIN)).isNotPresent(); }
Example #11
Source Project: Medusa Author: HanSolo File: ClockSkinBase.java License: Apache License 2.0 | 5 votes |
public ClockSkinBase(final Clock CLOCK) { super(CLOCK); clock = CLOCK; sizeListener = o -> handleEvents("RESIZE"); updateEventListener = e -> handleEvents(e.eventType.name()); currentTimeListener = o -> updateTime(ZonedDateTime.ofInstant(Instant.ofEpochSecond(clock.getCurrentTime()), ZoneId.of(ZoneId.systemDefault().getId()))); timeListener = o -> updateTime(clock.getTime()); alarmListener = c -> { updateAlarms(); redraw(); }; }
Example #12
Source Project: swblocks-decisiontree Author: jpmorganchase File: ValueGroupTest.java License: Apache License 2.0 | 5 votes |
@Test public void toStringCorrect() { final UUID uuid = new UUID(0, 1); final DateRange range = new DateRange(NOW, Instant.MAX); final ValueGroup group = new ValueGroup(uuid, "test-group", Arrays.asList("input1", "input2"), range); Assert.assertEquals(GroupDriver.VG_PREFIX + new UUID(0, 1), group.toString()); }
Example #13
Source Project: sailfish-core Author: exactpro File: SFAPIClient.java License: Apache License 2.0 | 5 votes |
public XmlResponse cleanResources(Instant olderthan) throws APICallException, APIResponseException { String url = rootUrl + RESOURCES_CLEAN_OLDERTHAN.replace("!olderthan", olderthan.toString()); XmlResponse xmlResponse; try { HttpDelete req = new HttpDelete(url); CloseableHttpResponse res = http.execute(req); checkHttpResponse(res); xmlResponse = unmarshal(XmlResponse.class, res); res.close(); return xmlResponse; } catch (Exception e) { throw new APICallException(e); } }
Example #14
Source Project: timbuctoo Author: HuygensING File: TinkerPopOperationsTest.java License: GNU General Public License v3.0 | 5 votes |
@Test public void replaceEntityRemovesThePropertiesThatAreNotProvided() throws Exception { Vres vres = createConfiguration(); Collection collection = vres.getCollection("testthings").get(); UUID id = UUID.randomUUID(); TinkerPopGraphManager graphManager = newGraph() .withVertex(v -> v .withTimId(id) .withVre("test") .withType("thing") .withProperty("testthing_prop1", "oldValue1") .withProperty("testthing_prop2", "oldValue2") .withProperty("isLatest", true) .withProperty("rev", 1) ).wrap(); TinkerPopOperations instance = forGraphWrapperAndMappings(graphManager, vres); ArrayList<TimProperty<?>> properties = Lists.newArrayList( new StringProperty("prop1", "newValue") ); UpdateEntity updateEntity = new UpdateEntity(id, properties, 1); long timeStamp = Instant.now().toEpochMilli(); updateEntity.setModified(new Change(timeStamp, "userId", null)); instance.replaceEntity(collection, updateEntity); Vertex vertex = graphManager.getGraph().traversal().V().has("tim_id", id.toString()).has("isLatest", true).next(); assertThat(vertex, is(likeVertex().withoutProperty("testthing_prop2"))); }
Example #15
Source Project: mycore Author: MyCoRe-Org File: MCRZonedDateTimeConverter.java License: GNU General Public License v3.0 | 5 votes |
@Override public ZonedDateTime convertToEntityAttribute(Date dbData) { if (dbData == null) { return null; } Instant instant = dbData.toInstant(); try { return ZonedDateTime.from(instant); } catch (DateTimeException exc) { LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("UTC")); return ZonedDateTime.of(localDateTime, ZoneId.of("UTC")); } }
Example #16
Source Project: styx Author: spotify File: CliMainTest.java License: Apache License 2.0 | 5 votes |
@Test public void testBackfillList() { final String component = "quux"; final String workflow = "foo"; final String start = "2017-01-01T00:00:00Z"; final String end = "2017-01-30T00:00:00Z"; final Backfill backfill = Backfill.newBuilder() .id("backfill-2") .start(Instant.parse(start)) .end(Instant.parse(end)) .workflowId(WorkflowId.create(component, workflow)) .concurrency(1) .description("Description") .nextTrigger(Instant.parse("2017-01-01T00:00:00Z")) .schedule(Schedule.DAYS) .created(currentTime) .lastModified(currentTime) .build(); final BackfillsPayload backfillsPayload = BackfillsPayload.create( List.of(BackfillPayload.create(backfill, Optional.empty()))); when(client.backfillList(Optional.of(component), Optional.of(workflow), false, false)) .thenReturn(CompletableFuture.completedFuture(backfillsPayload)); CliMain.run(cliContext, "backfill", "list", "-c", component, "-w", workflow, "--no-trunc"); verify(client).backfillList(Optional.of(component), Optional.of(workflow), false, false); verify(cliOutput).printBackfills(backfillsPayload.backfills(), true); }
Example #17
Source Project: dragonwell8_jdk Author: alibaba File: TCKInstant.java License: GNU General Public License v2.0 | 5 votes |
@Test public void plusMillis_long_min() { Instant t = Instant.ofEpochSecond(MIN_SECOND, 1000000); t = t.plusMillis(-1); assertEquals(t.getEpochSecond(), MIN_SECOND); assertEquals(t.getNano(), 0); }
Example #18
Source Project: plugins Author: open-osrs File: IdleNotifierPlugin.java License: GNU General Public License v3.0 | 5 votes |
@Subscribe void onGameStateChanged(GameStateChanged gameStateChanged) { lastInteracting = null; GameState state = gameStateChanged.getGameState(); switch (state) { case LOGIN_SCREEN: resetTimers(); isFirstTick = true; break; case HOPPING: isFirstTick = true; ready = true; break; case LOGGING_IN: case CONNECTION_LOST: ready = true; break; case LOGGED_IN: if (ready) { sixHourWarningTime = Instant.now().plus(SIX_HOUR_LOGOUT_WARNING_AFTER_DURATION); ready = false; resetTimers(); } resourceDoorReady = true; break; } }
Example #19
Source Project: j2objc Author: google File: TCKInstantPrinterParser.java License: Apache License 2.0 | 5 votes |
@Test @UseDataProvider("data_printDigits") public void test_print_digits(int fractionalDigits, long instantSecs, int nano, String expected) { Instant instant = Instant.ofEpochSecond(instantSecs, nano); DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(fractionalDigits).toFormatter(); assertEquals(f.format(instant), expected); }
Example #20
Source Project: allure-java Author: allure-framework File: AllureCucumber3JvmTest.java License: Apache License 2.0 | 5 votes |
@AllureFeatures.Timings @Test void shouldSetStop() { final long before = Instant.now().toEpochMilli(); final AllureResults results = runFeature("features/simple.feature"); final long after = Instant.now().toEpochMilli(); assertThat(results.getTestResults()) .extracting(TestResult::getStop) .allMatch(v -> v >= before && v <= after); }
Example #21
Source Project: hottub Author: dsrg-uoft File: ZoneRules.java License: GNU General Public License v2.0 | 5 votes |
/** * Gets the offset applicable at the specified instant in these rules. * <p> * The mapping from an instant to an offset is simple, there is only * one valid offset for each instant. * This method returns that offset. * * @param instant the instant to find the offset for, not null, but null * may be ignored if the rules have a single offset for all instants * @return the offset, not null */ public ZoneOffset getOffset(Instant instant) { if (savingsInstantTransitions.length == 0) { return standardOffsets[0]; } long epochSec = instant.getEpochSecond(); // check if using last rules if (lastRules.length > 0 && epochSec > savingsInstantTransitions[savingsInstantTransitions.length - 1]) { int year = findYear(epochSec, wallOffsets[wallOffsets.length - 1]); ZoneOffsetTransition[] transArray = findTransitionArray(year); ZoneOffsetTransition trans = null; for (int i = 0; i < transArray.length; i++) { trans = transArray[i]; if (epochSec < trans.toEpochSecond()) { return trans.getOffsetBefore(); } } return trans.getOffsetAfter(); } // using historic rules int index = Arrays.binarySearch(savingsInstantTransitions, epochSec); if (index < 0) { // switch negative insert position to start of matched range index = -index - 2; } return wallOffsets[index + 1]; }
Example #22
Source Project: spring-boot-admin Author: codecentric File: ApplicationRegistry.java License: Apache License 2.0 | 5 votes |
protected Mono<Application> toApplication(String name, Flux<Instance> instances) { return instances.collectList().map((instanceList) -> { Tuple2<String, Instant> status = getStatus(instanceList); return Application.create(name).instances(instanceList).buildVersion(getBuildVersion(instanceList)) .status(status.getT1()).statusTimestamp(status.getT2()).build(); }); }
Example #23
Source Project: lucene-solr Author: apache File: DateMathFunctionTest.java License: Apache License 2.0 | 5 votes |
@Test public void singleValueParameterTest() throws DateTimeParseException { Date date1 = Date.from(Instant.parse("1810-12-02T10:30:15Z")); Date date2 = Date.from(Instant.parse("1931-03-16T18:15:45Z")); TestDateValue val = new TestDateValue(); ConstantStringValue math1 = new ConstantStringValue("+1DAY"); ConstantStringValue math2 = new ConstantStringValue("-1MONTH"); ConstantStringValue math3 = new ConstantStringValue("+11YEARS"); AnalyticsValueStream uncasted = DateMathFunction.creatorFunction.apply(new AnalyticsValueStream[] {val, math1, math2, math3}); assertTrue(uncasted instanceof DateValue); DateValue func = (DateValue) uncasted; // Value doesn't exist val.setExists(false); func.getDate(); assertFalse(func.exists()); func.getLong(); assertFalse(func.exists()); // Value exists val.setValue("1800-01-01T10:30:15Z").setExists(true); assertEquals(date1, func.getDate()); assertTrue(func.exists()); assertEquals(date1.getTime(), func.getLong()); assertTrue(func.exists()); val.setValue("1920-04-15T18:15:45Z").setExists(true); assertEquals(date2, func.getDate()); assertTrue(func.exists()); assertEquals(date2.getTime(), func.getLong()); assertTrue(func.exists()); }
Example #24
Source Project: hedera-mirror-node Author: hashgraph File: UtilityTest.java License: Apache License 2.0 | 5 votes |
@ParameterizedTest(name = "with seconds {0} and nanos {1}") @CsvSource({ "1569936354, 901", "0, 901", "1569936354, 0", "0,0" }) public void instantToTimestamp(long seconds, int nanos) { Instant instant = Instant.ofEpochSecond(seconds).plusNanos(nanos); Timestamp test = Utility.instantToTimestamp(instant); assertAll( () -> assertEquals(instant.getEpochSecond(), test.getSeconds()) , () -> assertEquals(instant.getNano(), test.getNanos()) ); }
Example #25
Source Project: j2objc Author: google File: TCKZoneId.java License: Apache License 2.0 | 5 votes |
@Test() @UseDataProvider("data_offsetBasedValidPrefix") public void factory_of_String_offsetBasedValid_prefixGMT(String input, String id, String offsetId) { ZoneId test = ZoneId.of("GMT" + input); assertEquals(test.getId(), "GMT" + id); assertEquals(test.getRules(), ZoneOffset.of(offsetId).getRules()); assertEquals(test.normalized(), ZoneOffset.of(offsetId)); assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), displayName("GMT" + id)); assertEquals(test.getRules().isFixedOffset(), true); assertEquals(test.getRules().getOffset(Instant.EPOCH), ZoneOffset.of(offsetId)); }
Example #26
Source Project: vespa Author: vespa-engine File: Node.java License: Apache License 2.0 | 5 votes |
/** * Returns a copy of this node with wantToRetire and wantToDeprovision set to the given values and updated history. * * If both given wantToRetire and wantToDeprovision are equal to the current values, the method is no-op. */ public Node withWantToRetire(boolean wantToRetire, boolean wantToDeprovision, Agent agent, Instant at) { if (!type.isDockerHost() && wantToDeprovision) throw new IllegalArgumentException("wantToDeprovision can only be set for hosts"); if (wantToRetire == status.wantToRetire() && wantToDeprovision == status.wantToDeprovision()) return this; Node node = this.with(status.withWantToRetire(wantToRetire, wantToDeprovision)); if (wantToRetire) node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at))); return node; }
Example #27
Source Project: jdk8u-jdk Author: lambdalab-mirror File: TCKZoneRules.java License: GNU General Public License v2.0 | 5 votes |
public void test_Paris_preTimeZones() { ZoneRules test = europeParis(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); }
Example #28
Source Project: aws-sdk-java-v2 Author: aws File: IonRoundtripTest.java License: Apache License 2.0 | 5 votes |
@Override public void generate(SdkIonGenerator generator) { // Is this the only way to write a null value? generator.writeValue((String) null); generator.writeValue((BigInteger) null); generator.writeValue((BigDecimal) null); generator.writeValue((Instant) null); generator.writeValue((ByteBuffer) null); }
Example #29
Source Project: bluetooth-manager Author: sputnikdev File: DeviceGovernorImplTest.java License: Apache License 2.0 | 5 votes |
@Test public void testUpdateOnline() { int onlineTimeout = 20; governor.setBlockedControl(false); governor.setConnectionControl(true); when(device.isBlocked()).thenReturn(false); when(device.isConnected()).thenReturn(true); when(device.connect()).thenReturn(true); governor.setOnlineTimeout(onlineTimeout); governor.update(); verify(genericDeviceListener, times(1)).online(); governor.update(); verify(genericDeviceListener, times(1)).online(); governor.setConnectionControl(false); when(device.disconnect()).thenReturn(true); governor.update(); verify(genericDeviceListener, times(0)).offline(); Whitebox.setInternalState(governor, "lastInteracted", Instant.now().minusSeconds(onlineTimeout)); governor.setBlockedControl(true); when(device.isBlocked()).thenReturn(true); governor.update(); verify(genericDeviceListener, times(1)).offline(); }
Example #30
Source Project: Openfire Author: igniterealtime File: SystemPropertyTest.java License: Apache License 2.0 | 5 votes |
@Test public void willCreateAnInstantPropertyWithADefaultValue() { final String key = "test.instant.property.with.default"; final Instant defaultValue = Instant.now().truncatedTo(ChronoUnit.MILLIS); final SystemProperty<Instant> property = SystemProperty.Builder.ofType(Instant.class) .setKey(key) .setDefaultValue(defaultValue) .setDynamic(true) .build(); assertThat(property.getValue(), is(defaultValue)); }