Example usage for java.time ZonedDateTime toEpochSecond

List of usage examples for java.time ZonedDateTime toEpochSecond

Introduction

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

Prototype

default long toEpochSecond() 

Source Link

Document

Converts this date-time to the number of seconds from the epoch of 1970-01-01T00:00:00Z.

Usage

From source file:com.splicemachine.orc.OrcTester.java

private static Object preprocessWriteValueOld(TypeInfo typeInfo, Object value) throws IOException {
    if (value == null) {
        return null;
    }//from   w ww. j  av a 2 s . com
    switch (typeInfo.getCategory()) {
    case PRIMITIVE:
        PrimitiveObjectInspector.PrimitiveCategory primitiveCategory = ((PrimitiveTypeInfo) typeInfo)
                .getPrimitiveCategory();
        switch (primitiveCategory) {
        case BOOLEAN:
            return value;
        case BYTE:
            return ((Number) value).byteValue();
        case SHORT:
            return ((Number) value).shortValue();
        case INT:
            return ((Number) value).intValue();
        case LONG:
            return ((Number) value).longValue();
        case FLOAT:
            return ((Number) value).floatValue();
        case DOUBLE:
            return ((Number) value).doubleValue();
        case DECIMAL:
            return HiveDecimal.create(((Decimal) value).toBigDecimal().bigDecimal());
        case STRING:
            return value;
        case CHAR:
            return new HiveChar(value.toString(), ((CharTypeInfo) typeInfo).getLength());
        case DATE:
            LocalDate localDate = LocalDate.ofEpochDay((int) value);
            ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

            long millis = zonedDateTime.toEpochSecond() * 1000;
            Date date = new Date(0);
            // mills must be set separately to avoid masking
            date.setTime(millis);
            return date;
        case TIMESTAMP:
            long millisUtc = ((Long) value).intValue();
            return new Timestamp(millisUtc);
        case BINARY:
            return ((String) value).getBytes();
        //                        return (byte[])value;
        }
        break;
    case MAP:
        MapTypeInfo mapTypeInfo = (MapTypeInfo) typeInfo;
        TypeInfo keyTypeInfo = mapTypeInfo.getMapKeyTypeInfo();
        TypeInfo valueTypeInfo = mapTypeInfo.getMapValueTypeInfo();
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueOld(keyTypeInfo, entry.getKey()),
                    preprocessWriteValueOld(valueTypeInfo, entry.getValue()));
        }
        return newMap;
    case LIST:
        ListTypeInfo listTypeInfo = (ListTypeInfo) typeInfo;
        TypeInfo elementTypeInfo = listTypeInfo.getListElementTypeInfo();
        List<Object> newList = new ArrayList<>(((Collection<?>) value).size());
        for (Object element : (Iterable<?>) value) {
            newList.add(preprocessWriteValueOld(elementTypeInfo, element));
        }
        return newList;
    case STRUCT:
        StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;
        List<?> fieldValues = (List<?>) value;
        List<TypeInfo> fieldTypeInfos = structTypeInfo.getAllStructFieldTypeInfos();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueOld(fieldTypeInfos.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IOException(format("Unsupported Hive type: %s", typeInfo));
}

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

/**
 * Sets the index into the DataSequence object for each window along with
 * calculating the window times. The index or timestamp for each window will
 * be one of the following: - -1 to show that there isn't any data for that
 * window - An index where the timestamp is the exact value of the seek time
 * - An index where the timestamp is a value greater than the seek time
 * // w w w  . j  a  va 2  s.  co  m
 * @param data
 *            A non-null and non-empty data sequence object to read from.
 * @throws IllegalArgumentException
 *             if the data object was null or empty.
 */
@VisibleForTesting
void initializeIndices(final DataSequence data, final long start) {
    if (data == null || data.size() < 1) {
        throw new IllegalArgumentException("DataSequence cannot be null or empty.");
    }
    final ZonedDateTime base = Instant.ofEpochSecond(start).atZone(zone);

    for (int i = 0; i < pastWindows; i++) {
        final ZonedDateTime seek = base.minus((windowDistanceInterval * (pastWindows - i)),
                windowDistanceIntervalUnits);
        final long seek_time = seek.toEpochSecond();

        // cut down on iterations by dividing the data idx
        int idx = data.size() / (pastWindows - i);
        if (idx >= data.size()) {
            idx = data.size() - 1;
        }

        if (data.get(idx).time == seek_time) {
            // woot, found it!
        } else if (data.get(idx).time < seek_time) {
            while (idx < data.size() && data.get(idx).time < seek_time) {
                idx++;
            }
        } else {
            while (idx > 0 && data.get(idx - 1).time >= seek_time) {
                idx--;
            }
        }

        // reset to avoid OOB exceptions.
        if (idx >= data.size()) {
            idx = -1;
        }
        windowTimes[i] = seek;
        indices[i] = idx;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Initializing index: " + i + " to " + idx + " at " + seek);
        }
    }
}

