Example usage for java.time Instant ofEpochSecond

List of usage examples for java.time Instant ofEpochSecond

Introduction

In this page you can find the example usage for java.time Instant ofEpochSecond.

Prototype

public static Instant ofEpochSecond(long epochSecond) 

Source Link

Document

Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z.

Usage

From source file:org.openmhealth.shim.jawbone.mapper.JawboneDataPointMapper.java

/**
 * @param builder a {@link Measure} builder
 * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response
 *//*from   w w  w .  ja  v  a 2 s .co m*/
protected void setEffectiveTimeFrame(T.Builder builder, JsonNode listEntryNode) {

    Optional<Long> optionalStartTime = asOptionalLong(listEntryNode, "time_created");
    Optional<Long> optionalEndTime = asOptionalLong(listEntryNode, "time_completed");

    if (optionalStartTime.isPresent() && optionalStartTime.get() != null && optionalEndTime.isPresent()
            && optionalEndTime.get() != null) {

        ZoneId timeZoneForStartTime = getTimeZoneForTimestamp(listEntryNode, optionalStartTime.get());
        ZoneId timeZoneForEndTime = getTimeZoneForTimestamp(listEntryNode, optionalEndTime.get());

        OffsetDateTime startTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(optionalStartTime.get()),
                timeZoneForStartTime);
        OffsetDateTime endTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(optionalEndTime.get()),
                timeZoneForEndTime);

        builder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndEndDateTime(startTime, endTime));
    } else if (optionalStartTime.isPresent() && optionalStartTime.get() != null) {

        ZoneId timeZoneForStartTime = getTimeZoneForTimestamp(listEntryNode, optionalStartTime.get());
        builder.setEffectiveTimeFrame(
                OffsetDateTime.ofInstant(Instant.ofEpochSecond(optionalStartTime.get()), timeZoneForStartTime));
    }
}

From source file:org.createnet.raptor.models.data.RecordSet.java

private void parseJson(Stream stream, JsonNode row) {

    JsonNode channels = row;/*from   ww w.  j a va 2s. c  om*/
    if (row.has("channels")) {

        if (row.has("timestamp")) {
            Date date = Date.from(Instant.ofEpochSecond(row.get("timestamp").asLong()));
            this.setTimestamp(date);
        } else if (row.has("lastUpdate")) {
            Date date = Date.from(Instant.ofEpochSecond(row.get("lastUpdate").asLong()));
            this.setTimestamp(date);
        }

        channels = row.get("channels");
    }

    for (Iterator<Map.Entry<String, JsonNode>> iterator = channels.fields(); iterator.hasNext();) {

        Map.Entry<String, JsonNode> item = iterator.next();

        String channelName = item.getKey();
        JsonNode nodeValue = item.getValue();

        JsonNode valObj = nodeValue;

        // allow short-hand without [current-]value
        if (nodeValue.isObject()) {
            if (nodeValue.has("value")) {
                valObj = nodeValue.get("value");
            } else if (nodeValue.has("current-value")) {
                valObj = nodeValue.get("current-value");
            }
        }

        try {
            if (stream != null && (stream.channels != null && !stream.channels.isEmpty())) {
                if (stream.channels.containsKey(channelName)) {
                    this.addRecord(stream, channelName, valObj);
                }
            } else {
                // definition is unknown, add all channels to the record set
                this.addRecord(stream, channelName, valObj);
            }
        } catch (Exception e) {
            throw new RecordsetException(e);
        }

    }

}

From source file:org.eclipse.smarthome.binding.openweathermap.internal.handler.AbstractOpenWeatherMapHandler.java

protected State getDateTimeTypeState(@Nullable Integer value) {
    return (value == null) ? UnDefType.UNDEF
            : new DateTimeType(
                    ZonedDateTime.ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault()));
}

From source file:io.syndesis.rest.v1.state.ClientSideState.java

