Example usage for java.time Instant now

List of usage examples for java.time Instant now

Introduction

In this page you can find the example usage for java.time Instant now.

Prototype

public static Instant now() 

Source Link

Document

Obtains the current instant from the system clock.

Usage

From source file:com.coinblesk.server.service.KeyService.java

@Transactional
public TimeLockedAddress createTimeLockedAddress(@NonNull ECKey clientPublicKey, long lockTime)
        throws UserNotFoundException, InvalidLockTimeException {

    // Lock time must be valid
    if (!BitcoinUtils.isLockTimeByTime(lockTime)
            || BitcoinUtils.isAfterLockTime(Instant.now().getEpochSecond(), lockTime)) {
        throw new InvalidLockTimeException();
    }// ww w  .ja  v  a 2 s .c o m

    // Get client for which a new address should be created
    Keys client = keyRepository.findByClientPublicKey(clientPublicKey.getPubKey());
    if (client == null)
        throw new UserNotFoundException(clientPublicKey.getPublicKeyAsHex());

    // Create address
    final TimeLockedAddress address = new TimeLockedAddress(client.clientPublicKey(), client.serverPublicKey(),
            lockTime);

    // Check if address is already in database, if so nothing to do
    TimeLockedAddressEntity existingAddress = timeLockedAddressRepository
            .findByAddressHash(address.getAddressHash());
    if (existingAddress != null)
        return address;

    // Create the new address entity and save
    TimeLockedAddressEntity addressEntity = new TimeLockedAddressEntity();
    addressEntity.setLockTime(address.getLockTime()).setAddressHash(address.getAddressHash())
            .setRedeemScript(address.createRedeemScript().getProgram())
            .setTimeCreated(Utils.currentTimeSeconds()).setKeys(client);
    timeLockedAddressRepository.save(addressEntity);

    return address;
}

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java