From source file:com.netflix.spinnaker.front50.model.SwiftStorageService.java

@Override
public long getLastModified(ObjectType objectType) {
    List<? extends SwiftObject> objects = getSwift().objects().list(containerName,
            ObjectListOptions.create().path(objectType.group));
    ZonedDateTime lastModified = Instant.now().atZone(ZoneOffset.UTC);
    for (SwiftObject o : objects) {
        ZonedDateTime timestamp = ZonedDateTime.parse(
                getSwift().objects().getMetadata(containerName, o.getName()).get("Last-Modified"),
                DateTimeFormatter.RFC_1123_DATE_TIME);
        if (timestamp.isBefore(lastModified)) {
            lastModified = timestamp;/*from ww w  .j  a v  a 2s . c  o m*/
        }
    }
    return lastModified.toEpochSecond();
}

From source file:de.loercher.localpress.integration.GeoAndRatingITest.java

@Test
public void testAddArticle() {
    String nowString = "2015-10-12T08:00+02:00[Europe/Berlin]";
    ZonedDateTime now = new DateTimeConverter().fromString(nowString);

    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(nowString);
    Instant instant = now.toInstant();
    Instant fir = Instant.now();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("UserID", "ulf");

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, headers);

    RestTemplate template = new RestTemplate();
    ResponseEntity<Map> result = template.postForEntity("http://52.29.77.191:8080/localpress/feedback", request,
            Map.class);

    Instant afterRating = Instant.now();

    GeoBaseEntity.EntityBuilder builder = new GeoBaseEntity.EntityBuilder();
    GeoBaseEntity entity = builder.author("ulf")
            .coordinates(Arrays.asList(new Coordinate[] { new Coordinate(50.1, 8.4) }))
            .timestamp(now.toEpochSecond()).content("abc.de").title("mein titel").user("ulf").build();

    HttpEntity<GeoBaseEntity> second = new HttpEntity<>(entity, headers);
    System.out.println(result.getBody().get("articleID"));

    template.put("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"), second);

    Instant afterGeoPut = Instant.now();

    result = template.getForEntity("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"),
            Map.class);

    Instant afterGeoGet = Instant.now();

    assertEquals("User ID has changed over time!", "ulf", result.getBody().get("user"));
    assertEquals("Content URL has changed over time!", "abc.de", result.getBody().get("content"));

    DateTimeConverter conv = new DateTimeConverter();

    Duration first = Duration.between(fir, afterRating);
    Duration sec = Duration.between(afterRating, afterGeoPut);
    Duration third = Duration.between(afterGeoPut, afterGeoGet);

    System.out.println("Begin: " + conv.toString(now));
    System.out.println("Time until POST to rating: " + new Double(first.toMillis()) / 1000);
    System.out.println("Time until PUT to geo: " + new Double(sec.toMillis()) / 1000);
    System.out.println("Time until GET to geo: " + new Double(third.toMillis()) / 1000);
}

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();/* w ww  .j a  va 2 s  . c  o  m*/
        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:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java

/**
 * Schedules or reschedules a job for the channel with the given id if the given timestamp is in the future.
 *
 * @param channelId id of the channel//from  w w w. j  a  v  a 2 s. c  om
 * @param dateTime timestamp of the job represented as {@link ZonedDateTime}
 */
@SuppressWarnings("null")
private synchronized void scheduleJob(String channelId, ZonedDateTime dateTime) {
    long delay = dateTime.toEpochSecond() - ZonedDateTime.now().toEpochSecond();
    if (delay > 0) {
        Job job = JOBS.get(channelId);
        if (job == null || job.getFuture().isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Schedule job for '{}' in {} s (at '{}').", channelId, delay,
                        dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
            JOBS.put(channelId, new Job(channelId, delay));
        } else {
            if (delay != job.getDelay()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reschedule job for '{}' in {} s (at '{}').", channelId, delay,
                            dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                job.getFuture().cancel(true);
                JOBS.put(channelId, new Job(channelId, delay));
            }
        }
    }
}