Example usage for java.time ZonedDateTime ofInstant

List of usage examples for java.time ZonedDateTime ofInstant

Introduction

In this page you can find the example usage for java.time ZonedDateTime ofInstant.

Prototype

public static ZonedDateTime ofInstant(Instant instant, ZoneId zone) 

Source Link

Document

Obtains an instance of ZonedDateTime from an Instant .

Usage

From source file:org.lizardirc.beancounter.commands.earthquake.GeoJsonFeatureProperty.java

public ZonedDateTime getUpdatedTime() {
    return ZonedDateTime.ofInstant(Instant.ofEpochMilli(updated), ZoneId.systemDefault());
}

From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java

public static AWS4SignatureBuilder builder(final Date date, final String region, final String service) {
    return builder(ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()), region, service);
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static ZonedDateTime getZonedDateTime(final Timestamp timestamp) {
    return timestamp != null ? ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault()) : null;
}

From source file:sorcer.file.ScratchDirManager.java

private boolean isCutoffTime(Path path, long cutOffTime) throws IOException {
    ZonedDateTime now = ZonedDateTime.now();
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    ZonedDateTime created = ZonedDateTime.ofInstant(attrs.creationTime().toInstant(), now.getZone());

    created = created.withYear(now.getYear()).withMonth(now.getMonthValue());

    ZonedDateTime cutoff = created.plus(cutOffTime, MILLIS);

    log.info("Created {}", created);
    log.info("now     {}", now);
    log.info("cutoff  {}", cutoff);

    return now.isAfter(cutoff);
}

From source file:org.elasticsearch.multi_node.RollupIT.java

public void testBigRollup() throws Exception {
    final int numDocs = 200;
    String dateFormat = "strict_date_optional_time";

    // create the test-index index
    try (XContentBuilder builder = jsonBuilder()) {
        builder.startObject();/*from w  w  w .  ja v  a  2  s . c  o  m*/
        {
            builder.startObject("mappings").startObject("_doc").startObject("properties")
                    .startObject("timestamp").field("type", "date").field("format", dateFormat).endObject()
                    .startObject("value").field("type", "integer").endObject().endObject().endObject()
                    .endObject();
        }
        builder.endObject();
        final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
        Request req = new Request("PUT", "rollup-docs");
        req.setEntity(entity);
        client().performRequest(req);
    }

    // index documents for the rollup job
    final StringBuilder bulk = new StringBuilder();
    for (int i = 0; i < numDocs; i++) {
        bulk.append("{\"index\":{\"_index\":\"rollup-docs\",\"_type\":\"_doc\"}}\n");
        ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1531221196 + (60 * i)),
                ZoneId.of("UTC"));
        String date = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        bulk.append("{\"timestamp\":\"").append(date).append("\",\"value\":").append(i).append("}\n");
    }
    bulk.append("\r\n");

    final Request bulkRequest = new Request("POST", "/_bulk");
    bulkRequest.addParameter("refresh", "true");
    bulkRequest.setJsonEntity(bulk.toString());
    client().performRequest(bulkRequest);

    // create the rollup job
    final Request createRollupJobRequest = new Request("PUT", "/_xpack/rollup/job/rollup-job-test");
    int pageSize = randomIntBetween(2, 50);
    createRollupJobRequest.setJsonEntity("{" + "\"index_pattern\":\"rollup-*\","
            + "\"rollup_index\":\"results-rollup\"," + "\"cron\":\"*/1 * * * * ?\"," // fast cron so test runs quickly
            + "\"page_size\":" + pageSize + "," + "\"groups\":{" + "    \"date_histogram\":{"
            + "        \"field\":\"timestamp\"," + "        \"interval\":\"5m\"" + "      }" + "},"
            + "\"metrics\":[" + "    {\"field\":\"value\",\"metrics\":[\"min\",\"max\",\"sum\"]}" + "]" + "}");

    Map<String, Object> createRollupJobResponse = toMap(client().performRequest(createRollupJobRequest));
    assertThat(createRollupJobResponse.get("acknowledged"), equalTo(Boolean.TRUE));

    // start the rollup job
    final Request startRollupJobRequest = new Request("POST", "_xpack/rollup/job/rollup-job-test/_start");
    Map<String, Object> startRollupJobResponse = toMap(client().performRequest(startRollupJobRequest));
    assertThat(startRollupJobResponse.get("started"), equalTo(Boolean.TRUE));

    assertRollUpJob("rollup-job-test");

    // Wait for the job to finish, by watching how many rollup docs we've indexed
    assertBusy(() -> {
        final Request getRollupJobRequest = new Request("GET", "_xpack/rollup/job/rollup-job-test");
        Response getRollupJobResponse = client().performRequest(getRollupJobRequest);
        assertThat(getRollupJobResponse.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus()));

        Map<String, Object> job = getJob(getRollupJobResponse, "rollup-job-test");
        if (job != null) {
            assertThat(ObjectPath.eval("status.job_state", job), equalTo("started"));
            assertThat(ObjectPath.eval("stats.rollups_indexed", job), equalTo(41));
        }
    }, 30L, TimeUnit.SECONDS);

    // Refresh the rollup index to make sure all newly indexed docs are searchable
    final Request refreshRollupIndex = new Request("POST", "results-rollup/_refresh");
    toMap(client().performRequest(refreshRollupIndex));

    String jsonRequestBody = "{\n" + "  \"size\": 0,\n" + "  \"query\": {\n" + "    \"match_all\": {}\n"
            + "  },\n" + "  \"aggs\": {\n" + "    \"date_histo\": {\n" + "      \"date_histogram\": {\n"
            + "        \"field\": \"timestamp\",\n" + "        \"interval\": \"1h\",\n"
            + "        \"format\": \"date_time\"\n" + "      },\n" + "      \"aggs\": {\n"
            + "        \"the_max\": {\n" + "          \"max\": {\n" + "            \"field\": \"value\"\n"
            + "          }\n" + "        }\n" + "      }\n" + "    }\n" + "  }\n" + "}";

    Request request = new Request("GET", "rollup-docs/_search");
    request.setJsonEntity(jsonRequestBody);
    Response liveResponse = client().performRequest(request);
    Map<String, Object> liveBody = toMap(liveResponse);

    request = new Request("GET", "results-rollup/_rollup_search");
    request.setJsonEntity(jsonRequestBody);
    Response rollupResponse = client().performRequest(request);
    Map<String, Object> rollupBody = toMap(rollupResponse);

    // Do the live agg results match the rollup agg results?
    assertThat(ObjectPath.eval("aggregations.date_histo.buckets", liveBody),
            equalTo(ObjectPath.eval("aggregations.date_histo.buckets", rollupBody)));

    request = new Request("GET", "rollup-docs/_rollup_search");
    request.setJsonEntity(jsonRequestBody);
    Response liveRollupResponse = client().performRequest(request);
    Map<String, Object> liveRollupBody = toMap(liveRollupResponse);

    // Does searching the live index via rollup_search work match the live search?
    assertThat(ObjectPath.eval("aggregations.date_histo.buckets", liveBody),
            equalTo(ObjectPath.eval("aggregations.date_histo.buckets", liveRollupBody)));

}

