List of usage examples for org.joda.time DateTime plusDays
public DateTime plusDays(int days)
From source file:org.opendatakit.utilities.DateUtils.java
License:Apache License
private Interval tryParseInterval(String input) { for (int i = 0; i < userPartialParsers.length; i++) { try {// ww w . j av a2s . c o m DateTime start = userPartialParsers[i].parseDateTime(input); DateTime end = start.plusSeconds(USER_INTERVAL_DURATIONS[i]); return new Interval(start, end); } catch (IllegalArgumentException ignored) { // TODO } } if (!locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) { return null; } DateTime start = new DateTime().withTimeAtStartOfDay(); boolean match = false; if ("today".equalsIgnoreCase(input)) { match = true; } else if ("yesterday".equalsIgnoreCase(input)) { start = start.minusDays(1); match = true; } else if ("tomorrow".equalsIgnoreCase(input) || "tmw".equalsIgnoreCase(input)) { start = start.plusDays(1); match = true; } if (match) { DateTime end = start.plusDays(1); return new Interval(start, end); } return null; }
From source file:org.openmainframe.ade.ext.utils.ExtDateTimeUtils.java
License:Open Source License
/** * Method to return a "normalized" version of the input Date * whose time is reset to the absolute start of that same day * (first millisecond of first second of first minute of first hour). * /* w ww . j a v a 2 s.co m*/ * @param dateInst - instance of Date * @return - instance of Date as described * @throws AdeException */ public static Date endOfDayUsingOutputTimeZone(Date dateInst) throws AdeException { /* * Note: This method generates a different end of day compare to endOfDay(). * endOfDay() would generate timestamp: 10/10/2013 23:59:59 * endOfDayUsingOutputTimeZone() would generate timestampe: 10/11/2013 00:00:00 */ if (outputTimeZone == null) { final TimeZone outputTimezone = Ade.getAde().getConfigProperties().getOutputTimeZone(); outputTimeZone = DateTimeZone.forOffsetMillis(outputTimezone.getRawOffset()); } if (dateInst == null) { throw new IllegalArgumentException(); } /* Set end of today */ DateTime startOFDay = new DateTime(dateInst); startOFDay = startOFDay.withZone(outputTimeZone); startOFDay = startOFDay.plusDays(1); startOFDay = startOFDay.withTimeAtStartOfDay(); return startOFDay.toDate(); }
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;// ww w . j a v a2s. 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 */ 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 {//ww w . j a v a 2 s.c o 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 w ww . ja v a 2 s . c o 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."); } 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 ww w.java 2s. c o m*/ 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 . j a va 2s .co 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.opentestsystem.delivery.testadmin.scheduling.Scheduler.java
License:Open Source License
private Schedule generateScheduleStructure(final Schedule inSchedule, final Map<String, FacilityData> facilityData) { // build out the full Schedule structure // Create a List of ScheduledDay objects, one object for each day in the schedule // Each ScheduledDay object contains a List of ScheduledFacility objects, one for each Facility for this // institution // Each ScheduledFacility contains a list of ScheduledTimeSlots which are based upon the FacilityTimeSlot List // in each FacilityAvailability object // Each ScheduledTimeSlot contains a List of ScheduledSeat objects which are based off of the SeatConfigurations // setup in each FacilityTimeSlot Schedule scheduled = null;/*from w w w. java2 s.c om*/ try { scheduled = (Schedule) inSchedule.clone(); } catch (CloneNotSupportedException e) { throw new ScheduleException("Failed to clone schedule object, cannot generate schedule ", e); } TreeMap<DateTime, ScheduledDay> scheduledDaysMap = new TreeMap<DateTime, ScheduledDay>(); DateTime scheduleStart = scheduled.getStartDate(); DateTime scheduleEnd = scheduled.getEndDate(); DateTime curTime = scheduleStart; // build all the ScheduledDay objects for this schedule while (curTime.isBefore(scheduleEnd) || curTime.equals(scheduleEnd)) { if (scheduled.isDoNotScheduleWeekends()) { if (curTime.getDayOfWeek() <= DateTimeConstants.FRIDAY) { ScheduledDay sday = new ScheduledDay(); sday.setDay(curTime); scheduledDaysMap.put(curTime, sday); } } else { ScheduledDay sday = new ScheduledDay(); sday.setDay(curTime); scheduledDaysMap.put(curTime, sday); } curTime = curTime.plusDays(1); } // go ahead and set the ScheduledDay objects into the schedule scheduled.setScheduledDays(new ArrayList<ScheduledDay>(scheduledDaysMap.values())); // iterate through all the FacilityData objects we have // each FacilityData has a Facility and a List of FacilityAvailabilities // Need to create a ScheduledFacility for each Facility for each ScheduledDay, // The ScheduledFacility has a list of ScheduledTimeSlots that need to be generated based upon // the FacilityAvailability objects which state from and to time. Basically, we need to match the date of the // ScheduledDay to the from->to range to ensure that the date of the current ScheduledDay falls in there. for (Map.Entry<String, FacilityData> entry : facilityData.entrySet()) { FacilityData facilData = entry.getValue(); List<FacilityAvailability> availabilities = facilData.getAvailabilities(); Facility facility = facilData.getFacility(); // ensure that the seats are generated from the configurations facility.createSeatsFromConfiguration(); for (FacilityAvailability avail : availabilities) { DateTime from = avail.getFromDate(); DateTime to = avail.getToDate(); List<FacilityTimeSlot> facilityTimeSlots = avail.getFacilityTimes(); // iterate through ScheduledDays // if the day is in the range for the facility availability, then create a ScheduledFacility object // for that ScheduledDay for (DateTime schedDate : scheduledDaysMap.keySet()) { if ((from.isEqual(schedDate) || from.isBefore(schedDate)) && (to.isEqual(schedDate) || to.isAfter(schedDate))) { ScheduledFacility schedFacil = new ScheduledFacility(facility); // generate scheduled time slots for scheduledFacility for (FacilityTimeSlot slot : facilityTimeSlots) { slot.createSeatsFromConfiguration(); ScheduledTimeSlot schedSlot = new ScheduledTimeSlot(slot.getTimeSlot()); // create scheduled seats in slot for (SeatConfiguration seatConfig : slot.getSeatConfigurations()) { for (Seat seat : seatConfig.getSeats()) { schedSlot.addSeat(new ScheduledSeat(seat)); } } // modify the date on the ScheduledTimeSlot to have the correct date (from schedDate) to go // along with the specified time (from schedSlot) // This will allow for correct ordering of time slots DateTime newStartDate = new DateTime(schedDate.getYear(), schedDate.getMonthOfYear(), schedDate.getDayOfMonth(), schedSlot.getStartTime().getHourOfDay(), schedSlot.getStartTime().getMinuteOfHour()); DateTime newEndDate = new DateTime(schedDate.getYear(), schedDate.getMonthOfYear(), schedDate.getDayOfMonth(), schedSlot.getEndTime().getHourOfDay(), schedSlot.getEndTime().getMinuteOfHour()); schedSlot.setStartTime(newStartDate); schedSlot.setEndTime(newEndDate); schedFacil.addTimeSlot(schedSlot); } scheduledDaysMap.get(schedDate).addFacility(schedFacil); } } } } scheduled.generateOrderedTimeSlots(); return scheduled; }
From source file:org.opentestsystem.delivery.testadmin.scheduling.SchedulerHelper.java
License:Open Source License
/** * Interrogates a List of EligibleStudents to find a unique set of Assessments for all of the Students eligible. * /*from ww w . j a va2 s.co m*/ * @param eligibleStudents * @param startDate * @param endDate * @return */ public List<Assessment> findAssessments(final List<EligibleStudent> eligibleStudents, final DateTime startDate, final DateTime endDate, final List<String> tenantIdsForAssessment) { // the assessments to schedule are the assessments with a test window at least partially within the schedule // dates // taken from the EligibleStudents // use a set to avoid duplicate Assessments // IMPORTANT!!!!!!!!! // This code will add one day to the end date of the schedule and each of the test window end dates // because the Joda Interval makes the end instant EXCLUSIVE // We need to ensure that the interval takes into account that the end dates are part of the interval. // Since all of our schedule dates and test windows use midnight as the time, an end date of 06-02-2014 00:00:00 // will turn into 06-03-2014 00:00:00 and thus the entire day of 06-02 is now part of the interval // !!!!!!!!!!!!!!!!!! final Interval scheduleInterval = new Interval(startDate, endDate.plusDays(1)); Interval testWindowInterval = null; final Set<Assessment> schedulableAssessments = new HashSet<Assessment>(); for (final EligibleStudent eligStudent : eligibleStudents) { for (final Assessment assess : eligStudent.getAssessments()) { for (final TestWindow testWindow : assess.getTestWindow()) { testWindowInterval = new Interval(testWindow.getBeginWindow(), testWindow.getEndWindow().plusDays(1)); if (scheduleInterval.overlaps(testWindowInterval) && tenantIdsForAssessment.contains(assess.getTenantId())) { schedulableAssessments.add(assess); break; } } } } return new ArrayList<Assessment>(schedulableAssessments); }
From source file:org.openvpms.archetype.i18n.time.DateDurationFormatter.java
License:Open Source License
/** * Formats the duration between two timestamps. * <p/>// ww w .j a va 2 s .c o m * NOTE: this currently doesn't do anything sensible for from > to. Possible solution would be to simply * reverse the times, and then prepend a - between each field using the * * @param from the starting time * @param to the ending time * @return the formatted duration */ protected String format(DateTime from, DateTime to) { int years = 0; int months = 0; int weeks = 0; int days = 0; int hours = 0; int minutes = 0; DateTime start = from; if (showYears) { years = Years.yearsBetween(start, to).getYears(); start = start.plusYears(years); } if (showMonths) { months = Months.monthsBetween(start, to).getMonths(); start = start.plusMonths(months); } if (showWeeks) { weeks = Weeks.weeksBetween(start, to).getWeeks(); start = start.plusWeeks(weeks); } if (showDays) { days = Days.daysBetween(start, to).getDays(); start = start.plusDays(days); } if (showHours) { hours = Hours.hoursBetween(start, to).getHours(); start = start.plusHours(hours); } if (showMinutes) { minutes = Minutes.minutesBetween(start, to).getMinutes(); } Period period = new Period(years, months, weeks, days, hours, minutes, 0, 0); return formatter.print(period); }