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

/**
 * Creates the tagged product./* w  ww.  j a va  2 s .c  o  m*/
 * @param _groupId The id of the group that will contain the tagged product.
 * @param _entity Data for the created tagged product.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postTaggedProduct(@PathParam("groupid") int _groupId, TaggedProductInfo _entity)
        throws Exception {
    if (_entity.getUUID() == null || _entity.getTagUUID() == null || _entity.getProductUUID() == null
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toCreate;
    UUID productUUID;
    UUID tagUUID;
    try {
        toCreate = UUID.fromString(_entity.getUUID());
        productUUID = UUID.fromString(_entity.getProductUUID());
        tagUUID = UUID.fromString(_entity.getTagUUID());
    } 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();
    ITaggedProductController taggedProductController = ControllerFactory.getTaggedProductController(manager);
    try {
        taggedProductController.add(_groupId, toCreate, tagUUID, productUUID, created);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved tagged product."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(
                new Error().withMessage("The referenced " + "recipe or tag was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

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

@Override
public List<IMessage> bulkDelete() {
    return bulkDelete(getMessageHistoryTo(Instant.now().minus(Period.ofWeeks(2))));
}

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

@Test
public void testCreateResourceTicketAsync() 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 TenantsApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    tenantsApi.createResourceTicketAsync("foo", new ResourceTicketCreateSpec(), new FutureCallback<Task>() {
        @Override//w  w w  . ja  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.TenantsRestApiTest.java

@Test
public void testCreateResourceTicketAsync() 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.createResourceTicketAsync("foo", new ResourceTicketCreateSpec(), new FutureCallback<Task>() {
        @Override/*from  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.spinnaker.igor.travis.TravisBuildMonitor.java

private List<Repo> filterOutOldBuilds(List<Repo> repos) {
    /*/*from w  w w. j  av  a2  s.c om*/
    BUILD_STARTED_AT_THRESHOLD is here because the builds can be picked up by igor before lastBuildStartedAt is
    set. This means the TTL can be set in the BuildCache before lastBuildStartedAt, if that happens we need a
    grace threshold so that we don't resend the event to echo. The value of the threshold assumes that travis
    will set the lastBuildStartedAt within 30 seconds.
    */
    final Instant threshold = Instant.now().minus(travisProperties.getCachedJobTTLDays(), ChronoUnit.DAYS)
            .plusMillis(BUILD_STARTED_AT_THRESHOLD);
    return repos.stream().filter(
            repo -> repo.getLastBuildStartedAt() != null && repo.getLastBuildStartedAt().isAfter(threshold))
            .collect(Collectors.toList());
}

From source file:com.netflix.genie.common.dto.JobRequestTest.java

/**
 * Test to make sure can build a valid JobRequest with optional parameters.
 *//*from   w  w  w  .ja  v  a  2s  .  c o m*/
@Test
public void canBuildJobRequestWithOptionals() {
    final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, CLUSTER_CRITERIAS,
            COMMAND_CRITERIA);

    builder.withCommandArgs(COMMAND_ARGS);

    final int cpu = 5;
    builder.withCpu(cpu);

    final boolean disableLogArchival = true;
    builder.withDisableLogArchival(disableLogArchival);

    final String email = UUID.randomUUID().toString() + "@netflix.com";
    builder.withEmail(email);

    final Set<String> configs = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withConfigs(configs);

    final Set<String> dependencies = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withDependencies(dependencies);

    final String group = UUID.randomUUID().toString();
    builder.withGroup(group);

    final int memory = 2048;
    builder.withMemory(memory);

    final String setupFile = UUID.randomUUID().toString();
    builder.withSetupFile(setupFile);

    final Instant created = Instant.now();
    builder.withCreated(created);

    final String description = UUID.randomUUID().toString();
    builder.withDescription(description);

    final String id = UUID.randomUUID().toString();
    builder.withId(id);

    final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withTags(tags);

    final Instant updated = Instant.now();
    builder.withUpdated(updated);

    final List<String> applications = Lists.newArrayList(UUID.randomUUID().toString(),
            UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
    builder.withApplications(applications);

    final int timeout = 8970243;
    builder.withTimeout(timeout);

    final String grouping = UUID.randomUUID().toString();
    builder.withGrouping(grouping);

    final String groupingInstance = UUID.randomUUID().toString();
    builder.withGroupingInstance(groupingInstance);

    final JobRequest request = builder.build();
    Assert.assertThat(request.getName(), Matchers.is(NAME));
    Assert.assertThat(request.getUser(), Matchers.is(USER));
    Assert.assertThat(request.getVersion(), Matchers.is(VERSION));
    Assert.assertThat(request.getCommandArgs().orElseThrow(IllegalArgumentException::new),
            Matchers.is(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)));
    Assert.assertThat(request.getClusterCriterias(), Matchers.is(CLUSTER_CRITERIAS));
    Assert.assertThat(request.getCommandCriteria(), Matchers.is(COMMAND_CRITERIA));
    Assert.assertThat(request.getCpu().orElseThrow(IllegalArgumentException::new), Matchers.is(cpu));
    Assert.assertThat(request.isDisableLogArchival(), Matchers.is(disableLogArchival));
    Assert.assertThat(request.getEmail().orElseThrow(IllegalArgumentException::new), Matchers.is(email));
    Assert.assertThat(request.getConfigs(), Matchers.is(configs));
    Assert.assertThat(request.getDependencies(), Matchers.is(dependencies));
    Assert.assertThat(request.getGroup().orElseThrow(IllegalArgumentException::new), Matchers.is(group));
    Assert.assertThat(request.getMemory().orElseThrow(IllegalArgumentException::new), Matchers.is(memory));
    Assert.assertThat(request.getSetupFile().orElseThrow(IllegalArgumentException::new),
            Matchers.is(setupFile));
    Assert.assertThat(request.getCreated().orElseThrow(IllegalArgumentException::new), Matchers.is(created));
    Assert.assertThat(request.getDescription().orElseThrow(IllegalArgumentException::new),
            Matchers.is(description));
    Assert.assertThat(request.getId().orElseThrow(IllegalArgumentException::new), Matchers.is(id));
    Assert.assertThat(request.getTags(), Matchers.is(tags));
    Assert.assertThat(request.getUpdated().orElseThrow(IllegalArgumentException::new), Matchers.is(updated));
    Assert.assertThat(request.getApplications(), Matchers.is(applications));
    Assert.assertThat(request.getTimeout().orElseThrow(IllegalArgumentException::new), Matchers.is(timeout));
    Assert.assertThat(request.getGrouping().orElseThrow(IllegalArgumentException::new), Matchers.is(grouping));
    Assert.assertThat(request.getGroupingInstance().orElseThrow(IllegalArgumentException::new),
            Matchers.is(groupingInstance));
}

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

@Test
public void testPerformStartOperation() 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.performStartOperation("foo");
    assertEquals(task, responseTask);//from  w w  w  .ja  v  a2s  . c  om
}

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

@Test
public void testPerformStartOperation() 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.performStartOperation("foo");
    assertEquals(task, responseTask);/*from w  w  w  . j ava2  s .c om*/
}

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

/**
 * Creates a product.//www .  j a  v  a 2s.  co m
 * @param _groupId The id of the group that should contain the new product.
 * @param _entity Data for creating the group.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postProduct(@PathParam("groupid") int _groupId, ProductInfo _entity) throws Exception {
    if (_entity.getUUID() == null || (_entity.getName() != null && _entity.getName().length() == 0)
            || (_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getDefaultAmount() != null && _entity.getDefaultAmount() < 0.001f)
            || (_entity.getStepAmount() != null && _entity.getStepAmount() < 0.001f))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toCreate;
    UUID unitUUID = null;
    boolean removeUnit = (_entity.getRemoveUnit() != null ? _entity.getRemoveUnit() : false);
    try {
        toCreate = UUID.fromString(_entity.getUUID());
        if (_entity.getUnitUUID() != null && !removeUnit)
            unitUUID = UUID.fromString(_entity.getUnitUUID());
    } 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();
    float defaultAmount = (_entity.getDefaultAmount() != null ? _entity.getDefaultAmount() : 1f);
    float stepAmount = (_entity.getStepAmount() != null ? _entity.getStepAmount() : 1f);

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IProductController productController = ControllerFactory.getProductController(manager);
    try {
        productController.add(_groupId, toCreate, _entity.getName(), defaultAmount, stepAmount, unitUUID,
                created);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved product."));
    } catch (BadRequestException _e) {
        return ResponseFactory
                .generateBadRequest(new Error().withMessage("The referenced " + "unit was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Measures the total time to get an object from Manta.
 *
 * @param path path of the object to measure
 * @return two durations - full time in the JVM, server time processing
 * @throws IOException thrown when we can't access Manta over the network
 *//*from   ww  w .j a  v a  2 s . c  om*/
private static Duration[] measureGet(final String path) throws IOException {
    final Instant start = Instant.now();
    final String serverLatencyString;
    MantaObjectInputStream is = client.getAsInputStream(path);

    try {
        copyToTheEther(is);
        serverLatencyString = is.getHeader("x-response-time").toString();
    } finally {
        IOUtils.closeQuietly(is);
    }
    final Instant stop = Instant.now();

    Duration serverLatency = Duration.ofMillis(Long.parseLong(serverLatencyString));
    Duration fullLatency = Duration.between(start, stop);
    return new Duration[] { fullLatency, serverLatency };
}