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

/**
 * Update a subset of the fields of an existing secret
 *
 * @excludeParams user/*from w  w  w .j  av  a2s  .c  o m*/
 * @param request the JSON client request used to formulate the Secret
 *
 * @responseMessage 200 Successfully updated Secret
 */
@Path("{name}/partialupdate")
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response partialUpdateSecret(@Auth User user, @PathParam("name") String secretName,
        @Valid PartialUpdateSecretRequestV2 request) {

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

    long id = secretDAOReadWrite.partialUpdateSecret(secretName, user.getName(), request);

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

    Response response = Response.created(uri).entity(secretDetailResponseFromId(id)).build();

    if (response.getStatus() == HttpStatus.SC_CREATED) {
        Map<String, String> extraInfo = new HashMap<>();
        if (request.descriptionPresent()) {
            extraInfo.put("description", request.description());
        }
        if (request.metadataPresent()) {
            extraInfo.put("metadata", request.metadata().toString());
        }
        if (request.expiryPresent()) {
            extraInfo.put("expiry", Long.toString(request.expiry()));
        }
        auditLog.recordEvent(
                new Event(Instant.now(), EventTag.SECRET_UPDATE, user.getName(), secretName, extraInfo));
    }
    return response;
}

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

public Task createDummyTask() {
    Task task = new Task();
    task.setDescriptionFile(null);// w  w  w .  ja  v  a2s . c om
    task.setPublished(true);
    task.setTaskLocation(null);
    task.setTimeAdded(Date.from(Instant.now()));
    task = this.taskService.saveTask(task);
    return task;
}

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

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//from  w w  w  . j av a  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.vmware.photon.controller.api.client.resource.FlavorRestApiTest.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);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//  w  w  w .ja  v  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:dk.dbc.rawrepo.oai.OAIWorker.java

/**
 * Take an OAIIdentifier list and convert into a Record list, with the
 * content formattet as medataPrefix//from  w  ww  .  j  ava 2  s  . c  o  m
 *
 * @param collection     identifiers to fetch
 * @param metadataPrefix fetch to get content in
 * @return list of records
 */
private List<RecordType> fetchRecordContent(List<OAIIdentifier> collection, String metadataPrefix) {
    List<RecordFormatter.RecordWithContent> records = collection.stream()
            .map(id -> recordFormatter.fetch(id, metadataPrefix, allowedSets)).collect(Collectors.toList());
    log.debug("futures = " + records);
    try {
        Instant timeout = Instant.now().plus(config.getFetchRecordsTimeout(), ChronoUnit.SECONDS);
        List<RecordType> recordsWithContent = records.stream().map(rec -> {
            try {
                long waitFor = Math.max(0, Instant.now().until(timeout, ChronoUnit.SECONDS));
                log.debug("waitFor (sec) = " + waitFor);
                rec.complete(waitFor);
                RecordType record = rec.getOAIIdentifier().toRecord();
                if (!rec.getOAIIdentifier().isDeleted()) {
                    MetadataType metadata = OBJECT_FACTORY.createMetadataType();
                    String content = rec.getContent();
                    if (content == null) {
                        log.error("Cannot get content for: " + rec.getOAIIdentifier().getIdentifier());
                        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error");
                    }
                    Element element = stringToElement(content);
                    fixXmlNamespacePrefix(element, metadataPrefix);
                    metadata.setAny(element);
                    record.setMetadata(metadata);
                }
                return record;
            } catch (InterruptedException | ExecutionException ex) {
                log.error("Exception: " + ex.getMessage());
                log.debug("Exception: ", ex);
                throw new ServerErrorException(Response.Status.REQUEST_TIMEOUT, "Error retrieving record");
            } catch (TimeoutException ex) {
                log.error("Exception: " + ex.getMessage());
                log.debug("Exception: ", ex);
                throw new ServerErrorException(Response.Status.REQUEST_TIMEOUT,
                        "Error waiting for record formatting");
            }
        }).collect(Collectors.toList());
        return recordsWithContent;
    } catch (Exception e) {
        records.stream().forEach(record -> {
            try {
                record.cancel(true);
            } catch (Exception ex) {
                log.debug("Error canceling request: " + ex.getMessage());
            }
        });
        throw e;
    }
}

From source file:org.usrz.libs.webtools.resources.ServeResource.java

