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.vmware.photon.controller.api.client.resource.FlavorRestApiTest.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 FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override/*  w w w  .j ava2  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:io.pivotal.strepsirrhini.chaosloris.reaper.EventReaperTest.java

@Test
public void doReap() {
    Schedule schedule = new Schedule("test-schedule", "test-name");
    this.scheduleRepository.saveAndFlush(schedule);

    Application application = new Application(UUID.randomUUID());
    this.applicationRepository.saveAndFlush(application);

    Chaos chaos = new Chaos(application, 0.1, schedule);
    this.chaosRepository.saveAndFlush(chaos);

    Instant now = Instant.now();

    Event event1 = new Event(chaos, now.minus(3, DAYS), Collections.emptyList(), Integer.MIN_VALUE);
    this.eventRepository.saveAndFlush(event1);

    Event event2 = new Event(chaos, now, Collections.emptyList(), Integer.MIN_VALUE);
    this.eventRepository.saveAndFlush(event2);

    Event event3 = new Event(chaos, now.plus(3, DAYS), Collections.emptyList(), Integer.MIN_VALUE);
    this.eventRepository.saveAndFlush(event3);

    this.eventReaper.doReap().as(StepVerifier::create).expectNext(1L).expectComplete().verify();

    List<Event> events = this.eventRepository.findAll();
    assertThat(events).containsExactly(event2, event3);
}

From source file:org.noorganization.instalist.server.api.IngredientResourceTest.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 2 s . c  om*/

    Instant creation = Instant.now();
    mGroup = new DeviceGroup();
    mProduct = new Product().withGroup(mGroup).withName("product1").withUUID(UUID.randomUUID())
            .withUpdated(creation);
    mRecipe = new Recipe().withGroup(mGroup).withName("recipe1").withUUID(UUID.randomUUID())
            .withUpdated(creation);
    mIngredient = new Ingredient().withGroup(mGroup).withUUID(UUID.randomUUID()).withAmount(1f)
            .withUpdated(creation).withProduct(mProduct).withRecipe(mRecipe);
    mDeletedIngredient = new DeletedObject().withGroup(mGroup).withUUID(UUID.randomUUID())
            .withType(DeletedObject.Type.INGREDIENT).withUpdated(creation);
    mNAGroup = new DeviceGroup();
    mNARecipe = new Recipe().withName("recipe2").withUUID(UUID.randomUUID()).withGroup(mNAGroup);
    mNAProduct = new Product().withGroup(mNAGroup).withUUID(UUID.randomUUID()).withName("product2");
    mNAIngredient = new Ingredient().withGroup(mNAGroup).withUUID(UUID.randomUUID()).withProduct(mNAProduct)
            .withRecipe(mNARecipe);

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

    mManager.persist(mGroup);
    mManager.persist(mProduct);
    mManager.persist(mRecipe);
    mManager.persist(mIngredient);
    mManager.persist(mDeletedIngredient);
    mManager.persist(mNAGroup);
    mManager.persist(mNAProduct);
    mManager.persist(mNARecipe);
    mManager.persist(mNAIngredient);
    mManager.persist(authorizedDevice);
    mManager.getTransaction().commit();

    mManager.refresh(mGroup);
    mManager.refresh(mProduct);
    mManager.refresh(mRecipe);
    mManager.refresh(mIngredient);
    mManager.refresh(mDeletedIngredient);
    mManager.refresh(mNAGroup);
    mManager.refresh(mNAProduct);
    mManager.refresh(mNARecipe);
    mManager.refresh(mNAIngredient);
    mManager.refresh(authorizedDevice);

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

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

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

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

    Instant creation = Instant.now();
    mGroup = new DeviceGroup();
    mProduct = new Product().withGroup(mGroup).withName("product1").withUUID(UUID.randomUUID())
            .withUpdated(creation);
    mTag = new Tag().withGroup(mGroup).withName("tag1").withUUID(UUID.randomUUID()).withUpdated(creation);
    mTaggedProduct = new TaggedProduct().withGroup(mGroup).withUUID(UUID.randomUUID()).withUpdated(creation)
            .withProduct(mProduct).withTag(mTag);
    mDeletedIngredient = new DeletedObject().withGroup(mGroup).withUUID(UUID.randomUUID())
            .withType(DeletedObject.Type.TAGGEDPRODUCT).withUpdated(creation);
    mNAGroup = new DeviceGroup();
    mNATag = new Tag().withName("tag2").withUUID(UUID.randomUUID()).withGroup(mNAGroup);
    mNAProduct = new Product().withGroup(mNAGroup).withUUID(UUID.randomUUID()).withName("product2");
    mNATaggedProduct = new TaggedProduct().withGroup(mNAGroup).withUUID(UUID.randomUUID())
            .withProduct(mNAProduct).withTag(mNATag);

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

    mManager.persist(mGroup);
    mManager.persist(mProduct);
    mManager.persist(mTag);
    mManager.persist(mTaggedProduct);
    mManager.persist(mDeletedIngredient);
    mManager.persist(mNAGroup);
    mManager.persist(mNAProduct);
    mManager.persist(mNATag);
    mManager.persist(mNATaggedProduct);
    mManager.persist(authorizedDevice);
    mManager.getTransaction().commit();

    mManager.refresh(mGroup);
    mManager.refresh(mProduct);
    mManager.refresh(mTag);
    mManager.refresh(mTaggedProduct);
    mManager.refresh(mDeletedIngredient);
    mManager.refresh(mNAGroup);
    mManager.refresh(mNAProduct);
    mManager.refresh(mNATag);
    mManager.refresh(mNATaggedProduct);
    mManager.refresh(authorizedDevice);

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

