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

/**
 * Updates an tagged product. This REST-Endpoint is currently not really useful as
 * TaggedProduct only contain links between Products and Tags and no additional information. It
 * was created as reservation for future use.
 * @param _groupId The id of the group containing the tagged product.
 * @param _taggedProductUUID The uuid of the tagged product itself.
 * @param _entity Data for updating the tagged product.
 *//*from w w  w.j a  v a  2s  .c om*/
@PUT
@TokenSecured
@Path("{tpuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putTaggedProduct(@PathParam("groupid") int _groupId,
        @PathParam("tpuuid") String _taggedProductUUID, TaggedProductInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_taggedProductUUID))
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    UUID productUUID = null;
    UUID tagUUID = null;
    try {
        toUpdate = UUID.fromString(_taggedProductUUID);
        if (_entity.getProductUUID() != null)
            productUUID = UUID.fromString(_entity.getProductUUID());
        if (_entity.getTagUUID() != null)
            tagUUID = UUID.fromString(_entity.getTagUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITaggedProductController taggedProductController = ControllerFactory.getTaggedProductController(manager);
    try {
        taggedProductController.update(_groupId, toUpdate, tagUUID, productUUID, updated);
    } catch (NotFoundException _e) {
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The tagged product " + "was not found."));
    } catch (GoneException _e) {
        return ResponseFactory
                .generateGone(new Error().withMessage("The tagged product has " + "been deleted."));
    } 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 " + "product or tag was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:com.vmware.photon.controller.api.client.resource.ProjectApiTest.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);

    ProjectApi projectApi = new ProjectApi(restClient);

    Task task = projectApi.delete("foo");
    assertEquals(task, responseTask);//from w  w  w  .j a  va  2  s.  c  o  m
}

From source file:com.vmware.photon.controller.api.client.resource.ProjectRestApiTest.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);

    ProjectApi projectApi = new ProjectRestApi(restClient);

    Task task = projectApi.delete("foo");
    assertEquals(task, responseTask);/*from  w w  w .j a  va2s . c o  m*/
}

From source file:com.netflix.genie.web.tasks.job.JobMonitorTest.java

/**
 * Make sure that a timed out process sends event.
 * @throws Exception in case of error/* w  w w  .j a va 2  s . c  o  m*/
 */
@Test
public void canTryToKillTimedOutProcess() throws Exception {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);

    // Set timeout to yesterday to force timeout when check happens
    final Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
    this.jobExecution = new JobExecution.Builder(UUID.randomUUID().toString()).withProcessId(3808)
            .withCheckDelay(DELAY).withTimeout(yesterday).withId(UUID.randomUUID().toString()).build();
    this.monitor = new JobMonitor(this.jobExecution, this.stdOut, this.stdErr, this.genieEventBus,
            this.registry, JobsProperties.getJobsPropertiesDefaults(), processChecker);

    Mockito.doThrow(new GenieTimeoutException("...")).when(processChecker).checkProcess();

    this.monitor.run();

    final ArgumentCaptor<KillJobEvent> captor = ArgumentCaptor.forClass(KillJobEvent.class);
    Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(captor.capture());

    Assert.assertNotNull(captor.getValue());
    final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
    Assert.assertThat(captor.getValue().getId(), Matchers.is(jobId));
    Assert.assertThat(captor.getValue().getReason(), Matchers.is(JobStatusMessages.JOB_EXCEEDED_TIMEOUT));
    Assert.assertThat(captor.getValue().getSource(), Matchers.is(this.monitor));
    Mockito.verify(this.timeoutRate, Mockito.times(1)).increment();
}

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

/**
 * Updates the product./*w w  w . jav  a 2 s .  c  o m*/
 * @param _groupId The group containing the product to update.
 * @param _productUUID The uuid of the product to update.
 * @param _entity The data for changing the product.
 *      e.g. examples/product.example
 */
@PUT
@TokenSecured
@Path("{productuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putProduct(@PathParam("groupid") int _groupId, @PathParam("productuuid") String _productUUID,
        ProductInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_productUUID))
            || (_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 toUpdate;
    UUID unitUUID = null;
    boolean removeUnit = (_entity.getRemoveUnit() != null ? _entity.getRemoveUnit() : false);
    try {
        toUpdate = UUID.fromString(_productUUID);
        if (_entity.getUnitUUID() != null && !removeUnit)
            unitUUID = UUID.fromString(_entity.getUnitUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IProductController productController = ControllerFactory.getProductController(manager);
    try {
        productController.update(_groupId, toUpdate, _entity.getName(), _entity.getDefaultAmount(),
                _entity.getStepAmount(), unitUUID, removeUnit, updated);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The product was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The product has been " + "deleted."));
    } 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.generateOK(null);
}

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

/**
 * Updates the category./*from  w  w  w.j a  v a2s  . com*/
 * @param _uuid The uuid of the category to update.
 * @param _entity A category with updated information.
 */
@PUT
@TokenSecured
@Path("{categoryuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _uuid,
        CategoryInfo _entity) throws Exception {
    if (_entity.getName() == null)
        return ResponseFactory.generateBadRequest(CommonEntity.NO_DATA_RECVD);
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_uuid))
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    Instant changedDate = Instant.now();
    if (_entity.getLastChanged() != null) {
        changedDate = _entity.getLastChanged().toInstant();
        if (changedDate.isAfter(Instant.now()))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    UUID categoryUUID;
    try {
        categoryUUID = UUID.fromString(_uuid);
    } catch (IllegalArgumentException e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ICategoryController categoryController = ControllerFactory.getCategoryController(manager);
    try {
        categoryController.update(_groupId, categoryUUID, _entity.getName(), changedDate);
    } catch (NotFoundException e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("Category was not " + "found."));
    } catch (GoneException e) {
        return ResponseFactory.generateGone(new Error().withMessage("Category was already " + "deleted."));
    } catch (ConflictException e) {
        return ResponseFactory
                .generateConflict(new Error().withMessage("Sent sategory is in " + "conflict with saved one."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:com.vmware.photon.controller.api.client.resource.VmApiTest.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);

    VmApi vmApi = new VmApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/* w  w w  .j av  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.VmRestApiTest.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);

    VmApi vmApi = new VmRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//from  w  w  w .ja v  a  2 s. com
        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:org.ulyssis.ipp.reader.Reader.java

private void simulateOneTeam(ReaderConfig.SimulatedTeam team) {
    Instant instant = Instant.now();
    TagId tag = team.getTag();/*w  w  w  . j  av a2  s  .  c o  m*/
    if (acceptUpdate(instant, tag)) {
        pushUpdate(instant, tag);
    }
    Runnable runnable = () -> simulateOneTeam(team);
    executorService.schedule(runnable, team.getLapTime(), TimeUnit.SECONDS);
}

From source file:com.vmware.photon.controller.api.client.resource.TenantsApiTest.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 TenantsApi(restClient);

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