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.
Example 1
Project: tutorials   File: AccountResourceIntTest.java    License: 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
@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
Project: packagedrone   File: OsgiSitemapGenerator.java    License: 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 4
Project: j2objc   File: TestDateTimeParsing.java    License: 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 5
Project: ProjectAres   File: ObjectivePublishingMatchModule.java    License: 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 6
Project: outbackcdx   File: JwtAuthorizerTest.java    License: 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
Project: cxf   File: SPStateManagerTest.java    License: 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 8
Project: brooklin   File: DatastreamRestClient.java    License: 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 9
Project: prebid-server-java   File: VideoHandlerTest.java    License: 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 10
Project: alchemy   File: UserServiceIT.java    License: 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 11
Project: Medusa   File: ClockSkinBase.java    License: 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 12
Project: swblocks-decisiontree   File: ValueGroupTest.java    License: 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 13
Project: sailfish-core   File: SFAPIClient.java    License: Apache License 2.0 5 votes vote down vote up
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
Project: timbuctoo   File: TinkerPopOperationsTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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
Project: mycore   File: MCRZonedDateTimeConverter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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
Project: styx   File: CliMainTest.java    License: 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 17
Project: dragonwell8_jdk   File: TCKInstant.java    License: 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 18
Project: plugins   File: IdleNotifierPlugin.java    License: 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 19
Project: j2objc   File: TCKInstantPrinterParser.java    License: 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 20
Project: allure-java   File: AllureCucumber3JvmTest.java    License: 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);
}
 
Example 21
Project: hottub   File: ZoneRules.java    License: 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
Project: spring-boot-admin   File: ApplicationRegistry.java    License: 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 23
Project: lucene-solr   File: DateMathFunctionTest.java    License: 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 24
Project: hedera-mirror-node   File: UtilityTest.java    License: 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
Project: j2objc   File: TCKZoneId.java    License: 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 26
Project: vespa   File: Node.java    License: 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
Project: jdk8u-jdk   File: TCKZoneRules.java    License: 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 28
Project: aws-sdk-java-v2   File: IonRoundtripTest.java    License: 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 29
Project: bluetooth-manager   File: DeviceGovernorImplTest.java    License: 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 30
Project: Openfire   File: SystemPropertyTest.java    License: 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 31
Project: WeBASE-Node-Manager   File: FrontController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * qurey front info list.
 */
@GetMapping(value = "/find")
public BasePageResponse queryFrontList(
    @RequestParam(value = "frontId", required = false) Integer frontId,
    @RequestParam(value = "groupId", required = false) Integer groupId)
    throws NodeMgrException {
    BasePageResponse pagesponse = new BasePageResponse(ConstantCode.SUCCESS);
    Instant startTime = Instant.now();
    log.info("start queryFrontList startTime:{} frontId:{} groupId:{}",
        startTime.toEpochMilli(), frontId, groupId);

    //param
    FrontParam param = new FrontParam();
    param.setFrontId(frontId);
    param.setGroupId(groupId);

    //query front info
    int count = frontService.getFrontCount(param);
    pagesponse.setTotalCount(count);
    if (count > 0) {
        List<TbFront> list = frontService.getFrontList(param);
        pagesponse.setData(list);
    }

    log.info("end queryFrontList useTime:{} result:{}",
        Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(pagesponse));
    return pagesponse;
}
 
Example 32
Project: syncope   File: BinaryPDFPreviewer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] getImageData(final IResource.Attributes attributes) {
    if (thumbnail == null) {
        thumbnail = toImageData(getScaledImageInstance());
        setLastModifiedTime(Instant.now());
    }
    return thumbnail;
}
 
Example 33
Project: emodb   File: DefaultFanoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFanoutToNewTableWithDelayedCacheInvalidation() {
    when(_subscriptionsSupplier.get()).thenReturn(ImmutableList.of());
    EventData event = newEvent("id0", "new-table", "key0");

    // Need to set the current time to match the time of the event
    _now = Instant.ofEpochMilli(TimeUUIDs.getTimeMillis(UpdateRefSerializer.fromByteBuffer(event.getData().duplicate()).getChangeId()));

    // For the first 2 seconds the new table doesn't show up in cache
    final Table table = mockTable("new-table");
    final Instant nowPlus2Seconds = _now.plusSeconds(2);
    when(_dataProvider.getTable("new-table")).thenAnswer(ignore -> {
        if (_now.isBefore(nowPlus2Seconds)) {
            throw new UnknownTableException();
        }
        return table;
    });

    for (int i=0; i < 2; i++) {
        _defaultFanout.copyEvents(ImmutableList.of(event));
        assertTrue(_eventsSinked.isEmpty());
        assertTrue(_deletedKeys.isEmpty());
        _now = _now.plusSeconds(1);
    }

    // After 2 seconds the event should be fanned out and deleted
    _defaultFanout.copyEvents(ImmutableList.of(event));
    assertEquals(_eventsSinked, ImmutableMultimap.of(_remoteChannel, event.getData()));
    assertEquals(_deletedKeys, ImmutableList.of("id0"));
}
 
Example 34
Project: hedera-sdk-java   File: TransactionIdTest.java    License: 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 35
Project: spring-session   File: JdbcIndexedSessionRepositoryTests.java    License: 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 36
Project: Spring-5.0-Projects   File: UserService.java    License: 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 37
Project: jdk8u_jdk   File: TCKZonedDateTime.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factory_ofInstant_Instant_invalidOffset() {
    Instant instant = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500).toInstant(OFFSET_0130);
    ZonedDateTime test = ZonedDateTime.ofInstant(instant, ZONE_PARIS);
    check(test, 2008, 6, 30, 12, 0, 10, 500, OFFSET_0200, ZONE_PARIS);  // corrected offset, thus altered time
}
 
Example 38
Project: protools   File: ToolDatePlus.java    License: Apache License 2.0 4 votes vote down vote up
public static LocalDateTime date2LocalDateTime(final Date date) {
    Instant instant = date.toInstant();
    ZonedDateTime zdt = instant.atZone(DEFAULT_ZONE_ID);
    return zdt.toLocalDateTime();
}
 
Example 39
Project: molgenis   File: UserSecret.java    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
public Instant getLastFailedAuthentication() {
  return getInstant(UserSecretMetadata.LAST_FAILED_AUTHENICATION);
}
 
Example 40
Project: concursus   File: GroupController.java    License: MIT License 4 votes vote down vote up
@RequestMapping(path = "{groupId}", method = RequestMethod.DELETE)
public void deleteGroup(@PathVariable("groupId") String groupId) {
    groupCommands.delete(
            StreamTimestamp.of("admin", Instant.now()),
            groupId);
}