public void send(@NonNull final A msg) {
    eventBus.send(address, msg, addRunRightFastHeaders(new DeliveryOptions()));
    this.messageSent.mark();
    this.messageLastSent = Instant.now();
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testPostSuccess() throws InterruptedException {
    final String start = Instant.now().minusMillis(812).atZone(ZoneId.of("UTC"))
            .format(DateTimeFormatter.ISO_INSTANT);
    final String end = Instant.now().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT);
    final String id = UUID.randomUUID().toString();

    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        // Annotations
        Assert.assertEquals(7, r.getAnnotationsCount());
        assertAnnotation(r.getAnnotationsList(), "foo", "bar");
        assertAnnotation(r.getAnnotationsList(), "_service", "myservice");
        assertAnnotation(r.getAnnotationsList(), "_cluster", "mycluster");
        assertAnnotation(r.getAnnotationsList(), "_start", start);
        assertAnnotation(r.getAnnotationsList(), "_end", end);
        assertAnnotation(r.getAnnotationsList(), "_id", id);

        // Dimensions
        Assert.assertEquals(3, r.getDimensionsCount());
        assertDimension(r.getDimensionsList(), "host", "some.host.com");
        assertDimension(r.getDimensionsList(), "service", "myservice");
        assertDimension(r.getDimensionsList(), "cluster", "mycluster");

        // Samples
        assertSample(r.getTimersList(), "timerLong", 123L, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getTimersList(), "timerInt", 123, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getTimersList(), "timerShort", (short) 123, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getTimersList(), "timerByte", (byte) 123, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getCountersList(), "counter", 8d);
        assertSample(r.getGaugesList(), "gauge", 10d, ClientV2.Unit.Type.Value.BYTE,
                ClientV2.Unit.Scale.Value.UNIT);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final AtomicBoolean assertionResult = new AtomicBoolean(false);
    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH))
            .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 1, 451, true,
                    new CompletionHandler(semaphore)))
            .build();/*from   www. j  a  v  a2  s  .  co m*/

    final Map<String, String> annotations = new LinkedHashMap<>();
    annotations.put("foo", "bar");
    annotations.put("_start", start);
    annotations.put("_end", end);
    annotations.put("_host", "some.host.com");
    annotations.put("_service", "myservice");
    annotations.put("_cluster", "mycluster");
    annotations.put("_id", id);

    final TsdEvent event = new TsdEvent(annotations,
            createQuantityMap("timerLong", TsdQuantity.newInstance(123L, Units.NANOSECOND), "timerInt",
                    TsdQuantity.newInstance(123, Units.NANOSECOND), "timerShort",
                    TsdQuantity.newInstance((short) 123, Units.NANOSECOND), "timerByte",
                    TsdQuantity.newInstance((byte) 123, Units.NANOSECOND)),
            createQuantityMap("counter", TsdQuantity.newInstance(8d, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(10d, Units.BYTE)));

    sink.record(event);
    semaphore.acquire();

    // Ensure expected handler was invoked
    Assert.assertTrue(assertionResult.get());

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that data was sent
    _wireMockRule.verify(1, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}

From source file:cloudfoundry.norouter.f5.Agent.java

public void registerRoute(RouteDetails route) {
    final String poolName = poolNamePrefix + route.getHost();

    final PoolDescription poolDescription = new PoolDescription(Instant.now(), Instant.now());
    final String poolDescriptionJsonish = poolDescription.toJsonish();

    final Pool pool = Pool.create().name(poolName).description(poolDescriptionJsonish)
            // TODO Provide mechanism to make monitor configurable
            .monitor(Monitors.TCP_HALF_OPEN)
            // TODO Make reselect tries configurable
            .reselectTries(3).build();//from www .  jav a  2 s  . c  om

    boolean poolCreated = false;
    try {
        client.createPool(pool);
        LOGGER.info("Created pool {}", poolName);
        poolCreated = true;
    } catch (ConflictException e) {
        // Pool already exists, good
    }

    try {
        final PoolMemberDescription poolMemberDescription = new PoolMemberDescription(route);
        client.addPoolMember(poolName, route.getAddress(), poolMemberDescription.toJsonish());
        LOGGER.info("Added pool member {} to pool {}", route.getAddress(), poolName);

        if (!poolCreated) {
            // If we didn't create the pool but added the pool member, update the modified fields in the
            // pool description
            updatePoolModifiedTimestamp(poolName);
            LOGGER.debug("Updated modified field on pool {}", poolName);
        }
    } catch (ConflictException e) {
        // Pool member already exists
        updatePoolMemberDescription(poolName, route);
    }
}

From source file:org.noorganization.instalist.server.api.EntryResourceTest.java

@Test
public void testGetEntries() throws Exception {
    String url = "/groups/%d/listentries";

    Instant preUpdate = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request().get();
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").get();
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(401, wrongGroupResponse.getStatus());

    Response okResponse1 = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse1.getStatus());
    EntryInfo[] allEntryInfo = okResponse1.readEntity(EntryInfo[].class);
    assertEquals(2, allEntryInfo.length);
    for (EntryInfo current : allEntryInfo) {
        if (mEntry.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals(mEntry.getUpdated(), current.getLastChanged().toInstant());
            assertEquals(mList.getUUID(), UUID.fromString(current.getListUUID()));
            assertEquals(mProduct.getUUID(), UUID.fromString(current.getProductUUID()));
            assertEquals(1f, current.getAmount(), 0.001f);
            assertEquals(2, (int) current.getPriority());
            assertFalse(current.getStruck());
            assertFalse(current.getDeleted());
        } else if (mDeletedEntry.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertNull(current.getListUUID());
            assertNull(current.getProductUUID());
            assertNull(current.getAmount());
            assertNull(current.getPriority());
            assertNull(current.getStruck());
            assertEquals(mDeletedEntry.getUpdated(), current.getLastChanged().toInstant());
            assertTrue(current.getDeleted());
        } else/*from  w w  w.j  a v  a  2  s .  c  o  m*/
            fail("Unexpected Entry.");
    }

    mManager.getTransaction().begin();
    mEntry.setUpdated(Instant.now());
    mManager.getTransaction().commit();
    Response okResponse2 = target(String.format(url, mGroup.getId()))
            .queryParam("changedsince", ISO8601Utils.format(Date.from(preUpdate), true)).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse2.getStatus());
    EntryInfo[] oneEntryInfo = okResponse2.readEntity(EntryInfo[].class);
    assertEquals(1, oneEntryInfo.length);
    assertEquals(mEntry.getUUID(), UUID.fromString(oneEntryInfo[0].getUUID()));
    assertFalse(oneEntryInfo[0].getDeleted());
}

From source file:org.ng200.openolympus.services.ContestService.java

public boolean isContestOverIncludingAllTimeExtensions(final Contest contest) {
    return this.getContestEndIncludingAllTimeExtensions(contest).isBefore(Instant.now());
}

From source file:com.coinblesk.server.controller.AdminController.java

