Example usage for java.time OffsetDateTime toEpochSecond

List of usage examples for java.time OffsetDateTime toEpochSecond

Introduction

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

Prototype

public 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:Main.java

public static void main(String[] args) {
    OffsetDateTime o = OffsetDateTime.MAX;

    System.out.println(o.toEpochSecond());
}

From source file:keywhiz.api.ApiDate.java

public static ApiDate parse(String s) {
    OffsetDateTime odt = OffsetDateTime.parse(s);
    return new ApiDate(odt.toEpochSecond());
}

From source file:org.openmhealth.shim.jawbone.JawboneShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final JawboneDataTypes jawboneDataType;
    try {/*w w w.j a  v a 2  s  . co  m*/
        jawboneDataType = JawboneDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    /*
    Jawbone defaults to returning a maximum of 10 entries per request (limit = 10 by default), so
    we override the default by specifying an arbitrarily large number as the limit.
     */
    long numToReturn = 100_000;

    OffsetDateTime today = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? today.minusDays(1)
            : shimDataRequest.getStartDateTime();
    long startTimeInEpochSecond = startDateTime.toEpochSecond();

    // We are inclusive of the last day, so we need to add an extra day since we are dealing with start of day,
    // and would miss the activities that occurred during the last day within going to midnight of that day
    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? today.plusDays(1)
            : shimDataRequest.getEndDateTime().plusDays(1);
    long endTimeInEpochSecond = endDateTime.toEpochSecond();

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .path(jawboneDataType.getEndPoint()).queryParam("start_time", startTimeInEpochSecond)
            .queryParam("end_time", endTimeInEpochSecond).queryParam("limit", numToReturn);

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uriComponentsBuilder.build().encode().toUri(),
                JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // FIXME figure out how to handle this
        logger.error("A request for Jawbone data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {

        JawboneDataPointMapper mapper;
        switch (jawboneDataType) {
        case WEIGHT:
            mapper = new JawboneBodyWeightDataPointMapper();
            break;
        case STEPS:
            mapper = new JawboneStepCountDataPointMapper();
            break;
        case BODY_MASS_INDEX:
            mapper = new JawboneBodyMassIndexDataPointMapper();
            break;
        case ACTIVITY:
            mapper = new JawbonePhysicalActivityDataPointMapper();
            break;
        case SLEEP:
            mapper = new JawboneSleepDurationDataPointMapper();
            break;
        case HEART_RATE:
            mapper = new JawboneHeartRateDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ResponseEntity.ok().body(ShimDataResponse.result(JawboneShim.SHIM_KEY,
                mapper.asDataPoints(singletonList(responseEntity.getBody()))));

    } else {

        return ResponseEntity.ok()
                .body(ShimDataResponse.result(JawboneShim.SHIM_KEY, responseEntity.getBody()));
    }

}

From source file:org.openmhealth.shim.googlefit.GoogleFitShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {
    final GoogleFitDataTypes googleFitDataType;
    try {//from  w  w  w  .  ja va2 s .  com
        googleFitDataType = GoogleFitDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    OffsetDateTime todayInUTC = LocalDate.now().atStartOfDay().atOffset(ZoneOffset.UTC);

    OffsetDateTime startDateInUTC = shimDataRequest.getStartDateTime() == null ? todayInUTC.minusDays(1)
            : shimDataRequest.getStartDateTime();
    long startTimeNanos = (startDateInUTC.toEpochSecond() * 1000000000) + startDateInUTC.toInstant().getNano();

    OffsetDateTime endDateInUTC = shimDataRequest.getEndDateTime() == null ? todayInUTC.plusDays(1)
            : shimDataRequest.getEndDateTime().plusDays(1); // We are inclusive of the last day, so add 1 day to get
    // the end of day on the last day, which captures the
    // entire last day
    long endTimeNanos = (endDateInUTC.toEpochSecond() * 1000000000) + endDateInUTC.toInstant().getNano();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(googleFitDataType.getStreamId(), "datasets", "{startDate}-{endDate}");
    // TODO: Add limits back into the request once Google has fixed the 'limit' query parameter and paging

    URI uriRequest = uriBuilder.buildAndExpand(startTimeNanos, endTimeNanos).encode().toUri();

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uriRequest, JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // TODO figure out how to handle this
        logger.error("A request for Google Fit data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {
        GoogleFitDataPointMapper<?> dataPointMapper;
        switch (googleFitDataType) {
        case BODY_WEIGHT:
            dataPointMapper = new GoogleFitBodyWeightDataPointMapper();
            break;
        case BODY_HEIGHT:
            dataPointMapper = new GoogleFitBodyHeightDataPointMapper();
            break;
        case ACTIVITY:
            dataPointMapper = new GoogleFitPhysicalActivityDataPointMapper();
            break;
        case STEP_COUNT:
            dataPointMapper = new GoogleFitStepCountDataPointMapper();
            break;
        case HEART_RATE:
            dataPointMapper = new GoogleFitHeartRateDataPointMapper();
            break;
        case CALORIES_BURNED:
            dataPointMapper = new GoogleFitCaloriesBurnedDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ok().body(ShimDataResponse.result(GoogleFitShim.SHIM_KEY,
                dataPointMapper.asDataPoints(singletonList(responseEntity.getBody()))));
    } else {

        return ok().body(ShimDataResponse.result(GoogleFitShim.SHIM_KEY, responseEntity.getBody()));
    }
}

From source file:org.openmhealth.shim.ihealth.IHealthShim.java

@Override
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final IHealthDataTypes dataType;
    try {/*  w w  w  .j a v  a 2s  .  c  o m*/
        dataType = valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    OffsetDateTime now = OffsetDateTime.now();
    OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();
    OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    /*
    The physical activity point handles start and end datetimes differently than the other endpoints. It
    requires use to include the range until the beginning of the next day.
     */
    if (dataType == PHYSICAL_ACTIVITY) {

        endDate = endDate.plusDays(1);
    }

    // SC and SV values are client-based keys that are unique to each endpoint within a project
    String scValue = getScValue();
    List<String> svValues = getSvValues(dataType);

    List<JsonNode> responseEntities = newArrayList();

    int i = 0;

    // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit
    // requests to each of these endpoints, map the responses separately and then combine them
    for (String endPoint : dataType.getEndPoint()) {

        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL);

        // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using
        // getData to trigger Spring to conduct the OAuth exchange
        String userId = "uk";

        if (shimDataRequest.getAccessParameters() != null) {

            OAuth2AccessToken token = SerializationUtils
                    .deserialize(shimDataRequest.getAccessParameters().getSerializedToken());

            userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID"));
            uriBuilder.queryParam("access_token", token.getValue());
        }

        uriBuilder.path("/user/").path(userId + "/").path(endPoint)
                .queryParam("client_id", restTemplate.getResource().getClientId())
                .queryParam("client_secret", restTemplate.getResource().getClientSecret())
                .queryParam("start_time", startDate.toEpochSecond())
                .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default")
                .queryParam("sc", scValue).queryParam("sv", svValues.get(i));

        ResponseEntity<JsonNode> responseEntity;

        try {
            URI url = uriBuilder.build().encode().toUri();
            responseEntity = restTemplate.getForEntity(url, JsonNode.class);
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            // FIXME figure out how to handle this
            logger.error("A request for iHealth data failed.", e);
            throw e;
        }

        if (shimDataRequest.getNormalize()) {

            IHealthDataPointMapper mapper;

            switch (dataType) {

            case PHYSICAL_ACTIVITY:
                mapper = new IHealthPhysicalActivityDataPointMapper();
                break;
            case BLOOD_GLUCOSE:
                mapper = new IHealthBloodGlucoseDataPointMapper();
                break;
            case BLOOD_PRESSURE:
                mapper = new IHealthBloodPressureDataPointMapper();
                break;
            case BODY_WEIGHT:
                mapper = new IHealthBodyWeightDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                mapper = new IHealthBodyMassIndexDataPointMapper();
                break;
            case STEP_COUNT:
                mapper = new IHealthStepCountDataPointMapper();
                break;
            case SLEEP_DURATION:
                mapper = new IHealthSleepDurationDataPointMapper();
                break;
            case HEART_RATE:
                // there are two different mappers for heart rate because the data can come from two endpoints
                if (endPoint == "bp.json") {
                    mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper();
                    break;
                } else if (endPoint == "spo2.json") {
                    mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper();
                    break;
                }
            case OXYGEN_SATURATION:
                mapper = new IHealthOxygenSaturationDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody())));

        } else {
            responseEntities.add(responseEntity.getBody());
        }

        i++;

    }

    return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities));
}