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.noorganization.instalist.server.api.ProductResourceTest.java

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

    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());
    ProductInfo[] allProductInfo = okResponse1.readEntity(ProductInfo[].class);
    assertEquals(3, allProductInfo.length);
    for (ProductInfo current : allProductInfo) {
        if (mProduct.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals("product1", current.getName());
            assertEquals(mProduct.getUpdated(), current.getLastChanged().toInstant());
            assertNull(current.getRemoveUnit());
            assertNull(current.getUnitUUID());
            assertEquals(1f, current.getDefaultAmount(), 0.001f);
            assertEquals(0.5f, current.getStepAmount(), 0.001f);
            assertFalse(current.getDeleted());
        } else if (mProductWU.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals("product2", current.getName());
            assertEquals(mProductWU.getUpdated(), current.getLastChanged().toInstant());
            assertNull(current.getRemoveUnit());
            assertEquals(mUnit.getUUID(), UUID.fromString(current.getUnitUUID()));
            assertEquals(2f, current.getDefaultAmount(), 0.001f);
            assertEquals(2f, current.getStepAmount(), 0.001f);
            assertFalse(current.getDeleted());
        } else if (mDeletedProduct.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertNull(current.getName());
            assertNull(current.getRemoveUnit());
            assertNull(current.getUnitUUID());
            assertNull(current.getDefaultAmount());
            assertNull(current.getStepAmount());
            assertEquals(mDeletedProduct.getUpdated(), current.getLastChanged().toInstant());
            assertTrue(current.getDeleted());
        } else/*from ww  w. jav a2  s.c  o m*/
            fail("Unexpected unit.");
    }

    mManager.getTransaction().begin();
    mProduct.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());
    ProductInfo[] oneProductInfo = okResponse2.readEntity(ProductInfo[].class);
    assertEquals(1, oneProductInfo.length);
    assertEquals(mProduct.getUUID(), UUID.fromString(oneProductInfo[0].getUUID()));
    assertEquals("product1", oneProductInfo[0].getName());
    assertFalse(oneProductInfo[0].getDeleted());
}

From source file:io.pivotal.strepsirrhini.chaosloris.docs.EventDocumentation.java

@Test
public void eventList() throws Exception {
    Schedule schedule = new Schedule("0 0 * * * *", "hourly");
    schedule.setId(1L);/*from   w w w  .  j  av  a 2  s .  com*/

    Application application = new Application(UUID.randomUUID());
    application.setId(2L);

    Chaos chaos = new Chaos(application, 0.1, schedule);
    chaos.setId(3L);

    PageRequest pageable = new PageRequest(2, 3);

    when(this.eventRepository.findAll(pageable)).thenReturn(page(pageable, item -> {
        Event event = new Event(chaos, Instant.now(), Collections.singletonList((int) item % 10), 10);
        event.setId(item);
        return event;
    }));

    this.mockMvc.perform(get("/events" + query(pageable)).accept(HAL_JSON))
            .andDo(document(listRequestParameters(),
                    listResponseFields(fieldWithPath("_embedded.events").description(
                            "A collection of Events as described in [Read an Event](#read-an-event)")),
                    listLinks()));
}

From source file:com.teradata.benchto.driver.execution.ExecutionSynchronizer.java

/**
 * Executes {@code callable} when time comes. The {@code callable} gets executed immediately, without
 * offloading to a backghround thread, if execution time requested has already passed.
 *///  ww  w  .j av  a  2s  . c o m
public <T> CompletableFuture<T> execute(Instant when, Callable<T> callable) {
    if (!Instant.now().isBefore(when)) {
        // Run immediately.
        try {
            return completedFuture(callable.call());
        } catch (Exception e) {
            CompletableFuture<T> future = new CompletableFuture<>();
            future.completeExceptionally(e);
            return future;
        }
    }

    long delay = Instant.now().until(when, ChronoUnit.MILLIS);
    CompletableFuture<T> future = new CompletableFuture<>();
    executorService.schedule(() -> {
        try {
            future.complete(callable.call());
        } catch (Throwable e) {
            future.completeExceptionally(e);
            throw e;
        }
        return null;
    }, delay, MILLISECONDS);

    return future;
}

