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:org.createnet.raptor.db.mapdb.MapDBConnectionTest.java

private void populateObjectData(long dataLength) throws IOException {

    ObjectNode obj = loadData("model");

    obj.put("id", "test1");
    obj.put("userId", "test-user");
    objectStore.set(obj.get("id").asText(), obj, 0);

    obj.put("id", "test2");
    obj.put("userId", "test-user-x");
    objectStore.set(obj.get("id").asText(), obj, 0);

    obj.put("id", "test3");
    obj.put("userId", "test-user");
    objectStore.set(obj.get("id").asText(), obj, 0);

    // push data//from ww  w  . j  av a 2  s .com
    for (int i = 0; i < dataLength; i++) {

        ObjectNode record = loadData("record");

        String streamId = "mylocation";
        String objId = "test1";
        String userId = "test-user";

        Long timestamp = Instant.now().getEpochSecond() + i;

        record.put("streamId", streamId);
        record.put("objectId", objId);
        record.put("userId", userId);

        record.put("timestamp", timestamp);

        String key = String.join("-", new String[] { objId, streamId, timestamp.toString() });
        dataStore.set(key, record, 0);

    }

}

From source file:ddf.security.samlp.impl.SamlValidator.java

protected void checkTimestamp() throws ValidationException {
    DateTime issueInstant = getIssueInstant();
    if (issueInstant == null) {
        throw new ValidationException("Issue Instant cannot be null!");
    }/*  w  w w .  j a v  a2  s. co  m*/

    Instant instant = Instant.ofEpochMilli(issueInstant.getMillis());
    Instant now = Instant.now();
    if (instant.minus(builder.clockSkew).isAfter(now)) {
        throw new ValidationException("Issue Instant cannot be in the future");
    }

    if (instant.plus(builder.clockSkew).isBefore(now.minus(builder.timeout))) {
        throw new ValidationException("Issue Instant was outside valid time range");
    }

}

From source file:dk.nversion.jwt.JWTTest.java

/**
* Test of JWT encode private key//from ww  w .  j a  v a 2 s.  c o m
*/
@Test
public void testJWTEncodePrivateKey() throws CertificateException {
    System.out.println("encode");

    try {
        // Load private key
        String privatekeyfile = getClass().getClassLoader().getResource("example.org.pem").getFile();
        PrivateKey privkey = loadPrivateKey(privatekeyfile);
        JWT token = new JWT(Algorithm.RS256, privkey);

        long unixtime = Instant.now().getEpochSecond();

        token.setId("1"); // TODO generate random number
        token.setIssuer("http://localhost/oauth/");
        token.setAudience("http://localhost/service");
        token.setIssuedAt(unixtime);
        token.setNotBefore(unixtime - 5 * 60); // 5 minutes before issued at
        token.setExpires(unixtime + 10 * 60); // 10 minutes after issued at            
        token.setSubject("tlb@nversion.dk");

        String result = token.encode();

        String certificatefile = getClass().getClassLoader().getResource("example.org.crt").getFile();
        PublicKey pubkey = loadCertificate(certificatefile);

        JWT token2 = new JWT(result, pubkey, "http://localhost/service");

        System.out.println("stuff");

    } catch (IOException | JWTException | NoSuchAlgorithmException | InvalidKeyException
            | InvalidKeySpecException | SignatureException ex) {
        fail("Failed with exception");
    }
}

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

