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 testDeleteAsync() 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);

    TenantsApi tenantsApi = new TenantsRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    tenantsApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//from  w w  w  .  j a  v a 2s. c  o 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.vmware.photon.controller.api.client.resource.VmApiTest.java

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

    VmApi vmApi = new VmApi(restClient);

    Task task = vmApi.addTagToVm("foo", new Tag("tagValue"));
    assertEquals(task, responseTask);//from   www  . j  a va  2s  .co  m
}

From source file:com.joyent.manta.client.multipart.EncryptedJobsMultipartManagerIT.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  w w  .j av a  2s .  c  om

    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 EncryptedMultipartUpload<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.getWrapped().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);

    // If we are using encryption the remote md5 is the md5 of the
    // cipher text.  To prove we uploaded the right bytes and can
    // get them back again, we need to download and calculate.

    final byte[] remoteMd5;
    try (MantaObjectInputStream gotObject = mantaClient.getAsInputStream(path)) {
        remoteMd5 = DigestUtils.md5(gotObject);
    }

    if (!Arrays.equals(remoteMd5, expectedMd5)) {
        StringBuilder builder = new StringBuilder();
        builder.append("MD5 values do not match - job id: ").append(multipart.getWrapped().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.api.client.resource.VmRestApiTest.java

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

    VmApi vmApi = new VmRestApi(restClient);

    Task task = vmApi.addTagToVm("foo", new Tag("tagValue"));
    assertEquals(task, responseTask);//from  ww  w  .  ja v  a2  s  .  co  m
}

From source file:org.ng200.openolympus.ContestTest.java

public Contest createContestDirectly(Duration duration) throws Exception {
    return this.contestService.saveContest(new Contest(Date.from(Instant.now()), duration,
            "TestContest_" + ContestTest.id++, new HashSet<Task>(), false));
}

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

@Test
public void testPostProduct() throws Exception {
    String url = "/groups/%d/products";
    ProductInfo newProduct = new ProductInfo().withUUID(mProduct.getUUID()).withName("product4")
            .withDefaultAmount(1.0f).withStepAmount(0.3f);
    Instant preInsert = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request()
            .post(Entity.json(newProduct));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").post(Entity.json(newProduct));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newProduct));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newProduct));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mProduct);// w  w  w  .j  a va 2 s  .  co  m
    assertEquals("product1", mProduct.getName());

    newProduct.setUUID(UUID.randomUUID());
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newProduct));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<Product> savedProductsQuery = mManager.createQuery(
            "select p from " + "Product p where p.group = :group and p.UUID = :uuid", Product.class);
    savedProductsQuery.setParameter("group", mGroup);
    savedProductsQuery.setParameter("uuid", UUID.fromString(newProduct.getUUID()));
    List<Product> savedProducts = savedProductsQuery.getResultList();
    assertEquals(1, savedProducts.size());
    assertEquals("product4", savedProducts.get(0).getName());
    assertTrue(preInsert.isBefore(savedProducts.get(0).getUpdated()));
}

From source file:com.spotify.apollo.elide.ElideResourceTest.java

private Response<ByteString> invokeRoute(Request request) throws Exception {
    List<Route<AsyncHandler<Response<ByteString>>>> routes = resource.routes()
            .filter(r -> r.method().equals(request.method())).collect(toList());

    assertThat(routes.size(), is(1));/* w  w w.java 2 s.co m*/

    return routes.get(0).handler().invoke(RequestContexts.create(request, client, pathArgs(request.uri()), 0,
            RequestMetadataImpl.create(Instant.now(), empty(), empty()))).toCompletableFuture().get();
}

From source file:ai.susi.server.AbstractAPIHandler.java

/**
 * Create or fetch an anonymous identity
 * @return the anonymous ClientIdentity//from   www. j ava 2  s. c  om
 */
private static ClientIdentity getAnonymousIdentity(String remoteHost) {
    ClientCredential credential = new ClientCredential(ClientCredential.Type.host, remoteHost);
    Authentication authentication = new Authentication(credential, DAO.authentication);

    if (authentication.getIdentity() == null)
        authentication.setIdentity(new ClientIdentity(credential.toString()));
    authentication.setExpireTime(Instant.now().getEpochSecond() + defaultAnonymousTime);

    return authentication.getIdentity();
}

From source file:com.netflix.genie.web.controllers.DtoConverters.java

/**
 * Convert a V3 Command to a V4 Command.
 *
 * @param v3Command The V3 Command to convert
 * @return The V4 representation of the supplied command
 *///from w  ww .j ava2s.  c  om
public static Command toV4Command(final com.netflix.genie.common.dto.Command v3Command) {
    final CommandMetadata.Builder metadataBuilder = new CommandMetadata.Builder(v3Command.getName(),
            v3Command.getUser(), v3Command.getVersion(), v3Command.getStatus())
                    .withTags(toV4Tags(v3Command.getTags()));

    v3Command.getDescription().ifPresent(metadataBuilder::withDescription);
    v3Command.getMetadata().ifPresent(metadataBuilder::withMetadata);

    final ExecutionEnvironment resources = new ExecutionEnvironment(v3Command.getConfigs(),
            v3Command.getDependencies(), v3Command.getSetupFile().orElse(null));

    return new Command(v3Command.getId().orElseThrow(IllegalArgumentException::new),
            v3Command.getCreated().orElse(Instant.now()), v3Command.getUpdated().orElse(Instant.now()),
            resources, metadataBuilder.build(),
            Lists.newArrayList(StringUtils.split(v3Command.getExecutable())),
            v3Command.getMemory().orElse(null), v3Command.getCheckDelay());
}

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

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

    ProjectApi projectApi = new ProjectApi(restClient);

    Task task = projectApi.createDisk("foo", new DiskCreateSpec());
    assertEquals(task, responseTask);/* w w  w  .  j  a va2  s.c o  m*/
}