<T> TimestampedState<T> restoreWithTimestamp(final Cookie cookie, final Class<T> type) {
    final String value = cookie.getValue();

    final String[] parts = value.split("\\|", 5);

    final byte[] atime = DECODER.decode(parts[1]);

    final long atimeLong = atime(atime);

    if (atimeLong + timeout < timeSource.getAsLong()) {
        throw new IllegalArgumentException("Given value has timed out at: " + Instant.ofEpochSecond(atimeLong));
    }//from  ww w .  j a v  a 2  s.com

    final byte[] tid = DECODER.decode(parts[2]);
    if (!MessageDigest.isEqual(tid, edition.tid)) {
        throw new IllegalArgumentException(String.format("Given TID `%s`, mismatches current TID `%s`",
                new BigInteger(tid).toString(16), new BigInteger(edition.tid).toString(16)));
    }

    final KeySource keySource = edition.keySource();
    final int lastSeparatorIdx = value.lastIndexOf('|');
    final byte[] mac = DECODER.decode(parts[4]);
    final byte[] calculated = mac(edition.authenticationAlgorithm, value.substring(0, lastSeparatorIdx),
            keySource.authenticationKey());
    if (!MessageDigest.isEqual(mac, calculated)) {
        throw new IllegalArgumentException("Cookie value fails authenticity check");
    }

    final byte[] iv = DECODER.decode(parts[3]);
    final byte[] encrypted = DECODER.decode(parts[0]);
    final byte[] clear = decrypt(edition.encryptionAlgorithm, iv, encrypted, keySource.encryptionKey());

    @SuppressWarnings("unchecked")
    final T ret = (T) deserialization.apply(type, clear);

    return new TimestampedState<>(ret, atimeLong);
}

From source file:io.jwt.primer.resource.TokenResource.java

@POST
@Path("/v1/verify/{app}/{id}")
@ApiOperation(value = "Verify the token for a given user")
@ApiResponses({ @ApiResponse(code = 200, response = VerifyResponse.class, message = "Success"),
        @ApiResponse(code = 401, response = PrimerError.class, message = "Unauthorized"),
        @ApiResponse(code = 404, response = PrimerError.class, message = "Not Found"),
        @ApiResponse(code = 403, response = PrimerError.class, message = "Forbidden"),
        @ApiResponse(code = 412, response = PrimerError.class, message = "Expired"),
        @ApiResponse(code = 500, response = PrimerError.class, message = "Error") })
@Metered//from   ww  w. jav  a  2  s .  c o  m
public VerifyResponse verify(@HeaderParam("X-Auth-Token") String token, @PathParam("app") String app,
        @PathParam("id") String id, @Valid ServiceUser user) throws PrimerException {
    try {
        DynamicToken dynamicToken = PrimerCommands.getDynamic(aerospikeConfig, app, id);
        if (dynamicToken == null)
            throw new PrimerException(Response.Status.NOT_FOUND.getStatusCode(), "PR001", "Not Found");
        if (!dynamicToken.isEnabled()) {
            throw new PrimerException(Response.Status.FORBIDDEN.getStatusCode(), "PR002", "Forbidden");
        }
        final long adjusted = Instant.ofEpochSecond(dynamicToken.getExpiresAt().getTime())
                .plusSeconds(jwtConfig.getClockSkew()).getEpochSecond();
        final long now = Instant.now().getEpochSecond();
        if (adjusted <= now) {
            throw new PrimerException(Response.Status.PRECONDITION_FAILED.getStatusCode(), "PR003", "Expired");
        }
        if (token.equals(dynamicToken.getToken()) && user.getId().equals(dynamicToken.getSubject())
                && user.getName().equals(dynamicToken.getName())
                && user.getRole().equals(dynamicToken.getRole())) {
            return VerifyResponse.builder().expiresAt(dynamicToken.getExpiresAt().getTime())
                    .token(dynamicToken.getToken()).userId(dynamicToken.getSubject()).build();
        } else {
            throw new PrimerException(Response.Status.UNAUTHORIZED.getStatusCode(), "PR004", "Unauthorized");
        }
    } catch (Exception e) {
        PrimerExceptionUtil.handleException(e);
        log.error("Execution Error verifying token", e);
        throw new PrimerException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "PR001", "Error");
    }
}

From source file:net.morimekta.idltool.IdlUtils.java

public static String formatAgo(long timestamp) {
    Instant instant = Instant.ofEpochSecond(timestamp / 1000);
    LocalDateTime local = instant.atZone(Clock.systemUTC().getZone())
            .withZoneSameInstant(Clock.systemDefaultZone().getZone()).toLocalDateTime();
    return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(local).replaceAll("[T]", " ");
}

From source file:com.yahoo.egads.models.tsmm.OlympicModel2.java

