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:keywhiz.service.resources.admin.SecretsResource.java

/**
 * Create or update secret//from   www .  ja  va 2s. c  o  m
 *
 * @excludeParams user
 * @param request the JSON client request used to formulate the Secret
 *
 * @responseMessage 200 Successfully created Secret
 */
@Path("{name}")
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createOrUpdateSecret(@Auth User user, @PathParam("name") String secretName,
        @Valid CreateOrUpdateSecretRequestV2 request) {

    logger.info("User '{}' createOrUpdate secret '{}'.", user, secretName);

    Secret secret = secretController.builder(secretName, request.content(), user.getName(), request.expiry())
            .withDescription(request.description()).withMetadata(request.metadata()).withType(request.type())
            .createOrUpdate();

    URI uri = UriBuilder.fromResource(SecretsResource.class).path(secretName).build();

    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 && !request.description().isEmpty()) {
            extraInfo.put("description", request.description());
        }
        if (request.metadata() != null && !request.metadata().isEmpty()) {
            extraInfo.put("metadata", request.metadata().toString());
        }
        extraInfo.put("expiry", Long.toString(request.expiry()));
        auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATEORUPDATE, user.getName(),
                secretName, extraInfo));
    }
    return response;
}

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

/**
 * Creates the listEntry./*from   w  w  w.ja v  a  2 s  .com*/
 * @param _groupId The id of the group containing the entry.
 * @param _entity Data for created the entry.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postEntry(@PathParam("groupid") int _groupId, EntryInfo _entity) throws Exception {
    if (_entity.getUUID() == null || _entity.getListUUID() == null || _entity.getProductUUID() == null
            || (_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getAmount() != null && _entity.getAmount() < 0.001f))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toCreate;
    UUID productUUID;
    UUID listUUID;
    try {
        toCreate = UUID.fromString(_entity.getUUID());
        productUUID = UUID.fromString(_entity.getProductUUID());
        listUUID = UUID.fromString(_entity.getListUUID());
    } 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 amount = (_entity.getAmount() != null ? _entity.getAmount() : 1f);
    int priority = (_entity.getPriority() != null ? _entity.getPriority() : 0);
    boolean struck = (_entity.getStruck() != null ? _entity.getStruck() : false);

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IEntryController entryController = ControllerFactory.getEntryController(manager);
    try {
        entryController.add(_groupId, toCreate, productUUID, listUUID, amount, priority, struck, created);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved list entry."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(
                new Error().withMessage("The referenced " + "product or list was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

private void verify(final String authenticationId, final JsonObject user, final String authorizationId,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    JsonObject effectiveUser = user;/*from   www. jav  a 2 s . co m*/
    String effectiveAuthorizationId = authenticationId;
    if (authorizationId != null && !authorizationId.isEmpty() && isAuthorizedToImpersonate(user)) {
        final JsonObject impersonatedUser = users.get(authorizationId);
        if (impersonatedUser != null) {
            effectiveUser = impersonatedUser;
            effectiveAuthorizationId = authorizationId;
            log.debug("granting authorization id specified by client");
        } else {
            log.debug(
                    "no user found for authorization id provided by client, granting authentication id instead");
        }
    }
    final Authorities grantedAuthorities = getAuthorities(effectiveUser);
    final String grantedAuthorizationId = effectiveAuthorizationId;
    final Instant tokenExpirationTime = Instant.now().plus(tokenFactory.getTokenLifetime());
    final String token = tokenFactory.createToken(grantedAuthorizationId, grantedAuthorities);
    final HonoUser honoUser = new HonoUser() {

        @Override
        public String getName() {
            return grantedAuthorizationId;
        }

        @Override
        public String getToken() {
            return token;
        }

        @Override
        public Authorities getAuthorities() {
            return grantedAuthorities;
        }

        @Override
        public boolean isExpired() {
            return !Instant.now().isBefore(tokenExpirationTime);
        }

        @Override
        public Instant getExpirationTime() {
            return tokenExpirationTime;
        }
    };
    authenticationResultHandler.handle(Future.succeededFuture(honoUser));
}

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

/**
 * Creates the ingredient.//from   w  ww.jav a2 s .  c om
 * @param _groupId The id of the group that will contain the ingredient.
 * @param _entity Data for the created ingredient.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postIngredient(@PathParam("groupid") int _groupId, IngredientInfo _entity) throws Exception {
    if (_entity.getUUID() == null || _entity.getRecipeUUID() == null || _entity.getProductUUID() == null
            || (_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getAmount() != null && _entity.getAmount() < 0.001f))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toCreate;
    UUID productUUID;
    UUID recipeUUID;
    try {
        toCreate = UUID.fromString(_entity.getUUID());
        productUUID = UUID.fromString(_entity.getProductUUID());
        recipeUUID = UUID.fromString(_entity.getRecipeUUID());
    } 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 amount = (_entity.getAmount() != null ? _entity.getAmount() : 1f);

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IIngredientController ingredientController = ControllerFactory.getIngredientController(manager);
    try {
        ingredientController.add(_groupId, toCreate, recipeUUID, productUUID, amount, created);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved ingredient."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(
                new Error().withMessage("The referenced " + "recipe or product was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

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

@Test
public void testCreatePersistentDiskAsync() 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.createDiskAsync("foo", new DiskCreateSpec(), new FutureCallback<Task>() {
        @Override//from  w ww  .ja va 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:io.specto.hoverfly.junit.core.Hoverfly.java

/**
 * Blocks until the Hoverfly process becomes healthy, otherwise time out
 *///from  w w  w  .ja  v a2s .  c o m
private void waitForHoverflyToBecomeHealthy() {
    final Instant now = Instant.now();

    while (Duration.between(now, Instant.now()).getSeconds() < BOOT_TIMEOUT_SECONDS) {
        if (hoverflyClient.getHealth())
            return;
        try {
            // TODO: prefer executors and tasks to threads
            Thread.sleep(RETRY_BACKOFF_INTERVAL_MS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    throw new IllegalStateException("Hoverfly has not become healthy in " + BOOT_TIMEOUT_SECONDS + " seconds");
}

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

/**
 * Creates the category./*from  ww  w.  j a va2  s  .c  o  m*/
 * @param _groupId The group to add the category to.
 * @param _entity Information for the new category.
 *      e.g. examples/category.example
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postCategory(@PathParam("groupid") int _groupId, CategoryInfo _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);
    Instant lastChanged;
    if (_entity.getLastChanged() != null) {
        lastChanged = _entity.getLastChanged().toInstant();
        if (lastChanged.isAfter(Instant.now()))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        lastChanged = Instant.now();

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

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ICategoryController categoryController = ControllerFactory.getCategoryController(manager);
    try {
        categoryController.add(_groupId, newCatUUID, _entity.getName(), lastChanged);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The new category " + "stands in conflict with existing one."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

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

@Test
public void testCreatePersistentDiskAsync() 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.createDiskAsync("foo", new DiskCreateSpec(), new FutureCallback<Task>() {
        @Override/*  w w  w.j av  a  2  s . 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:org.ulyssis.ipp.reader.Reader.java

public void messageReceived(LLRPMessage msg) {
    if (msg.getTypeNum() == RO_ACCESS_REPORT.TYPENUM) {
        RO_ACCESS_REPORT report = (RO_ACCESS_REPORT) msg;
        List<TagReportData> tags = report.getTagReportDataList();
        for (TagReportData tagReportData : tags) {
            // NOTE: We're using Instant.now() instead of relying on the timestamp
            //          of the update. The delay should be small, and we'll keep the
            //         counting systems in sync using NTP.
            Instant now = Instant.now();
            TagId tag = LLRPReader.decodeEPCParameter(tagReportData.getEPCParameter());
            if (acceptUpdate(now, tag)) {
                pushUpdate(now, tag);//from  www  . j  a v a  2s.  co  m
            }
        }
    }
}

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

public void canAbortMultipartBinary() throws IOException {
    final long oneMB = 1024L * 1024L;

    File[] parts = new File[] { createTemporaryDataFile(oneMB, 1), createTemporaryDataFile(oneMB, 1),
            createTemporaryDataFile(oneMB, 1) };

    final String name = uploadName("can-abort-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];//from   w  w  w.  j  a  va  2s  .c o  m
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    multipart.complete(upload, uploadedParts);

    Instant start = Instant.now();
    multipart.abort(upload);

    boolean caught = false;

    try {
        multipart.waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
            fail("Completion operation didn't succeed within timeout");
            return null;
        });
    } catch (MantaMultipartException e) {
        if (e.getMessage().startsWith("Manta job backing multipart upload was "
                + "aborted. This upload was unable to be completed.")) {
            caught = true;
        }
    }

    assertTrue(caught, "Backing job aborted exception wasn't thrown");
    Instant end = Instant.now();

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

    MantaJob job = multipart.findJob(upload);

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

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

    if (!job.getCancelled()) {
        fail("Job wasn't cancelled:" + job.toString());
    }

    assertFalse(mantaClient.existsAndIsAccessible(multipart.multipartUploadDir(upload.getId())),
            "Upload directory shouldn't be present after abort");
}