From source file:com.skipjaq.awspricing.pricing.AwsPricing.java

private List<PricingInfo.Term> getTerms(List<String> skus) {
    return skus.stream().map(s -> pricingInfo.getTerms().get("OnDemand").get(s).values())
            .flatMap(v -> v.stream()/*from w  w w .ja v  a  2s . c  o  m*/
                    // TODO(mirek) check if term is only one for product
                    .filter(t -> Date.from(Instant.now()).after(getDate(t.getEffectiveDate()))))
            .collect(Collectors.toList());
}

From source file:com.hurence.logisland.connect.opc.CommonOpcSourceTask.java

@Override
public void start(Map<String, String> props) {
    setConfigurationProperties(props);//from w w w .ja v a2  s. co m

    transferQueue = new LinkedTransferQueue<>();
    opcOperations = new SmartOpcOperations<>(createOpcOperations());
    ConnectionProfile connectionProfile = createConnectionProfile();
    host = connectionProfile.getConnectionUri().getHost();
    tagInfoMap = CommonUtils.parseTagsFromProperties(props).stream()
            .collect(Collectors.toMap(TagInfo::getTagId, Function.identity()));
    minWaitTime = Math.min(10, tagInfoMap.values().stream().map(TagInfo::getSamplingInterval)
            .mapToLong(Duration::toMillis).min().getAsLong());
    opcOperations.connect(connectionProfile);
    if (!opcOperations.awaitConnected()) {
        throw new ConnectException("Unable to connect");
    }

    //set up polling source emission
    pollingScheduler = Executors.newSingleThreadScheduledExecutor();
    streamingThread = Executors.newSingleThreadExecutor();
    Map<Duration, List<TagInfo>> pollingMap = tagInfoMap.values().stream()
            .filter(tagInfo -> StreamingMode.POLL.equals(tagInfo.getStreamingMode()))
            .collect(Collectors.groupingBy(TagInfo::getSamplingInterval));
    final Map<String, OpcData> lastValues = Collections.synchronizedMap(new HashMap<>());
    pollingMap.forEach((k, v) -> pollingScheduler.scheduleAtFixedRate(() -> {
        final Instant now = Instant.now();
        v.stream().map(TagInfo::getTagId).map(lastValues::get).filter(Functions.not(Objects::isNull))
                .map(data -> Pair.of(now, data)).forEach(transferQueue::add);

    }, 0, k.toNanos(), TimeUnit.NANOSECONDS));
    //then subscribe for all
    final SubscriptionConfiguration subscriptionConfiguration = new SubscriptionConfiguration()
            .withDefaultSamplingInterval(Duration.ofMillis(10_000));
    tagInfoMap.values().forEach(tagInfo -> subscriptionConfiguration
            .withTagSamplingIntervalForTag(tagInfo.getTagId(), tagInfo.getSamplingInterval()));
    running.set(true);
    streamingThread.submit(() -> {
        while (running.get()) {
            try {
                createSessionIfNeeded();
                if (session == null) {
                    return;
                }

                session.stream(subscriptionConfiguration,
                        tagInfoMap.keySet().toArray(new String[tagInfoMap.size()])).forEach(opcData -> {
                            if (tagInfoMap.get(opcData.getTag()).getStreamingMode()
                                    .equals(StreamingMode.SUBSCRIBE)) {
                                transferQueue.add(Pair.of(
                                        hasServerSideSampling() ? opcData.getTimestamp() : Instant.now(),
                                        opcData));
                            } else {
                                lastValues.put(opcData.getTag(), opcData);
                            }
                        });
            } catch (Exception e) {
                if (running.get()) {
                    logger.warn("Stream interrupted while reading from " + host, e);
                    safeCloseSession();
                    lastValues.clear();

                }
            }
        }
    });

}

