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.ProjectApiTest.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);

    ProjectApi projectApi = new ProjectApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    projectApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override// w  w w . 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:com.vmware.photon.controller.api.client.resource.ProjectRestApiTest.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);

    ProjectApi projectApi = new ProjectRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    projectApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*from  www  .  j ava 2  s  .  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:org.noorganization.instalist.server.api.TaggedProductResourceTest.java

@Test
public void testPostTaggedProduct() throws Exception {
    String url = "/groups/%d/taggedproducts";
    TaggedProductInfo newTP = new TaggedProductInfo().withUUID(mTaggedProduct.getUUID())
            .withProductUUID(mProduct.getUUID()).withTagUUID(mNATag.getUUID());
    Instant preInsert = Instant.now();

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

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

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

    newTP.setUUID(UUID.randomUUID());
    Response wrongRefResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newTP));
    assertEquals(400, wrongRefResponse.getStatus());

    newTP.setTagUUID(mTag.getUUID());//www .j  ava  2s. c o m
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newTP));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<TaggedProduct> savedTaggedProductQuery = mManager.createQuery(
            "select tp from " + "TaggedProduct tp where tp.group = :group and tp.UUID = :uuid",
            TaggedProduct.class);
    savedTaggedProductQuery.setParameter("group", mGroup);
    savedTaggedProductQuery.setParameter("uuid", UUID.fromString(newTP.getUUID()));
    List<TaggedProduct> savedIngredients = savedTaggedProductQuery.getResultList();
    assertEquals(1, savedIngredients.size());
    assertTrue(preInsert.isBefore(savedIngredients.get(0).getUpdated()));
}

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

/**
 * Creates the recipe.//from   w  w  w.  j  av  a2  s  .com
 * @param _groupId The id of the group that should contain the new recipe.
 * @param _entity Data to change.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postRecipe(@PathParam("groupid") int _groupId, RecipeInfo _entity) throws Exception {
    try {

        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();
        IRecipeController recipeController = ControllerFactory.getRecipeController(manager);
        try {
            recipeController.add(_groupId, toCreate, _entity.getName(), created);
        } catch (ConflictException _e) {
            return ResponseFactory.generateConflict(
                    new Error().withMessage("The sent data would " + "conflict with saved recipe."));
        } finally {
            manager.close();
        }

        return ResponseFactory.generateCreated(null);
    } catch (Exception _e) {
        _e.printStackTrace();
        throw _e;
    }
}

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

/**
 * Creates the unit.//from  w w  w.j  a v  a 2 s.c  o  m
 * @param _groupId The group-id the new Unit should belong to.
 * @param _entity Data of the new unit.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postUnit(@PathParam("groupid") int _groupId, UnitInfo _entity) throws Exception {
    if (_entity.getUUID() == null || (_entity.getDeleted() != null && _entity.getDeleted())
            || _entity.getName() == null || _entity.getName().length() == 0)
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toInsert;
    try {
        toInsert = UUID.fromString(_entity.getUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    Instant insertDate;
    if (_entity.getLastChanged() == null)
        insertDate = Instant.now();
    else {
        insertDate = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(insertDate))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IUnitController unitController = ControllerFactory.getUnitController(manager);
    try {
        unitController.add(_groupId, toInsert, _entity.getName(), insertDate);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "lead to a conflict with saved unit."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:io.dropwizard.revolver.resource.RevolverMailboxResource.java

@Path("/v1/message/persist")
@POST// ww w.  j  a va 2s.com
@Metered
@ApiOperation(value = "Persist a request in the mailbox")
@Produces({ MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK, MediaType.APPLICATION_XML,
        MediaType.TEXT_HTML })
public Response persistRequest(@Context final HttpHeaders headers, @Context final UriInfo uriInfo,
        final byte[] body) {
    val requestId = headers.getHeaderString(RevolversHttpHeaders.REQUEST_ID_HEADER);
    val mailBoxId = headers.getHeaderString(RevolversHttpHeaders.MAILBOX_ID_HEADER);
    persistenceProvider.saveRequest(requestId, mailBoxId,
            RevolverCallbackRequest.builder().api("persist").mode("POLLING").callbackUri(null).method("POST")
                    .service("mailbox").path(uriInfo.getPath()).headers(headers.getRequestHeaders())
                    .queryParams(uriInfo.getQueryParameters()).body(body).build());
    return Response.accepted().entity(
            RevolverAckMessage.builder().requestId(requestId).acceptedAt(Instant.now().toEpochMilli()).build())
            .build();
}

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

    final CountDownLatch latch = new CountDownLatch(1);

    tenantsApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override// w ww  . 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.noorganization.instalist.server.api.IngredientResourceTest.java

@Test
public void testPostIngredient() throws Exception {
    String url = "/groups/%d/ingredients";
    IngredientInfo newIngred = new IngredientInfo().withUUID(mIngredient.getUUID())
            .withProductUUID(mProduct.getUUID()).withRecipeUUID(mRecipe.getUUID()).withAmount(3f);
    Instant preInsert = Instant.now();

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

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

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

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newIngred));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mIngredient);/*from w  w  w  .  ja v a  2s  .  c o m*/
    assertEquals(1f, mIngredient.getAmount(), 0.001f);

    newIngred.setUUID(UUID.randomUUID());
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newIngred));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<Ingredient> savedIngredientQuery = mManager.createQuery(
            "select i from " + "Ingredient i where i.group = :group and i.UUID = :uuid", Ingredient.class);
    savedIngredientQuery.setParameter("group", mGroup);
    savedIngredientQuery.setParameter("uuid", UUID.fromString(newIngred.getUUID()));
    List<Ingredient> savedIngredients = savedIngredientQuery.getResultList();
    assertEquals(1, savedIngredients.size());
    assertEquals(3f, savedIngredients.get(0).getAmount(), 0.001f);
    assertTrue(preInsert.isBefore(savedIngredients.get(0).getUpdated()));
}

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

@Test
public void testPostEntry() throws Exception {
    String url = "/groups/%d/listentries";
    EntryInfo newProduct = new EntryInfo().withUUID(mEntry.getUUID()).withProductUUID(mProduct.getUUID())
            .withListUUID(mList.getUUID()).withAmount(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(mEntry);//from   ww  w .  j a  v  a 2s . c o  m
    assertEquals(1f, mEntry.getAmount(), 0.001f);

    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<ListEntry> savedEntriesQuery = mManager.createQuery(
            "select le from " + "ListEntry le where le.group = :group and le.UUID = :uuid", ListEntry.class);
    savedEntriesQuery.setParameter("group", mGroup);
    savedEntriesQuery.setParameter("uuid", UUID.fromString(newProduct.getUUID()));
    List<ListEntry> savedEntries = savedEntriesQuery.getResultList();
    assertEquals(1, savedEntries.size());
    assertEquals(3f, savedEntries.get(0).getAmount(), 0.001f);
    assertTrue(preInsert.isBefore(savedEntries.get(0).getUpdated()));
}