@RequestMapping(value = "/keys", method = GET)
@ResponseBody/*www . jav a 2  s.co m*/
public List<KeysDTO> getAllKeys() {
    NetworkParameters params = appConfig.getNetworkParameters();

    // Pre-calculate balances for each address
    Map<Address, Coin> balances = walletService.getBalanceByAddresses();

    List<Keys> keys = keyService.allKeys();

    // ...and summed for each public key
    Map<Keys, Long> balancesPerKeys = keys.stream()
            .collect(Collectors.toMap(Function.identity(), key -> key.timeLockedAddresses().stream()
                    .map(tla -> tla.toAddress(params)).map(balances::get).mapToLong(Coin::longValue).sum()));

    // Map the Keys entities to DTOs including the containing TimeLockedAddresses
    return keys.stream().map(key -> new KeysDTO(SerializeUtils.bytesToHex(key.clientPublicKey()),
            SerializeUtils.bytesToHex(key.serverPublicKey()), SerializeUtils.bytesToHex(key.serverPrivateKey()),
            Date.from(Instant.ofEpochSecond(key.timeCreated())), key.virtualBalance(), balancesPerKeys.get(key),
            key.virtualBalance() + balancesPerKeys.get(key), key.timeLockedAddresses().stream().map(tla -> {
                Instant createdAt = Instant.ofEpochSecond(tla.getTimeCreated());
                Instant lockedUntil = Instant.ofEpochSecond(tla.getLockTime());
                Coin balance = balances.get(tla.toAddress(params));
                return new TimeLockedAddressDTO(tla.toAddress(params).toString(),
                        "http://" + (params.getClass().equals(TestNet3Params.class) ? "tbtc." : "")
                                + "blockr.io/address/info/" + tla.toAddress(params),
                        Date.from(createdAt), Date.from(lockedUntil), lockedUntil.isAfter(Instant.now()),
                        balance.longValue());
            }).collect(Collectors.toList()))).collect(Collectors.toList());
}

From source file:com.yahoo.pulsar.broker.service.Consumer.java

public Consumer(Subscription subscription, SubType subType, long consumerId, String consumerName,
        int maxUnackedMessages, ServerCnx cnx, String appId) throws BrokerServiceException {

    this.subscription = subscription;
    this.subType = subType;
    this.consumerId = consumerId;
    this.consumerName = consumerName;
    this.maxUnackedMessages = maxUnackedMessages;
    this.cnx = cnx;
    this.msgOut = new Rate();
    this.msgRedeliver = new Rate();
    this.appId = appId;
    PERMITS_RECEIVED_WHILE_CONSUMER_BLOCKED_UPDATER.set(this, 0);
    MESSAGE_PERMITS_UPDATER.set(this, 0);
    UNACKED_MESSAGES_UPDATER.set(this, 0);

    stats = new ConsumerStats();
    stats.address = cnx.clientAddress().toString();
    stats.consumerName = consumerName;//from  ww  w  . j a v  a  2  s .  co m
    stats.connectedSince = DATE_FORMAT.format(Instant.now());

    if (subType == SubType.Shared) {
        this.pendingAcks = new ConcurrentOpenHashMap<PositionImpl, Integer>(256, 2);
    } else {
        // We don't need to keep track of pending acks if the subscription is not shared
        this.pendingAcks = null;
    }
}

From source file:org.noorganization.instalist.server.api.TaggedProductResourceTest.java

@Test
public void testGetTaggedProducts() throws Exception {
    String url = "/groups/%d/taggedproducts";

    Instant preUpdate = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request().get();
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").get();
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(401, wrongGroupResponse.getStatus());

    Response okResponse1 = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse1.getStatus());
    TaggedProductInfo[] allTaggedProductInfo = okResponse1.readEntity(TaggedProductInfo[].class);
    assertEquals(2, allTaggedProductInfo.length);
    for (TaggedProductInfo current : allTaggedProductInfo) {
        if (mTaggedProduct.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals(mTaggedProduct.getUpdated(), current.getLastChanged().toInstant());
            assertEquals(mTag.getUUID(), UUID.fromString(current.getTagUUID()));
            assertEquals(mProduct.getUUID(), UUID.fromString(current.getProductUUID()));
            assertFalse(current.getDeleted());
        } else if (mDeletedIngredient.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertNull(current.getTagUUID());
            assertNull(current.getProductUUID());
            assertEquals(mDeletedIngredient.getUpdated(), current.getLastChanged().toInstant());
            assertTrue(current.getDeleted());
        } else/*  w  ww  .  ja v a  2  s.  c  om*/
            fail("Unexpected TaggedProduct.");
    }

    mManager.getTransaction().begin();
    mTaggedProduct.setUpdated(Instant.now());
    mManager.getTransaction().commit();
    Response okResponse2 = target(String.format(url, mGroup.getId()))
            .queryParam("changedsince", ISO8601Utils.format(Date.from(preUpdate), true)).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse2.getStatus());
    TaggedProductInfo[] oneTaggedProductInfo = okResponse2.readEntity(TaggedProductInfo[].class);
    assertEquals(1, oneTaggedProductInfo.length);
    assertEquals(mTaggedProduct.getUUID(), UUID.fromString(oneTaggedProductInfo[0].getUUID()));
    assertFalse(oneTaggedProductInfo[0].getDeleted());
}

From source file:com.vmware.photon.controller.api.client.resource.ClusterApiTest.java

@Test
public void testResize() throws IOException {
    Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterApi(restClient);

    Task task = clusterApi.resize("dummy-cluster-id", 100);
    assertEquals(task, responseTask);/*  w  ww  . ja  va  2  s .  com*/
}