java.security.cert.CertificateExpiredException#java.time.Instant源码实例Demo

下面列出了java.security.cert.CertificateExpiredException#java.time.Instant 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: tutorials   文件: AccountResourceIntTest.java
@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();
}
 
@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));
}
 
源代码3 项目: packagedrone   文件: OsgiSitemapGenerator.java
/**
 * 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 );
}
 
源代码4 项目: j2objc   文件: TestDateTimeParsing.java
@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)},
    };
}
 
@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; }
    });
}
 
源代码6 项目: outbackcdx   文件: JwtAuthorizerTest.java
@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);
}
 
源代码7 项目: cxf   文件: SPStateManagerTest.java
@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);
}
 
源代码8 项目: brooklin   文件: DatastreamRestClient.java
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;
}
 
源代码9 项目: prebid-server-java   文件: VideoHandlerTest.java
@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);
}
 
源代码10 项目: alchemy   文件: UserServiceIT.java
@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();
}
 
源代码11 项目: Medusa   文件: ClockSkinBase.java
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();
    };
}
 
源代码12 项目: swblocks-decisiontree   文件: ValueGroupTest.java
@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());
}
 
源代码13 项目: sailfish-core   文件: SFAPIClient.java
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);
    }
}
 
源代码14 项目: timbuctoo   文件: TinkerPopOperationsTest.java
@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")));
}
 
源代码15 项目: mycore   文件: MCRZonedDateTimeConverter.java
@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"));
    }
}
 
源代码16 项目: styx   文件: CliMainTest.java
@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);
}
 
源代码17 项目: dragonwell8_jdk   文件: TCKInstant.java
@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);
}
 
源代码18 项目: plugins   文件: IdleNotifierPlugin.java
@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;
	}
}
 
源代码19 项目: j2objc   文件: TCKInstantPrinterParser.java
@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);
}
 
源代码20 项目: allure-java   文件: AllureCucumber3JvmTest.java
@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);
}
 
源代码21 项目: hottub   文件: ZoneRules.java
/**
 * 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];
}
 
源代码22 项目: spring-boot-admin   文件: ApplicationRegistry.java
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();
	});
}
 
源代码23 项目: lucene-solr   文件: DateMathFunctionTest.java
@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());
}
 
源代码24 项目: hedera-mirror-node   文件: UtilityTest.java
@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())
    );
}
 
源代码25 项目: j2objc   文件: TCKZoneId.java
@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));
}
 
源代码26 项目: vespa   文件: Node.java
/**
 * 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;
}
 
源代码27 项目: jdk8u-jdk   文件: TCKZoneRules.java
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);
}
 
源代码28 项目: aws-sdk-java-v2   文件: IonRoundtripTest.java
@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);
}
 
源代码29 项目: bluetooth-manager   文件: DeviceGovernorImplTest.java
@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();
}
 
源代码30 项目: Openfire   文件: SystemPropertyTest.java
@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));
}