From source file:org.jhk.pulsing.web.service.prod.PulseService.java

/**
 * Hmmm should work in DRPC from storm+trident to get notified of new batch and then send 
 * the message to client component for new set? Look into it since familiar only w/ trident
 * //from www .  jav  a  2  s .c  o  m
 * @param numMinutes
 * @return
 */
@Override
public Map<Long, String> getTrendingPulseSubscriptions(int numMinutes) {

    Instant current = Instant.now();
    Instant beforeRange = current.minus(numMinutes, ChronoUnit.MINUTES);

    Optional<Set<String>> optTps = redisPulseDao.getTrendingPulseSubscriptions(beforeRange.getEpochSecond(),
            current.getEpochSecond());

    @SuppressWarnings("unchecked")
    Map<Long, String> tpSubscriptions = Collections.EMPTY_MAP;

    if (optTps.isPresent()) {
        tpSubscriptions = PulseServiceUtil.processTrendingPulseSubscribe(optTps.get(), _objectMapper);
    }
    ;

    return tpSubscriptions;
}

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

private DeviceNotification createNotification(long id, String guid) {
    DeviceNotification notification = new DeviceNotification();
    notification.setId(id);//w w w . ja va2s . c om
    notification.setTimestamp(Date.from(Instant.now()));
    notification.setDeviceGuid(guid);
    notification.setNotification("SOME TEST DATA_" + id);
    notification.setParameters(new JsonStringWrapper("{\"param1\":\"value1\",\"param2\":\"value2\"}"));
    return notification;
}

From source file:io.kamax.mxisd.threepid.session.ThreePidSession.java

public synchronized void validate(String token) {
    if (Instant.now().minus(24, ChronoUnit.HOURS).isAfter(getCreationTime())) {
        throw new BadRequestException("Session " + getId() + " has expired");
    }/*ww w .  java  2 s. co  m*/

    if (!StringUtils.equals(this.token, token)) {
        throw new InvalidCredentialsException();
    }

    if (isValidated()) {
        return;
    }

    validationTimestamp = Instant.now();
    isValidated = true;
}

From source file:org.lendingclub.mercator.newrelic.NewRelicScanner.java

private void scanAlertPolicies() {

    Instant startTime = Instant.now();

    ObjectNode alertPolicies = getNewRelicClient().getAlertPolicies();
    Preconditions.checkNotNull(getProjector().getNeoRxClient(), "neorx client must be set");

    String cypher = "WITH {json} as data " + "UNWIND data.policies as policy "
            + "MERGE ( s:NewRelicAlertPolicy { nr_policyId: toString(policy.id), nr_accountId:{accountId} } ) "
            + "ON CREATE SET s.name = policy.name, s.policyCreatedTs = policy.created_at, s.policyUpdatedTs = policy.updated_at, "
            + "s.createTs = timestamp(), s.updateTs = timestamp() "
            + "ON MATCH SET s.policyUpdatedTs = policy.updated_at, s.updateTs = timestamp() ";

    getProjector().getNeoRxClient().execCypher(cypher, "json", alertPolicies, "accountId",
            clientSupplier.get().getAccountId());
    Instant endTime = Instant.now();

    logger.info("Updating neo4j with the latest information about {} NewRelic alert policies took {} secs",
            alertPolicies.get("policies").size(), Duration.between(startTime, endTime).getSeconds());
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedPUTUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*w w w .  j av a  2  s  .  c o m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "PUT", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    connection.setReadTimeout(3000);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(10);
    connection.connect();

    try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), UTF_8)) {
        out.write(TEST_DATA);
    } finally {
        connection.disconnect();
    }

    // Wait for file to become available
    for (int i = 0; i < 10; i++) {
        Thread.sleep(500);

        if (mantaClient.existsAndIsAccessible(path)) {
            break;
        }
    }

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA);
}