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.ng200.openolympus.services.SecurityService.java

public boolean isContestInProgressForUser(final Contest contest, String username) {
    return !contest.getStartTime().toInstant().isAfter(Instant.now()) && !this.contestService
            .getContestEndTimeForUser(contest, this.userRepository.findByUsername(username)).toInstant()
            .isBefore(Instant.now());
}

From source file:nl.ctrlaltdev.harbinger.filter.BlacklistFilterTest.java

@Test
public void shouldUnblockBlackListAfterTimeout() throws IOException, ServletException, InterruptedException {
    new Expectations() {
        {//from  w  w  w  . java 2 s. co  m
            chain.doFilter(request, response);
        }
    };
    request.setRemoteAddr("8.8.8.8");
    ctx.blacklist("8.8.8.8", Instant.now().plusSeconds(1));
    filter.doFilter(request, response, chain);
    Thread.sleep(1100L);
    filter.doFilter(request, response, chain);
}

From source file:com.netflix.spinnaker.igor.scm.AbstractCommitController.java

public List<Map<String, Object>> getNotFoundCommitsResponse(String projectKey, String repositorySlug, String to,
        String from, String url) {
    Map<String, Object> eMap = new HashMap<>();
    eMap.put("displayId", "NOT_FOUND");
    eMap.put("id", "NOT_FOUND");
    eMap.put("authorDisplayName", "UNKNOWN");
    eMap.put("timestamp", Instant.now());
    eMap.put("message", String.format("could not find any commits from %s to %s in %s %s/%s", from, to, url,
            projectKey, repositorySlug));
    eMap.put("commitUrl", url);
    return Collections.singletonList(eMap);
}

From source file:io.gravitee.management.service.impl.InstanceServiceImpl.java

@Override
public Collection<InstanceListItem> findInstances(boolean includeStopped) {
    Set<EventEntity> events;

    if (includeStopped) {
        events = eventService.findByType(instancesAllState);
    } else {/*ww  w. j a v a 2  s.  c  o m*/
        events = eventService.findByType(instancesRunningOnly);
    }

    Instant nowMinusXMinutes = Instant.now().minus(5, ChronoUnit.MINUTES);
    return events.stream().map(event -> {
        Map<String, String> props = event.getProperties();
        InstanceListItem instance = new InstanceListItem(props.get("id"));
        instance.setEvent(event.getId());
        instance.setLastHeartbeatAt(new Date(Long.parseLong(props.get("last_heartbeat_at"))));
        instance.setStartedAt(new Date(Long.parseLong(props.get("started_at"))));

        if (event.getPayload() != null) {
            try {
                InstanceInfo info = objectMapper.readValue(event.getPayload(), InstanceInfo.class);
                instance.setHostname(info.getHostname());
                instance.setIp(info.getIp());
                instance.setVersion(info.getVersion());
                instance.setTags(info.getTags());
                instance.setOperatingSystemName(info.getSystemProperties().get("os.name"));
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while getting instance informations from event payload", ioe);
            }
        }

        if (event.getType() == EventType.GATEWAY_STARTED) {
            instance.setState(InstanceState.STARTED);
            // If last heartbeat timestamp is < now - 5m, set as unknown state
            Instant lastHeartbeat = Instant.ofEpochMilli(instance.getLastHeartbeatAt().getTime());
            if (lastHeartbeat.isBefore(nowMinusXMinutes)) {
                instance.setState(InstanceState.UNKNOWN);
            }
        } else {
            instance.setState(InstanceState.STOPPED);
            instance.setStoppedAt(new Date(Long.parseLong(props.get("stopped_at"))));
        }

        return instance;
    }).collect(Collectors.toList());
}

From source file:ai.grakn.test.engine.tasks.storage.TaskStateGraphStoreTest.java

@Test
public void testTaskStateStoreRetrieve() {
    ShortExecutionMockTask task = new ShortExecutionMockTask();
    Instant runAt = Instant.now();
    Json configuration = Json.object("test key", "test value");

    TaskId id = stateStorage.newState(task(at(runAt), configuration));
    assertNotNull(id);//from  w  ww .  j a  v  a2  s  .com

    TaskState state = stateStorage.getState(id);
    assertNotNull(state);

    Assert.assertEquals(task.getClass(), state.taskClass());
    Assert.assertEquals(this.getClass().getName(), state.creator());
    assertEquals(runAt, state.schedule().runAt());
    assertFalse(state.schedule().isRecurring());
    assertEquals(Optional.empty(), state.schedule().interval());
    assertEquals(configuration.toString(), state.configuration().toString());
}