private Response produce(String path) throws Exception {

    /* Basic check for null/empty path */
    if ((path == null) || (path.length() == 0))
        return NOT_FOUND;

    /* Get our resource file, potentially a ".less" file for CSS */
    Resource resource = manager.getResource(path);
    if ((resource == null) && path.endsWith(".css")) {
        path = path.substring(0, path.length() - 4) + ".less";
        resource = manager.getResource(path);
    }/* www  .  j  av  a  2 s .  c o m*/

    /* If the root is incorrect, log this, if not found, 404 it! */
    if (resource == null)
        return NOT_FOUND;

    /* Ok, we have a resource on disk, this can be potentially long ... */
    final String fileName = resource.getFile().getName();

    /* Check and validated our cache */
    Entry cached = cache.computeIfPresent(resource, (r, entry) -> entry.resource.hasChanged() ? null : entry);

    /* If we have no cache, we *might* want to cache something */
    if (cached == null) {

        /* What to do, what to do? */
        if ((fileName.endsWith(".css") && minify) || fileName.endsWith(".less")) {

            /* Lessify CSS and cache */
            xlog.debug("Lessifying resource \"%s\"", fileName);
            cached = new Entry(resource, lxess.convert(resource, minify), styleMediaType);

        } else if (fileName.endsWith(".js") && minify) {

            /* Uglify JavaScript and cache */
            xlog.debug("Uglifying resource \"%s\"", fileName);
            cached = new Entry(resource, uglify.convert(resource.readString(), minify, minify),
                    scriptMediaType);

        } else if (fileName.endsWith(".json")) {

            /* Strip comments and normalize JSON */
            xlog.debug("Normalizing JSON resource \"%s\"", fileName);

            /* All to do with Jackson */
            final Reader reader = resource.read();
            final StringWriter writer = new StringWriter();
            final JsonParser parser = json.createParser(reader);
            final JsonGenerator generator = json.createGenerator(writer);

            /* Not minifying? Means pretty printing! */
            if (!minify)
                generator.useDefaultPrettyPrinter();

            /* Get our schtuff through the pipeline */
            parser.nextToken();
            generator.copyCurrentStructure(parser);
            generator.flush();
            generator.close();
            reader.close();
            parser.close();

            /* Cached results... */
            cached = new Entry(resource, writer.toString(), jsonMediaType);

        }

        /* Do we have anything to cache? */
        if (cached != null) {
            xlog.debug("Caching resource \"%s\"", fileName);
            cache.put(resource, cached);
        }
    }

    /* Prepare our basic response from either cache or file */
    final ResponseBuilder response = Response.ok();
    if (cached != null) {

        /* Response from cache */
        xlog.trace("Serving cached resource \"%s\"", fileName);
        response.entity(cached.contents).lastModified(new Date(resource.lastModifiedAt())).type(cached.type);
    } else {

        /* Response from a file */
        xlog.trace("Serving file-based resource \"%s\"", fileName);

        /* If text/* or application/javascript, append encoding */
        MediaType type = MediaTypes.get(fileName);
        if (type.getType().equals("text") || scriptMediaType.isCompatible(type)) {
            type = type.withCharset(charsetName);
        }

        /* Our file is served! */
        response.entity(resource.getFile()).lastModified(new Date(resource.lastModifiedAt())).type(type);
    }

    /* Caching headers and build response */
    final Date expires = Date.from(Instant.now().plus(cacheDuration));
    return response.cacheControl(cacheControl).expires(expires).build();

}

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

@Test
public void testPerformStopOperation() 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.performStopOperation("foo");
    assertEquals(task, responseTask);/*from www .  j  a v  a2 s.  c  om*/
}

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

@Test
public void testPerformStopOperation() 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.performStopOperation("foo");
    assertEquals(task, responseTask);//from  w w  w . j  a  v a  2s .c  o m
}

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

@Test
public void testPutEntry() throws Exception {
    String url = "/groups/%d/listentries/%s";
    Instant preUpdate = mEntry.getUpdated();
    EntryInfo updatedEntry = new EntryInfo().withAmount(3f);

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId(), mEntry.getUUID().toString()))
            .request().put(Entity.json(updatedEntry));
    assertEquals(401, notAuthorizedResponse.getStatus());

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

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

    Response wrongListResponse = target(String.format(url, mGroup.getId(), mNAEntry.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedEntry));
    assertEquals(404, wrongListResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId(), mDeletedEntry.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedEntry));
    assertEquals(410, goneResponse.getStatus());
    mManager.refresh(mEntry);/*from   ww  w .ja v a  2 s  .  c  o  m*/
    assertEquals(1f, mEntry.getAmount(), 0.001f);

    updatedEntry.setLastChanged(new Date(preUpdate.toEpochMilli() - 10000));
    Response conflictResponse = target(String.format(url, mGroup.getId(), mEntry.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedEntry));
    assertEquals(409, conflictResponse.getStatus());
    mManager.refresh(mEntry);
    assertEquals(1f, mEntry.getAmount(), 0.001f);

    updatedEntry.setLastChanged(Date.from(Instant.now()));
    Response okResponse = target(String.format(url, mGroup.getId(), mEntry.getUUID().toString())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedEntry));
    assertEquals(200, okResponse.getStatus());
    mManager.refresh(mEntry);
    assertEquals(3f, mEntry.getAmount(), 0.001f);
    assertTrue(preUpdate + " is not before " + mEntry.getUpdated(), preUpdate.isBefore(mEntry.getUpdated()));
}