From source file:org.haiku.haikudepotserver.job.controller.JobController.java

/**
 * <p>This is helper-code that can be used to check to see if the data is stale and
 * will then enqueue the job, run it and then redirect the user to the data
 * download.</p>//  ww  w.java  2  s . c o m
 * @param response is the HTTP response to send the redirect to.
 * @param ifModifiedSinceHeader is the inbound header from the client.
 * @param lastModifyTimestamp is the actual last modified date for the data.
 * @param jobSpecification is the job that would be run if the data is newer than in the
 *                         inbound header.
 */

public static void handleRedirectToJobData(HttpServletResponse response, JobService jobService,
        String ifModifiedSinceHeader, Date lastModifyTimestamp, JobSpecification jobSpecification)
        throws IOException {

    if (!Strings.isNullOrEmpty(ifModifiedSinceHeader)) {
        try {
            Date requestModifyTimestamp = new Date(Instant
                    .from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(ifModifiedSinceHeader)).toEpochMilli());

            if (requestModifyTimestamp.getTime() >= lastModifyTimestamp.getTime()) {
                response.setStatus(HttpStatus.NOT_MODIFIED.value());
                return;
            }
        } catch (DateTimeParseException dtpe) {
            LOGGER.warn("bad [{}] header on request; [{}] -- will ignore", HttpHeaders.IF_MODIFIED_SINCE,
                    StringUtils.abbreviate(ifModifiedSinceHeader, 128));
        }
    }

    // what happens here is that we get the report and if it is too old, delete it and try again.

    JobSnapshot jobSnapshot = getJobSnapshotStartedAfter(jobService, lastModifyTimestamp, jobSpecification);
    Set<String> jobDataGuids = jobSnapshot.getDataGuids();

    if (1 != jobDataGuids.size()) {
        throw new IllegalStateException("found [" + jobDataGuids.size()
                + "] job data guids related to the job [" + jobSnapshot.getGuid() + "] - was expecting 1");
    }

    String lastModifiedValue = DateTimeFormatter.RFC_1123_DATE_TIME
            .format(ZonedDateTime.ofInstant(lastModifyTimestamp.toInstant(), ZoneOffset.UTC));
    String destinationLocationUrl = UriComponentsBuilder.newInstance()
            .pathSegment(AuthenticationFilter.SEGMENT_SECURED).pathSegment(JobController.SEGMENT_JOBDATA)
            .pathSegment(jobDataGuids.iterator().next()).pathSegment(JobController.SEGMENT_DOWNLOAD)
            .toUriString();

    response.addHeader(HttpHeaders.LAST_MODIFIED, lastModifiedValue);
    response.sendRedirect(destinationLocationUrl);
}