From source file:keepinchecker.utility.EmailUtilities.java

protected static boolean hasScheduledEmailBeenSent(User user) {
    String emailFrequency = user.getEmailFrequency();
    long emailLastSentDate = user.getEmailLastSentDate();
    Duration timeBetweenLastEmailSentToNow = Duration.between(new Date(emailLastSentDate).toInstant(),
            Instant.now());

    if (StringUtils.equals(emailFrequency, User.EMAIL_FREQUENCY_WEEKLY)
            && timeBetweenLastEmailSentToNow.toDays() < 7) {
        return true;
    } else if (StringUtils.equals(emailFrequency, User.EMAIL_FREQUENCY_DAILY)
            && timeBetweenLastEmailSentToNow.toDays() < 1) {
        return true;
    }/*from w  ww .j  av  a 2  s  .c  o m*/

    return false;
}

From source file:com.netflix.genie.web.util.UnixProcessChecker.java

/**
 * {@inheritDoc}//from   ww w. ja  va2 s.  c  o  m
 */
@Override
public void checkProcess() throws GenieTimeoutException, ExecuteException, IOException {
    this.executor.execute(this.commandLine);

    // If we get here the process is still running. Check if it should be killed due to timeout.
    if (Instant.now().isAfter(this.timeout)) {
        throw new GenieTimeoutException("Job has exceeded its timeout time of " + this.timeout);
    }
}

From source file:io.gravitee.gateway.services.sync.ScheduledSyncService.java

/**
 * Synchronization done when Gravitee node is starting.
 * This sync phase must be done by all node before starting.
 *///from w ww  . ja  v  a2s  .  co m
private void doSync() {
    logger.debug("Synchronization #{} started at {}", counter.incrementAndGet(), Instant.now().toString());

    syncStateManager.refresh();

    logger.debug("Synchronization #{} ended at {}", counter.get(), Instant.now().toString());
}

From source file:eu.hansolo.tilesfx.tools.Location.java

public Location() {
    this(0, 0, 0, Instant.now(), "", "", TileColor.BLUE);
}

From source file:se.curity.examples.oauth.opaque.OpaqueTokenValidator.java

public @Nullable OpaqueToken validate(String token) throws IOException {
    @Nullable//from  w ww .  j  a  v  a 2 s . c o m
    OpaqueToken cachedValue = _tokenCache.get(token);
    if (cachedValue != null) {
        return cachedValue;
    }

    String introspectJson = introspect(token);
    OAuthIntrospectResponse response = parseIntrospectResponse(introspectJson);
    if (response.getActive()) {
        OpaqueToken newToken = new OpaqueToken(response.getSub(), response.getExp(), response.getScope());
        if (newToken.getExpiresAt().isAfter(Instant.now())) {
            //Note: If this cache is backed by some persistent storage, the token should be hashed and not stored
            //      in clear text
            _tokenCache.put(token, newToken);
            return newToken;
        }
    }
    return null;
}

From source file:com.bouncestorage.swiftproxy.v2.Identity.java

@Path("tokens")
@POST//from  ww  w .j a va 2s  . com
@Produces(MediaType.APPLICATION_JSON)
public Response auth(AuthV2Request payload, @HeaderParam("Host") Optional<String> host,
        @Context Request request) {
    String tenant = payload.auth.tenantName;
    String identity = payload.auth.passwordCredentials.username;
    if (Strings.isNullOrEmpty(tenant)) {
        tenant = identity;
    }
    String credential = payload.auth.passwordCredentials.password;
    String authToken = null;
    try {
        authToken = ((BounceResourceConfig) application).authenticate(tenant + ":" + identity, credential);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    if (authToken == null) {
        return notAuthorized();
    }

    String storageURL = host.orElseGet(() -> request.getLocalAddr() + ":" + request.getLocalPort());
    String scheme = request.getScheme();
    tenant = "AUTH_" + tenant;
    storageURL = scheme + "://" + storageURL + "/v1/" + tenant;

    AuthV2Response resp = new AuthV2Response();
    resp.access.token.id = authToken;
    resp.access.token.expires = Instant.now().plusSeconds(InfoResource.CONFIG.tempauth.token_life);
    resp.access.token.tenant = new IDAndName(tenant, tenant);
    resp.access.user = new AuthV2Response.Access.User(identity, identity);
    resp.access.user.roles.add(new IDAndName(identity, identity));
    if (!identity.equals(tenant)) {
        resp.access.user.roles.add(new IDAndName(tenant, tenant));
    }

    AuthV2Response.Access.ServiceCatalog.Endpoint endpoint = new AuthV2Response.Access.ServiceCatalog.Endpoint();
    try {
        endpoint.publicURL = new URL(storageURL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw propagate(e);
    }
    endpoint.tenantId = tenant;
    resp.access.serviceCatalog[0].endpoints.add(endpoint);
    org.jclouds.Context c = getBlobStore(authToken).get().getContext().unwrap();
    resp.access.serviceCatalog[0].name += String.format(" (%s %s)", c.getId(),
            c.getProviderMetadata().getEndpoint());
    return Response.ok(resp).build();
}