From source file:io.dropwizard.primer.PrimerBundleTests.java

@Test
public void testVerifyCall() throws JsonProcessingException {
    stubFor(post(urlEqualTo("/v1/verify/test/test"))
            .willReturn(//from w  w w  . j a va  2  s.  c  o m
                    aResponse().withStatus(200).withHeader("Content-Type", "application/json")
                            .withBody(mapper.writeValueAsBytes(VerifyResponse.builder()
                                    .expiresAt(Instant.now().plusSeconds(10000).toEpochMilli()).token("test")
                                    .userId("test").build()))));
    final JacksonDecoder decoder = new JacksonDecoder();
    final JacksonEncoder encoder = new JacksonEncoder();
    final Slf4jLogger logger = new Slf4jLogger();
    PrimerClient primerClient = Feign.builder().decoder(decoder).encoder(encoder)
            .errorDecoder((methodKey, response) -> {
                try {
                    final PrimerError error = environment.getObjectMapper()
                            .readValue(response.body().asInputStream(), PrimerError.class);
                    return PrimerException.builder().message(error.getMessage()).errorCode(error.getErrorCode())
                            .status(response.status()).build();
                } catch (IOException e) {
                    return PrimerException.builder().status(response.status()).errorCode("PR000")
                            .message(e.getMessage()).build();
                }
            }).client(new OkHttpClient()).logger(logger).logLevel(Logger.Level.BASIC)
            .target(PrimerClient.class, "http://localhost:9090");
    try {
        final VerifyResponse verifyResponse = primerClient.verify("test", "test", "test",
                ServiceUser.builder().id("test").name("test").role("test").build());
        assertEquals("test", verifyResponse.getUserId());
        assertEquals("test", verifyResponse.getToken());
    } catch (PrimerException e) {
        fail();
    }
}

From source file:de.rkl.tools.tzconv.model.ApplicationModel.java

private static SetMultimap<ZoneOffset, ZoneId> sortAvailableZoneIds() {
    final SortedSetMultimap<ZoneOffset, ZoneId> zoneIdMap = TreeMultimap.create(Ordering.natural().reverse(),
            new Ordering<ZoneId>() {
                @Override/* w  ww. j  av a  2  s .c  o  m*/
                public int compare(final ZoneId zoneId1, final ZoneId zoneId2) {
                    return ComparisonChain.start().compare(zoneId1.toString(), zoneId2.toString()).result();
                }
            }.nullsFirst());
    ZoneId.getAvailableZoneIds().stream().forEach(zoneId -> {
        final ZoneId zoneIdObject = ZoneId.of(zoneId);
        zoneIdMap.put(zoneIdObject.getRules().getStandardOffset(Instant.now()), zoneIdObject);
    });
    return ImmutableSetMultimap.copyOf(zoneIdMap);
}

From source file:com.orange.cepheus.broker.persistence.SubscriptionsRepositoryTest.java

@Test
public void saveSubscriptionTest() throws URISyntaxException, SubscriptionPersistenceException {
    SubscribeContext subscribeContext = createSubscribeContextTemperature();
    Subscription subscription = new Subscription("12345", Instant.now().plus(1, ChronoUnit.DAYS),
            subscribeContext);/*  www . j  a v a2 s  .c om*/
    subscriptionsRepository.saveSubscription(subscription);
    Map<String, Subscription> subscriptions = subscriptionsRepository.getAllSubscriptions();
    Assert.assertEquals(1, subscriptions.size());
    Assert.assertEquals(subscription.getSubscriptionId(), subscriptions.get("12345").getSubscriptionId());
    Assert.assertEquals(subscription.getExpirationDate(), subscriptions.get("12345").getExpirationDate());
    Assert.assertEquals(subscribeContext.getDuration(),
            subscriptions.get("12345").getSubscribeContext().getDuration());
}

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

@Test
public void testCreate() 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);

    TenantsApi tenantsApi = new TenantsApi(restClient);

    Task task = tenantsApi.create("foo");
    assertEquals(task, responseTask);/*from   w  ww.j  a v a2  s . c om*/
}

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

@Test
public void testCreate() 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);

    TenantsApi tenantsApi = new TenantsRestApi(restClient);

    Task task = tenantsApi.create("foo");
    assertEquals(task, responseTask);/*  w  w  w  .j a va 2s. c om*/
}