From source file:org.openhab.binding.nest.handler.NestBaseHandler.java

protected State getAsDateTimeTypeOrNull(@Nullable Date date) {
    if (date == null) {
        return UnDefType.NULL;
    }/*  ww w.  j a  v a  2s .  c om*/

    long offsetMillis = TimeZone.getDefault().getOffset(date.getTime());
    Instant instant = date.toInstant().plusMillis(offsetMillis);
    return new DateTimeType(ZonedDateTime.ofInstant(instant, TimeZone.getDefault().toZoneId()));
}

From source file:io.werval.modules.jose.JwtPluginTest.java

@Test
public void http() throws InterruptedException {
    String tokenHeaderName = WERVAL.application().config().string(JWT.HTTP_HEADER_CONFIG_KEY);
    JWT jwt = WERVAL.application().plugin(JWT.class);

    // Unauthorized access to authenticated resource
    when().get("/authenticated").then().statusCode(UNAUTHORIZED_CODE);

    // Login/*from ww w. j a v a2 s . c  o  m*/
    String token = given().body("{\"email\":\"admin@example.com\",\"password\":\"admin-password\"}")
            .contentType(APPLICATION_JSON).when().post("/login").then().statusCode(OK_CODE)
            .header(tokenHeaderName, notNullValue()).log().all().extract().header(tokenHeaderName);

    // Authenticated access
    given().header(tokenHeaderName, token).when().get("/authenticated").then().statusCode(OK_CODE);

    // Authorized access
    given().header(tokenHeaderName, token).when().get("/authorized").then().statusCode(OK_CODE);

    // Gather time related claims from token
    ZoneId utc = ZoneId.of("UTC");
    Map<String, Object> claims = jwt.claimsOfToken(token);
    ZonedDateTime iat = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_ISSUED_AT)),
            utc);
    ZonedDateTime nbf = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_NOT_BEFORE)),
            utc);
    ZonedDateTime exp = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_EXPIRATION)),
            utc);

    // Wait at least one second before renewal so new dates will be different
    Thread.sleep(1200);

    // Renew token
    String renewed = given().header(tokenHeaderName, token).when().post("/renew").then().statusCode(OK_CODE)
            .header(tokenHeaderName, notNullValue()).log().all().extract().header(tokenHeaderName);

    // Gather time related claims from renewed token
    claims = jwt.claimsOfToken(renewed);
    ZonedDateTime renewedIat = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_ISSUED_AT)), utc);
    ZonedDateTime renewedNbf = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_NOT_BEFORE)), utc);
    ZonedDateTime renewedExp = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_EXPIRATION)), utc);

    // Assert renewed token time related claims are greater than the ones in the original token
    assertTrue(renewedIat.isAfter(iat));
    assertTrue(renewedNbf.isAfter(nbf));
    assertTrue(renewedExp.isAfter(exp));
}

From source file:lumbermill.internal.aws.AWSV4SignerImpl.java

public AWSV4SignerImpl(AWSCredentialsProvider credentialsProvider, String region, String service) {
    this.credentialsProvider = credentialsProvider;
    this.region = region;
    this.service = service;
    clock = () -> ZonedDateTime.ofInstant(ZonedDateTime.now().toInstant(), ZoneId.of("UTC")).toLocalDateTime();
}

From source file:io.stallion.utils.GeneralUtils.java

@Deprecated
public static ZonedDateTime milsToDateTime(long mils) {
    return ZonedDateTime.ofInstant(Instant.ofEpochMilli(mils), UTC);
}