@Before
public void setUp() throws Exception {
    super.setUp();

    CommonData data = new CommonData();
    mManager = DatabaseHelper.getInstance().getManager();
    mManager.getTransaction().begin();/*  ww w  . ja v a 2 s .c o  m*/

    Instant creation = Instant.now();
    mGroup = new DeviceGroup();
    mUnit = new Unit().withGroup(mGroup).withName("unit1").withUUID(UUID.randomUUID());
    mProduct = new Product().withGroup(mGroup).withName("product1").withUUID(UUID.randomUUID())
            .withDefaultAmount(1f).withStepAmount(0.5f).withUpdated(creation);
    mProductWU = new Product().withGroup(mGroup).withName("product2").withUnit(mUnit)
            .withUUID(UUID.randomUUID()).withDefaultAmount(2f).withStepAmount(2f).withUpdated(creation);
    mDeletedProduct = new DeletedObject().withGroup(mGroup).withUUID(UUID.randomUUID())
            .withType(DeletedObject.Type.PRODUCT).withUpdated(creation);
    mNAGroup = new DeviceGroup();
    mNAProduct = new Product().withGroup(mNAGroup).withName("product3").withUUID(UUID.randomUUID());

    Device authorizedDevice = new Device().withAuthorized(true).withGroup(mGroup).withName("dev1")
            .withSecret(data.mEncryptedSecret);

    mManager.persist(mGroup);
    mManager.persist(mUnit);
    mManager.persist(mProduct);
    mManager.persist(mProductWU);
    mManager.persist(mDeletedProduct);
    mManager.persist(mNAGroup);
    mManager.persist(mNAProduct);
    mManager.persist(authorizedDevice);
    mManager.getTransaction().commit();

    mManager.refresh(mGroup);
    mManager.refresh(mUnit);
    mManager.refresh(mProduct);
    mManager.refresh(mProductWU);
    mManager.refresh(mDeletedProduct);
    mManager.refresh(mNAGroup);
    mManager.refresh(mNAProduct);
    mManager.refresh(authorizedDevice);

    mToken = ControllerFactory.getAuthController().getTokenByHttpAuth(mManager, authorizedDevice.getId(),
            data.mSecret);
    assertNotNull(mToken);
}

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

@Before
public void setUp() throws Exception {
    super.setUp();

    CommonData data = new CommonData();
    mManager = DatabaseHelper.getInstance().getManager();
    mManager.getTransaction().begin();//from   w  w  w  . j  a  va 2s  .com

    mUpdate = Instant.now();

    mGroup = new DeviceGroup();
    mCat = new Category().withGroup(mGroup).withName("").withUUID(UUID.randomUUID()).withUpdated(mUpdate);
    mListWC = new ShoppingList().withGroup(mGroup).withName("list1").withCategrory(mCat)
            .withUUID(UUID.randomUUID()).withUpdated(mUpdate);
    mListWOC = new ShoppingList().withGroup(mGroup).withName("list2").withUUID(UUID.randomUUID())
            .withUpdated(mUpdate);
    mDeletedList = new DeletedObject().withGroup(mGroup).withUUID(UUID.randomUUID())
            .withType(DeletedObject.Type.LIST).withUpdated(mUpdate);
    mNAGroup = new DeviceGroup().withUpdated(Date.from(mUpdate));
    mNAList = new ShoppingList().withGroup(mNAGroup).withName("list3").withUUID(UUID.randomUUID())
            .withUpdated(mUpdate);

    Device authorizedDevice = new Device().withAuthorized(true).withGroup(mGroup).withName("dev1")
            .withSecret(data.mEncryptedSecret).withCreated(Date.from(mUpdate));

    mManager.persist(mGroup);
    mManager.persist(mCat);
    mManager.persist(mListWC);
    mManager.persist(mListWOC);
    mManager.persist(mDeletedList);
    mManager.persist(mNAGroup);
    mManager.persist(mNAList);
    mManager.persist(authorizedDevice);
    mManager.getTransaction().commit();

    mManager.refresh(mGroup);
    mManager.refresh(mCat);
    mManager.refresh(mListWC);
    mManager.refresh(mListWOC);
    mManager.refresh(mDeletedList);
    mManager.refresh(mNAGroup);
    mManager.refresh(mNAList);
    mManager.refresh(authorizedDevice);

    mToken = ControllerFactory.getAuthController().getTokenByHttpAuth(mManager, authorizedDevice.getId(),
            data.mSecret);
    assertNotNull(mToken);
}

From source file:oauth2.services.ChangePasswordService.java

private void changePassword(User user, String newPassword) {
    user.setPassword(passwordEncoder.encode(newPassword));
    user.setPasswordExpiresAt(Instant.now().plus(90, ChronoUnit.DAYS));
}

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

@Test
public void testCreateAsync() throws Exception {
    final 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);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override//from   w  w w  .  ja  va 2  s. co m
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.pw.ism.heartbeat.InMemoryHeartbeatRepositoryTest.java

@Test
public void shouldRefreshHeartbeat() throws Exception {
    Heartbeat hb1 = new Heartbeat();
    hb1.setCustomer("TEST1");
    hb1.setNetwork("NETWORK1");

    repo.addHeartbeat(hb1, Instant.now().minusSeconds(5));

    List<Heartbeat> list = repo.getExpiredHeartbeats(3);
    Assert.isTrue(list.contains(hb1));//from   w ww  .ja va 2 s .  c  o  m

    Heartbeat hb2 = new Heartbeat();
    hb2.setCustomer("TEST1");
    hb2.setNetwork("NETWORK1");

    repo.addHeartbeat(hb2, Instant.now().minusSeconds(2));

    list = repo.getExpiredHeartbeats(3);
    Assert.isTrue(list.isEmpty());
}

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

