List of usage examples for org.joda.time DateTime minusDays
public DateTime minusDays(int days)
From source file:org.openmhealth.shim.fitbit.FitbitShim.java
License:Apache License
@Override public ShimDataResponse getData(ShimDataRequest shimDataRequest) throws ShimException { AccessParameters accessParameters = shimDataRequest.getAccessParameters(); String accessToken = accessParameters.getAccessToken(); String tokenSecret = accessParameters.getTokenSecret(); FitbitDataType fitbitDataType;//from ww w . j a v a 2 s. co 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 */ DateTime today = dayFormatter.parseDateTime(new DateTime().toString(dayFormatter)); //ensure beginning of today DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1) : shimDataRequest.getStartDate(); DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate(); DateTime 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.toDate().before(endDate.toDate()) || currentDate.toDate().equals(endDate.toDate())) { dayResponses.add(getDaysData(currentDate, fitbitDataType, shimDataRequest.getNormalize(), accessToken, tokenSecret)); currentDate = currentDate.plusDays(1); } return shimDataRequest.getNormalize() ? aggregateNormalized(dayResponses) : aggregateIntoList(dayResponses); } }
From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java
License:Apache License
@Override public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException { final HealthVaultDataType healthVaultDataType; try {/* w ww. ja v a 2 s .co m*/ healthVaultDataType = HealthVaultDataType .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."); } final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss"); /*** * Setup default date parameters */ DateTime today = new DateTime(); DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1) : shimDataRequest.getStartDate(); String dateStart = startDate.toString(formatter); DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate(); String dateEnd = endDate.toString(formatter); long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100 : shimDataRequest.getNumToReturn(); Request request = new Request(); request.setMethodName("GetThings"); request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>" + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>" + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>"); RequestTemplate template = new RequestTemplate(connection); return template.makeRequest(shimDataRequest.getAccessParameters(), request, new Marshaller<ShimDataResponse>() { public ShimDataResponse marshal(InputStream istream) throws Exception { /** * XML Document mappings to JSON don't respect repeatable * tags, they don't get properly serialized into collections. * Thus, we pickup the 'things' via the 'group' root tag * and create a new JSON document out of each 'thing' node. */ XmlMapper xmlMapper = new XmlMapper(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(istream); NodeList nodeList = doc.getElementsByTagName("thing"); /** * Collect JsonNode from each 'thing' xml node. */ List<JsonNode> thingList = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Document thingDoc = builder.newDocument(); Node newNode = thingDoc.importNode(node, true); thingDoc.appendChild(newNode); thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc))); } /** * Rebuild JSON document structure to pass to deserializer. */ String thingsJson = "{\"things\":["; String thingsContent = ""; for (JsonNode thingNode : thingList) { thingsContent += thingNode.toString() + ","; } thingsContent = "".equals(thingsContent) ? thingsContent : thingsContent.substring(0, thingsContent.length() - 1); thingsJson += thingsContent; thingsJson += "]}"; /** * Return raw re-built 'things' or a normalized JSON document. */ ObjectMapper objectMapper = new ObjectMapper(); if (shimDataRequest.getNormalize()) { SimpleModule module = new SimpleModule(); module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer()); objectMapper.registerModule(module); return objectMapper.readValue(thingsJson, ShimDataResponse.class); } else { return ShimDataResponse.result(HealthvaultShim.SHIM_KEY, objectMapper.readTree(thingsJson)); } } }); }
From source file:org.openmhealth.shim.jawbone.JawboneShim.java
License:Apache License
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { String urlRequest = DATA_URL; final JawboneDataTypes jawboneDataType; try {/*from www. j a v a 2s. c om*/ 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."); } urlRequest += jawboneDataType.getEndPoint() + "?"; long numToReturn = 100; if (shimDataRequest.getNumToReturn() != null) { numToReturn = shimDataRequest.getNumToReturn(); } DateTime today = new DateTime(); DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1) : shimDataRequest.getStartDate(); long startTimeTs = startDate.toDate().getTime() / 1000; DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate(); long endTimeTs = endDate.toDate().getTime() / 1000; urlRequest += "&start_time=" + startTimeTs; urlRequest += "&end_time=" + endTimeTs; urlRequest += "&limit=" + numToReturn; ObjectMapper objectMapper = new ObjectMapper(); ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(urlRequest, byte[].class); JsonNode json = null; try { if (shimDataRequest.getNormalize()) { SimpleModule module = new SimpleModule(); module.addDeserializer(ShimDataResponse.class, jawboneDataType.getNormalizer()); objectMapper.registerModule(module); return new ResponseEntity<>( objectMapper.readValue(responseEntity.getBody(), ShimDataResponse.class), HttpStatus.OK); } else { return new ResponseEntity<>(ShimDataResponse.result(JawboneShim.SHIM_KEY, objectMapper.readTree(responseEntity.getBody())), HttpStatus.OK); } } catch (IOException e) { e.printStackTrace(); throw new ShimException("Could not read response data."); } }
From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java
License:Apache License
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { String dataTypeKey = shimDataRequest.getDataTypeKey().trim().toUpperCase(); RunkeeperDataType runkeeperDataType; try {//from w w w. j a va 2 s.c om runkeeperDataType = RunkeeperDataType.valueOf(dataTypeKey); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException("Null or Invalid data type parameter: " + dataTypeKey + " in shimDataRequest, cannot retrieve data."); } String urlRequest = DATA_URL; urlRequest += "/" + runkeeperDataType.getEndPointUrl(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", runkeeperDataType.getDataTypeHeader()); final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); /*** * Setup default date parameters */ DateTime today = new DateTime(); DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1) : shimDataRequest.getStartDate(); String dateStart = startDate.toString(formatter); DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate(); String dateEnd = endDate.toString(formatter); long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100 : shimDataRequest.getNumToReturn(); String urlParams = ""; urlParams += "&noEarlierThan=" + dateStart; urlParams += "&noLaterThan=" + dateEnd; urlParams += "&pageSize=" + numToReturn; urlRequest += "".equals(urlParams) ? "" : ("?" + urlParams.substring(1, urlParams.length())); ObjectMapper objectMapper = new ObjectMapper(); ResponseEntity<byte[]> response = restTemplate.exchange(urlRequest, HttpMethod.GET, new HttpEntity<byte[]>(headers), byte[].class); try { if (shimDataRequest.getNormalize()) { SimpleModule module = new SimpleModule(); module.addDeserializer(ShimDataResponse.class, runkeeperDataType.getNormalizer()); objectMapper.registerModule(module); return new ResponseEntity<>(objectMapper.readValue(response.getBody(), ShimDataResponse.class), HttpStatus.OK); } else { return new ResponseEntity<>( ShimDataResponse.result(RunkeeperShim.SHIM_KEY, objectMapper.readTree(response.getBody())), HttpStatus.OK); } } catch (IOException e) { e.printStackTrace(); throw new ShimException("Could not read response data."); } }
From source file:org.openmhealth.shim.withings.WithingsShim.java
License:Apache License
@Override public ShimDataResponse getData(ShimDataRequest shimDataRequest) throws ShimException { AccessParameters accessParameters = shimDataRequest.getAccessParameters(); String accessToken = accessParameters.getAccessToken(); String tokenSecret = accessParameters.getTokenSecret(); final String userid = accessParameters.getAdditionalParameters().get("userid").toString(); String endPointUrl = DATA_URL; final WithingsDataType withingsDataType; try {/* ww w . ja v a 2s . c o m*/ withingsDataType = WithingsDataType.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."); } final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); /*** * Setup default date parameters */ DateTime today = new DateTime(); DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1) : shimDataRequest.getStartDate(); String dateStart = startDate.toString(formatter); long dateStartTs = startDate.toDate().getTime() / 1000; DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate(); String dateEnd = endDate.toString(formatter); long dateEndTs = endDate.toDate().getTime() / 1000; endPointUrl += "/" + withingsDataType.getEndPointMethod(); //"&meastype=4"; endPointUrl += "&userid=" + userid; if (withingsDataType.isTimeStampFormat()) { endPointUrl += "&" + withingsDataType.getDateParamStart() + "=" + dateStartTs; endPointUrl += "&" + withingsDataType.getDateParamEnd() + "=" + dateEndTs; } else { endPointUrl += "&" + withingsDataType.getDateParamStart() + "=" + dateStart; endPointUrl += "&" + withingsDataType.getDateParamEnd() + "=" + dateEnd; } if (withingsDataType.isNumToReturnSupported() && shimDataRequest.getNumToReturn() != null) { endPointUrl += "&limit=" + shimDataRequest.getNumToReturn(); } URL url = signUrl(endPointUrl, accessToken, tokenSecret, null); // Fetch and decode the JSON data. ObjectMapper objectMapper = new ObjectMapper(); HttpGet get = new HttpGet(url.toString()); HttpResponse response; try { response = httpClient.execute(get); HttpEntity responseEntity = response.getEntity(); if (shimDataRequest.getNormalize()) { SimpleModule module = new SimpleModule(); module.addDeserializer(ShimDataResponse.class, withingsDataType.getNormalizer()); objectMapper.registerModule(module); return objectMapper.readValue(responseEntity.getContent(), ShimDataResponse.class); } else { return ShimDataResponse.result(WithingsShim.SHIM_KEY, objectMapper.readTree(responseEntity.getContent())); } } catch (IOException e) { throw new ShimException("Could not fetch data", e); } finally { get.releaseConnection(); } }
From source file:org.projectforge.web.address.BirthdayEventsProvider.java
License:Open Source License
/** * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime, org.joda.time.DateTime) *///from w w w . jav a 2 s.c o m @Override protected void buildEvents(final DateTime start, final DateTime end) { if (filter.isShowBirthdays() == false) { // Don't show birthdays. return; } DateTime from = start; if (start.getMonthOfYear() == Calendar.MARCH && start.getDayOfMonth() == 1) { from = start.minusDays(1); } final Set<BirthdayAddress> set = addressDao.getBirthdays(from.toDate(), end.toDate(), 1000, true); for (final BirthdayAddress birthdayAddress : set) { final AddressDO address = birthdayAddress.getAddress(); final int month = birthdayAddress.getMonth() + 1; final int dayOfMonth = birthdayAddress.getDayOfMonth(); DateTime date = getDate(from, end, month, dayOfMonth); // February, 29th fix: if (date == null && month == Calendar.FEBRUARY + 1 && dayOfMonth == 29) { date = getDate(from, end, month + 1, 1); } if (date == null && WebConfiguration.isDevelopmentMode() == true) { log.info("Date " + birthdayAddress.getDayOfMonth() + "/" + (birthdayAddress.getMonth() + 1) + " not found between " + from + " and " + end); continue; } else { if (dataProtection == false && date != null) { birthdayAddress.setAge(date.toDate()); } } final Event event = new Event().setAllDay(true); event.setClassName(EVENT_CLASS_NAME); final String id = "" + address.getId(); event.setId(id); event.setStart(date); final StringBuffer buf = new StringBuffer(); if (dataProtection == false) { // Birthday is not visible for all users (age == 0). buf.append(DateTimeFormatter.instance().getFormattedDate(address.getBirthday(), DateFormats.getFormatString(DateFormatType.DATE_SHORT))).append(" "); } buf.append(address.getFirstName()).append(" ").append(address.getName()); if (dataProtection == false && birthdayAddress.getAge() > 0) { // Birthday is not visible for all users (age == 0). buf.append(" (").append(birthdayAddress.getAge()).append(" ").append(getString("address.age.short")) .append(")"); } event.setTitle(buf.toString()); if (birthdayAddress.isFavorite() == true) { // Colors of events of birthdays of favorites (for default color see CalendarPanel): event.setBackgroundColor("#06790E"); event.setBorderColor("#06790E"); event.setTextColor("#FFFFFF"); } events.put(id, event); } }
From source file:org.slc.sli.common.util.datetime.DateHelper.java
License:Apache License
public DateTime getNowMinusGracePeriod() { DateTime now = DateTime.now(); int numDays = Integer.parseInt(gracePeriod); return now.minusDays(numDays); }
From source file:org.slc.sli.common.util.datetime.DateHelper.java
License:Apache License
public boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod) { boolean expired = false; if (null != body.get(fieldName)) { DateTime expire = DateTime.parse((String) body.get(fieldName), FMT); DateTime now = DateTime.now(); if (useGracePeriod) { int numDays = Integer.parseInt(gracePeriod); now = now.minusDays(numDays); }//ww w . jav a 2s .co m expired = now.isAfter(expire); } return expired; }
From source file:org.sonar.plugins.scmstats.utils.DateRange.java
License:Open Source License
public static DateRange getDateRange(int numDays, DateTime toDate) { DateTime now = new DateTime(); DateTime earliest = new DateTime("1980-01-01"); DateTime end = toDate != null ? toDate : now; DateTime start = numDays == 0 ? earliest : end.minusDays(numDays); return new DateRange(start, end); }
From source file:org.springframework.analytics.rest.controller.AggregateCounterController.java
License:Apache License
/** * Return a default value for the interval start if none has been provided. */// w w w . j a v a 2 s . c o m private DateTime providedOrDefaultFromValue(DateTime from, DateTime to, AggregateCounterResolution resolution) { if (from != null) { return from; } switch (resolution) { case minute: return to.minusMinutes(59); case hour: return to.minusHours(23); case day: return to.minusDays(6); case month: return to.minusMonths(11); case year: return to.minusYears(4); default: throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution); } }