java.time.Instant Java Examples

The following examples show how to use java.time.Instant. 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: AccountResourceIntTest.java    From tutorials with MIT License 6 votes vote down vote up
@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 File: TestDateTimeParsing.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: VideoHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: BaseExternalCalendarSubscriptionTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@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 #5
Source File: DatastreamRestClient.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #6
Source File: JwtAuthorizerTest.java    From outbackcdx with Apache License 2.0 6 votes vote down vote up
@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 File: OsgiSitemapGenerator.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #8
Source File: SPStateManagerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: ObjectivePublishingMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #10
Source File: SystemPropertyTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #11
Source File: IonRoundtripTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: CliMainTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: ApplicationRegistry.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: ValueGroupTest.java    From swblocks-decisiontree with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: ClockSkinBase.java    From Medusa with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void flushModeSetLastAccessedTime() {
	this.repository.setFlushMode(FlushMode.IMMEDIATE);
	JdbcSession session = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	session.setLastAccessedTime(Instant.now());
	verify(this.jdbcOperations).update(startsWith("UPDATE SPRING_SESSION SET"), isA(PreparedStatementSetter.class));
	verifyNoMoreInteractions(this.jdbcOperations);
}
 
Example #17
Source File: UserServiceIT.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: DateMathFunctionTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: TransactionIdTest.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("strictly increasing validStart")
void strictlyIncreasingValidStart() {
    final AccountId id = new AccountId(2);
    Instant lastTime = new TransactionId(id).validStart;
    for (int i = 0; i < 200; ++i) {
        final Instant thisTime = new TransactionId(id).validStart;
        assertTrue(thisTime.isAfter(lastTime));
        lastTime = thisTime;
    }
}
 
Example #20
Source File: UserService.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
/**
 * Not activated users should be automatically deleted after 3 days.
 * <p>
 * This is scheduled to get fired everyday, at 01:00 (am).
 */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    userRepository
        .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
        .forEach(user -> {
            log.debug("Deleting not activated user {}", user.getLogin());
            userRepository.delete(user);
            this.clearUserCaches(user);
        });
}
 
Example #21
Source File: ZoneRules.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 File: DeviceGovernorImplTest.java    From bluetooth-manager with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: TCKInstant.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 #24
Source File: UtilityTest.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
@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 File: TCKZoneRules.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #26
Source File: Node.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * 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 File: IdleNotifierPlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
@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 #28
Source File: TCKZoneId.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@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 #29
Source File: TCKInstantPrinterParser.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: AllureCucumber3JvmTest.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@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);
}