@Before
public void setUp() throws Exception {
    super.setUp();

    CommonData data = new CommonData();
    mManager = DatabaseHelper.getInstance().getManager();
    mManager.getTransaction().begin();/*from   ww w  .  j  a va  2  s  . c  om*/

    Instant creation = Instant.now();
    mGroup = new DeviceGroup();
    mProduct = new Product().withGroup(mGroup).withName("product1").withUUID(UUID.randomUUID())
            .withUpdated(creation);
    mList = new ShoppingList().withGroup(mGroup).withName("list1").withUUID(UUID.randomUUID())
            .withUpdated(creation);
    mEntry = new ListEntry().withGroup(mGroup).withUUID(UUID.randomUUID()).withAmount(1f).withPriority(2)
            .withUpdated(creation).withProduct(mProduct).withList(mList);
    mDeletedEntry = new DeletedObject().withGroup(mGroup).withUUID(UUID.randomUUID())
            .withType(DeletedObject.Type.LISTENTRY).withUpdated(creation);
    mNAGroup = new DeviceGroup();
    mNAList = new ShoppingList().withName("list2").withUUID(UUID.randomUUID()).withGroup(mNAGroup);
    mNAProduct = new Product().withGroup(mNAGroup).withUUID(UUID.randomUUID()).withName("product2");
    mNAEntry = new ListEntry().withGroup(mNAGroup).withUUID(UUID.randomUUID()).withProduct(mNAProduct)
            .withList(mList);

    Device authorizedDevice = new Device().withAuthorized(true).withGroup(mGroup).withName("dev1")
            .withSecret(data.mEncryptedSecret);

    mManager.persist(mGroup);
    mManager.persist(mProduct);
    mManager.persist(mList);
    mManager.persist(mEntry);
    mManager.persist(mDeletedEntry);
    mManager.persist(mNAGroup);
    mManager.persist(mNAProduct);
    mManager.persist(mNAList);
    mManager.persist(mNAEntry);
    mManager.persist(authorizedDevice);
    mManager.getTransaction().commit();

    mManager.refresh(mGroup);
    mManager.refresh(mProduct);
    mManager.refresh(mList);
    mManager.refresh(mEntry);
    mManager.refresh(mDeletedEntry);
    mManager.refresh(mNAGroup);
    mManager.refresh(mNAProduct);
    mManager.refresh(mNAList);
    mManager.refresh(mNAEntry);
    mManager.refresh(authorizedDevice);

    mToken = ControllerFactory.getAuthController().getTokenByHttpAuth(mManager, authorizedDevice.getId(),
            data.mSecret);
    assertNotNull(mToken);
}

From source file:com.devicehive.handler.notification.NotificationInsertHandlerTest.java

@Test
public void testInsertNotification() throws ExecutionException, InterruptedException, TimeoutException {
    final String guid = UUID.randomUUID().toString();
    final long id = System.nanoTime();

    DeviceNotification originalNotification = new DeviceNotification();
    originalNotification.setTimestamp(Date.from(Instant.now()));
    originalNotification.setId(id);// w w w  .j  a va 2 s  .  c  o m
    originalNotification.setDeviceGuid(guid);
    originalNotification.setNotification("SOME TEST DATA");
    originalNotification.setParameters(new JsonStringWrapper("{\"param1\":\"value1\",\"param2\":\"value2\"}"));
    NotificationInsertRequest nir = new NotificationInsertRequest(originalNotification);
    Response response = handler.handle(Request.newBuilder().withBody(nir).build());

    assertTrue(hazelcastService.find(id, guid, DeviceNotification.class)
            .filter(notification -> notification.equals(originalNotification)).isPresent());

    ArgumentCaptor<NotificationEvent> eventCaptor = ArgumentCaptor.forClass(NotificationEvent.class);
    verify(eventBus).publish(eventCaptor.capture());
    NotificationEvent event = eventCaptor.getValue();
    assertEquals(event.getNotification(), originalNotification);

    assertNotNull(response);
    assertNotNull(response.getBody());
    assertTrue(response.getBody() instanceof NotificationInsertResponse);
    NotificationInsertResponse body = (NotificationInsertResponse) response.getBody();
    assertEquals(body.getDeviceNotification(), originalNotification);
}