@Override
public void train(final DataSequence data) throws Exception {
    initializeIndices(data, modelStartEpoch);

    final long size = data.size();
    ZonedDateTime model_ts = Instant.ofEpochSecond(modelStartEpoch).atZone(zone);
    ZonedDateTime end_ts = model_ts.plus(windowSize, windowUnits);
    int prediction_index = 0;
    final List<WeightedValue> accumulator = Lists.newArrayList();

    // start the loop and break once we've filled the model.
    while (true) {
        accumulator.clear();/*from  w w w  . j  a v a  2s  . com*/
        for (int i = 0; i < windowTimes.length; i++) {
            if (indices[i] < 0 || indices[i] >= size) {
                continue;
            }

            // advance
            windowTimes[i] = windowTimes[i].plus(interval, intervalUnits);
            long interval_end = windowTimes[i].toEpochSecond();
            final List<Double> doubles = Lists.newArrayList();
            long first_ts = -1;
            while (indices[i] < size && data.get(indices[i]).time < interval_end) {
                if (Double.isFinite(data.get(indices[i]).value)) {
                    doubles.add((double) data.get(indices[i]).value);
                }
                if (first_ts < 0) {
                    first_ts = data.get(indices[i]).time;
                }
                indices[i]++;
            }

            if (!doubles.isEmpty()) {
                // TODO - for DST if we jumped back then we may have a
                // period
                // with more than we expect. In that case, depending on the
                // aggregator, we may need to use only part of the data.
                // TODO - potentially other aggregations.
                double sum = 0;
                for (final Double v : doubles) {
                    sum += v;
                }
                accumulator.add(new WeightedValue((sum / doubles.size()), i + 1));
            }
        }

        if (drop_lowest > 0 || drop_highest > 0) {
            if (drop_highest > drop_lowest) {
                WeightedValue.drop(accumulator, drop_highest, true);
                WeightedValue.drop(accumulator, drop_lowest, false);
            } else {
                WeightedValue.drop(accumulator, drop_lowest, false);
                WeightedValue.drop(accumulator, drop_highest, true);
            }
        }

        model.add(new Pair<Long, Double>(model_ts.toEpochSecond(),
                WeightedValue.aggregate(accumulator, windowAggregator)));

        model_ts = model_ts.plus(interval, intervalUnits);
        if (model_ts.toEpochSecond() > end_ts.toEpochSecond()) {
            prediction_index++;
            if (prediction_index >= futureWindows) {
                break;
            }
            model_ts = Instant.ofEpochSecond(modelStartEpoch).atZone(zone);
            model_ts = model_ts.plus((windowDistanceInterval * prediction_index), windowDistanceIntervalUnits);
            end_ts = model_ts.plus(windowSize, windowUnits);
            for (int i = 0; i < windowTimes.length; i++) {
                windowTimes[i] = null;
                indices[i] = 0;
            }
            initializeIndices(data, model_ts.toEpochSecond());
        }
    }
}

From source file:com.bdb.weather.display.summary.HighLowMedianTempPanel.java

@Override
public void chartMouseClicked(ChartMouseEventFX event) {
    ChartEntity entity = event.getEntity();
    ///*from w w  w  .j  av  a  2s.  c o m*/
    // Was a point on the plot selected?
    //
    if (entity instanceof XYItemEntity) {
        XYItemEntity itemEntity = (XYItemEntity) entity;
        XYDataset dataset = itemEntity.getDataset();
        Number x = dataset.getXValue(itemEntity.getSeriesIndex(), itemEntity.getItem());

        //ZoneId id = ZoneId.of(ZoneId.systemDefault().getId());
        //ZoneOffset offset = ZoneOffset.of(ZoneId.systemDefault().getId());
        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochSecond(x.longValue() / 1000),
                ZoneId.systemDefault());

        boolean doubleClick = event.getTrigger().getClickCount() == 2;
        if (doubleClick)
            supporter.launchView(viewLauncher, time.toLocalDate());
    }
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

private LocalDateTime epochToLocalDateTime(final long TIMESTAMP) {
    return LocalDateTime.ofInstant(Instant.ofEpochSecond(TIMESTAMP), ZoneId.of(timeZone.getID()));
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

private LocalDateTime epochStringToLocalDateTime(final String TIME_STRING) {
    return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(TIME_STRING)),
            ZoneId.of(timeZone.getID()));
}