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.TenantsRestApiTest.java

@Test
public void testDelete() 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.delete("foo");
    assertEquals(task, responseTask);/*from   w  w w.  jav a 2 s. co m*/
}

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

@Test
public void testDeleteImageAsync() throws IOException, InterruptedException {
    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);

    ImagesApi imagesApi = new ImagesApi(this.restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    imagesApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*from  w  ww  .ja  v  a2s  .  c om*/
        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:keywhiz.service.resources.admin.SecretsResource.java

/**
 * Create Secret//from  w  ww.j a va  2  s  .  c o m
 *
 * @excludeParams user
 * @param request the JSON client request used to formulate the Secret
 *
 * @description Creates a Secret with the name from a valid secret request.
 * Used by Keywhiz CLI and the web ui.
 * @responseMessage 200 Successfully created Secret
 * @responseMessage 400 Secret with given name already exists
 */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createSecret(@Auth User user, @Valid CreateSecretRequest request) {

    logger.info("User '{}' creating secret '{}'.", user, request.name);

    Secret secret;
    try {
        SecretController.SecretBuilder builder = secretController.builder(request.name, request.content,
                user.getName(), request.expiry);

        if (request.description != null) {
            builder.withDescription(request.description);
        }

        if (request.metadata != null) {
            builder.withMetadata(request.metadata);
        }

        secret = builder.create();
    } catch (DataAccessException e) {
        logger.info(format("Cannot create secret %s", request.name), e);
        throw new ConflictException(format("Cannot create secret %s.", request.name));
    }

    URI uri = UriBuilder.fromResource(SecretsResource.class).path("{secretId}").build(secret.getId());
    Response response = Response.created(uri).entity(secretDetailResponseFromId(secret.getId())).build();

    if (response.getStatus() == HttpStatus.SC_CREATED) {
        Map<String, String> extraInfo = new HashMap<>();
        if (request.description != null) {
            extraInfo.put("description", request.description);
        }
        if (request.metadata != null) {
            extraInfo.put("metadata", request.metadata.toString());
        }
        extraInfo.put("expiry", Long.toString(request.expiry));
        auditLog.recordEvent(
                new Event(Instant.now(), EventTag.SECRET_CREATE, user.getName(), request.name, extraInfo));
    }
    // TODO (jessep): Should we also log failures?

    return response;
}

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

@Test
public void testDeleteImageAsync() throws IOException, InterruptedException {
    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);

    ImagesApi imagesApi = new ImagesRestApi(this.restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    imagesApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*  ww  w  .  j  a  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.netflix.genie.web.services.impl.HttpFileTransferImplTest.java

/**
 * Make sure can get the last update time of a file.
 *
 * @throws GenieException On error// ww  w.j a  v  a2 s.  c om
 */
@Test
public void canGetLastModifiedTimeIfNoHeader() throws GenieException {
    final long time = Instant.now().toEpochMilli() - 1;
    this.server.expect(MockRestRequestMatchers.requestTo(TEST_URL))
            .andExpect(MockRestRequestMatchers.method(HttpMethod.HEAD))
            .andRespond(MockRestResponseCreators.withSuccess());
    Assert.assertTrue(this.httpFileTransfer.getLastModifiedTime(TEST_URL) > time);
    Mockito.verify(this.metadataTimerId, Mockito.times(1)).withTags(MetricsUtils.newSuccessTagsMap());
    Mockito.verify(this.metadataTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:sx.blah.discord.handle.impl.obj.Channel.java

@Override
public MessageHistory getMessageHistoryTo(long id, int maxCount) {
    return getMessageHistoryIn(DiscordUtils.getSnowflakeFromTimestamp(Instant.now()), id, maxCount);
}

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

/**
 * Creates the tag./*from   ww w.  j av  a2  s.  c o m*/
 * @param _groupId The id of the group that should contain the new tag.
 * @param _entity Data needed for creation.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postTag(@PathParam("groupid") int _groupId, TagInfo _entity) throws Exception {
    if (_entity.getUUID() == null || (_entity.getName() != null && _entity.getName().length() == 0)
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toCreate;
    try {
        toCreate = UUID.fromString(_entity.getUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant created;
    if (_entity.getLastChanged() != null) {
        created = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(created))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        created = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITagController tagController = ControllerFactory.getTagController(manager);
    try {
        tagController.add(_groupId, toCreate, _entity.getName(), created);
    } catch (ConflictException _e) {
        return ResponseFactory
                .generateConflict(new Error().withMessage("The sent data would " + "conflict with saved tag."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:com.joyent.manta.client.multipart.JobsMultipartManagerIT.java

private void canUploadMultipartBinary(final long sizeInMb, final int noOfParts) throws IOException {
    final long size = sizeInMb * 1024L * 1024L;

    File[] parts = new File[noOfParts];

    for (int i = 0; i < noOfParts; i++) {
        parts[i] = createTemporaryDataFile(size, 1);
    }//from w  ww.j a v  a  2 s .c o m

    final File expectedFile = concatenateFiles(parts);
    final byte[] expectedMd5 = md5(expectedFile);

    final String name = uploadName("can-upload-5mb-multipart-binary");
    final String path = testPathPrefix + name;

    final JobsMultipartUpload upload = multipart.initiateUpload(path);

    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        File part = parts[i];
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    Instant start = Instant.now();
    multipart.complete(upload, uploadedParts.stream());
    multipart.waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
        fail("Completion operation didn't succeed within timeout");
        return null;
    });
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);
    assertEquals(status, MantaMultipartStatus.COMPLETED);

    MantaObjectResponse head = mantaClient.head(path);
    byte[] remoteMd5 = head.getMd5Bytes();

    if (!Arrays.equals(remoteMd5, expectedMd5)) {
        StringBuilder builder = new StringBuilder();
        builder.append("MD5 values do not match - job id: ").append(multipart.findJob(upload));
        fail(builder.toString());
    }

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Concatenating {} parts took {} seconds", parts.length, totalCompletionTime.toMillis() / 1000);
}

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

@Test
public void testPerformOperationAsync() throws IOException, InterruptedException {
    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);

    VmApi vmApi = new VmApi(restClient);

    VmOperation vmOperation = new VmOperation();
    vmOperation.setOperation(Operation.START_VM.name());

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.performOperationAsync("foo", vmOperation, new FutureCallback<Task>() {
        @Override// ww  w . j a  v a  2s  .c  om
        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.orange.cepheus.cep.SubscriptionManager.java

/**
 * Subscribe to a provider//from  ww  w  .j  a  va  2 s .c  o  m
 * @param provider
 * @param subscribeContext
 * @param subscriptions
 */
private void subscribeProvider(Provider provider, SubscribeContext subscribeContext,
        Subscriptions subscriptions) {
    logger.debug("Subscribe to {} for {}", provider.getUrl(), subscribeContext.toString());

    ngsiClient.subscribeContext(provider.getUrl(), null, subscribeContext)
            .addCallback(subscribeContextResponse -> {
                SubscribeError error = subscribeContextResponse.getSubscribeError();
                if (error == null) {
                    String subscriptionId = subscribeContextResponse.getSubscribeResponse().getSubscriptionId();

                    provider.setSubscriptionDate(Instant.now());
                    provider.setSubscriptionId(subscriptionId);
                    subscriptions.addSubscription(subscriptionId);

                    logger.debug("Subscription done for {}", provider.getUrl());
                } else {
                    logger.warn("Error during subscription for {}: {}", provider.getUrl(),
                            error.getErrorCode());
                }
            }, throwable -> {
                logger.warn("Error during subscription for {}:{}", provider.getUrl(), throwable.toString());
            });
}