List of usage examples for java.time OffsetDateTime minusDays
public OffsetDateTime minusDays(long days)
From source file:Main.java
public static void main(String[] args) { OffsetDateTime o = OffsetDateTime.now(); OffsetDateTime d = o.minusDays(120); System.out.println(d);//from ww w. j a v a2 s . co m }
From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { String dataTypeKey = shimDataRequest.getDataTypeKey().trim().toUpperCase(); RunkeeperDataType runkeeperDataType; try {/* w w w .j a v a 2 s.co m*/ runkeeperDataType = RunkeeperDataType.valueOf(dataTypeKey); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException("Null or Invalid data type parameter: " + dataTypeKey + " in shimDataRequest, cannot retrieve data."); } /*** * Setup default date parameters */ OffsetDateTime now = OffsetDateTime.now(); OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? now.minusDays(1) : shimDataRequest.getStartDateTime(); OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? now.plusDays(1) : shimDataRequest.getEndDateTime(); /* Runkeeper defaults to returning a maximum of 25 entries per request (pageSize = 25 by default), so we override the default by specifying an arbitrarily large number as the pageSize. */ long numToReturn = 100_000; UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL) .pathSegment(runkeeperDataType.getEndPointUrl()) .queryParam("noEarlierThan", startDateTime.toLocalDate()) .queryParam("noLaterThan", endDateTime.toLocalDate()).queryParam("pageSize", numToReturn) .queryParam("detail", true); // added to all endpoints to support summaries HttpHeaders headers = new HttpHeaders(); headers.set("Accept", runkeeperDataType.getDataTypeHeader()); ResponseEntity<JsonNode> responseEntity; try { responseEntity = restTemplate.exchange(uriBuilder.build().encode().toUri(), GET, new HttpEntity<JsonNode>(headers), JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // FIXME figure out how to handle this logger.error("A request for RunKeeper data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { RunkeeperDataPointMapper<?> dataPointMapper; switch (runkeeperDataType) { case ACTIVITY: dataPointMapper = new RunkeeperPhysicalActivityDataPointMapper(); break; case CALORIES: dataPointMapper = new RunkeeperCaloriesBurnedDataPointMapper(); break; default: throw new UnsupportedOperationException(); } return ok().body(ShimDataResponse.result(SHIM_KEY, dataPointMapper.asDataPoints(singletonList(responseEntity.getBody())))); } else { return ok().body(ShimDataResponse.result(SHIM_KEY, responseEntity.getBody())); } }
From source file:org.openmhealth.shim.misfit.MisfitShim.java
@Override protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final MisfitDataTypes misfitDataType; try {/*from w w w . j a va 2 s. co m*/ misfitDataType = MisfitDataTypes.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."); } // TODO don't truncate dates OffsetDateTime now = OffsetDateTime.now(); OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? now.minusDays(1) : shimDataRequest.getStartDateTime(); OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? now.plusDays(1) : shimDataRequest.getEndDateTime(); if (Duration.between(startDateTime, endDateTime).toDays() > MAX_DURATION_IN_DAYS) { endDateTime = startDateTime.plusDays(MAX_DURATION_IN_DAYS - 1); // TODO when refactoring, break apart queries } UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL); for (String pathSegment : Splitter.on("/").split(misfitDataType.getEndPoint())) { uriBuilder.pathSegment(pathSegment); } uriBuilder.queryParam("start_date", startDateTime.toLocalDate()) // TODO convert ODT to LocalDate properly .queryParam("end_date", endDateTime.toLocalDate()).queryParam("detail", true); // added to all endpoints to support summaries ResponseEntity<JsonNode> responseEntity; try { responseEntity = restTemplate.getForEntity(uriBuilder.build().encode().toUri(), JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // FIXME figure out how to handle this logger.error("A request for Misfit data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { MisfitDataPointMapper<?> dataPointMapper; switch (misfitDataType) { case ACTIVITIES: dataPointMapper = physicalActivityMapper; break; case SLEEP: dataPointMapper = sleepDurationMapper; break; case STEPS: dataPointMapper = stepCountMapper; break; default: throw new UnsupportedOperationException(); } return ok().body(ShimDataResponse.result(SHIM_KEY, dataPointMapper.asDataPoints(singletonList(responseEntity.getBody())))); } else { return ok().body(ShimDataResponse.result(SHIM_KEY, responseEntity.getBody())); } }
From source file:org.openmhealth.shim.jawbone.JawboneShim.java
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final JawboneDataTypes jawboneDataType; try {/*from ww w.ja v a 2s .com*/ 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 v a 2 s . c om*/ 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 {//from w ww . j av a 2 s .co 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)); }
From source file:org.openmhealth.shim.fitbit.FitbitShim.java
@Override public ShimDataResponse getData(ShimDataRequest shimDataRequest) throws ShimException { AccessParameters accessParameters = shimDataRequest.getAccessParameters(); String accessToken = accessParameters.getAccessToken(); String tokenSecret = accessParameters.getTokenSecret(); FitbitDataType fitbitDataType;/* w ww. j a v a2 s. c o m*/ try { fitbitDataType = FitbitDataType.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."); } /*** * Setup default date parameters */ OffsetDateTime today = LocalDate.now().atStartOfDay(ZoneId.of("Z")).toOffsetDateTime(); OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? today.minusDays(1) : shimDataRequest.getStartDateTime(); OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? today.plusDays(1) : shimDataRequest.getEndDateTime(); OffsetDateTime currentDate = startDate; if (fitbitDataType.equals(FitbitDataType.WEIGHT)) { return getRangeData(startDate, endDate, fitbitDataType, shimDataRequest.getNormalize(), accessToken, tokenSecret); } else { /** * Fitbit's API limits you to making a request for each given day * of data. Thus we make a request for each day in the submitted time * range and then aggregate the response based on the normalization parameter. */ List<ShimDataResponse> dayResponses = new ArrayList<>(); while (currentDate.toLocalDate().isBefore(endDate.toLocalDate()) || currentDate.toLocalDate().isEqual(endDate.toLocalDate())) { dayResponses.add(getDaysData(currentDate, fitbitDataType, shimDataRequest.getNormalize(), accessToken, tokenSecret)); currentDate = currentDate.plusDays(1); } ShimDataResponse shimDataResponse = shimDataRequest.getNormalize() ? aggregateNormalized(dayResponses) : aggregateIntoList(dayResponses); return shimDataResponse; } }