Example usage for org.joda.time DateTime plusHours

List of usage examples for org.joda.time DateTime plusHours

Introduction

In this page you can find the example usage for org.joda.time DateTime plusHours.

Prototype

public DateTime plusHours(int hours) 

Source Link

Document

Returns a copy of this datetime plus the specified number of hours.

Usage

From source file:org.jruby.ext.date.RubyDate.java

License:LGPL

private void adjustWithDayFraction(ThreadContext context, DateTime dt, final long[] rest) {
    final RubyFixnum zero = RubyFixnum.zero(context.runtime);
    int ival;//  w  w  w .j  a va  2 s .co  m

    ival = RubyDateTime.getHour(context, zero, rest);
    dt = dt.plusHours(ival);

    if (rest[0] != 0) {
        ival = RubyDateTime.getMinute(context, zero, rest);
        dt = dt.plusMinutes(ival);

        if (rest[0] != 0) {
            ival = RubyDateTime.getSecond(context, zero, rest);
            dt = dt.plusSeconds(ival);

            final long r0 = rest[0], r1 = rest[1];
            if (r0 != 0) {
                long millis = (1000 * r0) / r1;
                dt = dt.plusMillis((int) millis);

                subMillisNum = ((1000 * r0) - (millis * r1));
                subMillisDen = r1;
                normalizeSubMillis();
            }
        }
    }

    this.dt = dt;
}

From source file:org.kairosdb.util.Util.java

License:Apache License

/**
 Computes the duration of the sampling (value * unit) starting at timestamp.
        //w  w  w.  j a  v  a2 s  .  c o m
 @param timestamp unix timestamp of the start time.
 @return the duration of the sampling in millisecond.
 */
public static long getSamplingDuration(long timestamp, Sampling sampling, DateTimeZone timeZone) {
    long ret = sampling.getValue();
    DateTime dt = new DateTime(timestamp, timeZone);
    switch (sampling.getUnit()) {
    case YEARS:
        ret = new org.joda.time.Duration(dt, dt.plusYears((int) sampling.getValue())).getMillis();
        break;
    case MONTHS:
        ret = new org.joda.time.Duration(dt, dt.plusMonths((int) sampling.getValue())).getMillis();
        break;
    case WEEKS:
        ret = new org.joda.time.Duration(dt, dt.plusWeeks((int) sampling.getValue())).getMillis();
        break;
    case DAYS:
        ret = new org.joda.time.Duration(dt, dt.plusDays((int) sampling.getValue())).getMillis();
        break;
    case HOURS:
        ret = new org.joda.time.Duration(dt, dt.plusHours((int) sampling.getValue())).getMillis();
        break;
    case MINUTES:
        ret = new org.joda.time.Duration(dt, dt.plusMinutes((int) sampling.getValue())).getMillis();
        break;
    case SECONDS:
        ret = new org.joda.time.Duration(dt, dt.plusSeconds((int) sampling.getValue())).getMillis();
        break;
    case MILLISECONDS:
        ret = (long) sampling.getValue();
        break;
    }
    return ret;
}

From source file:org.killbill.billing.plugin.analytics.reports.scheduler.JobsScheduler.java

License:Apache License

@VisibleForTesting
DateTime computeNextRun(final AnalyticsReportJob report) {

    final DateTime now = clock.getUTCNow();

    if (Frequency.HOURLY.equals(report.getRefreshFrequency())) {
        // 5' past the hour (fixed to avoid drifts)
        return now.plusHours(1).withMinuteOfHour(5).withSecondOfMinute(0).withMillisOfSecond(0);
    } else if (Frequency.DAILY.equals(report.getRefreshFrequency())) {
        // 6am GMT by default
        final Integer hourOfTheDayGMT = MoreObjects.firstNonNull(report.getRefreshHourOfDayGmt(), 6);
        final DateTime boundaryTime = now.withHourOfDay(hourOfTheDayGMT).withMinuteOfHour(0)
                .withSecondOfMinute(0).withMillisOfSecond(0);
        return now.compareTo(boundaryTime) >= 0 ? boundaryTime.plusDays(1) : boundaryTime;
    } else {//from  w ww . jav a  2 s  . com
        // Run now
        return now;
    }
}

From source file:org.kitesdk.apps.spi.oozie.CronConverter.java

License:Apache License

public static Instant nextInstant(String cronSchedule, Instant current) {

    DateTime currentTime = new DateTime(current, DateTimeZone.UTC).withSecondOfMinute(0).withMillisOfSecond(0);

    validate(cronSchedule);//w  w  w.  j  a  va  2  s .  com

    String[] splits = cronSchedule.split(" ");

    String minutePart = splits[0];
    String hourPart = splits[1];
    String dayPart = splits[2];

    // TODO: fold these together like the hour.
    if (isWildCard(minutePart)) {
        return currentTime.plusMinutes(1).toInstant();
    }

    if (isInterval(minutePart)) {

        // Roll minutes forward until we hit a start time
        // that matches the cron interval.
        int interval = getInterval(minutePart);

        DateTime next = currentTime.withSecondOfMinute(0).plusMinutes(1);

        while (!(next.getMinuteOfHour() % interval == 0)) {

            next = next.plusMinutes(1);
        }

        return next.toInstant();
    }

    assert (isConstant(minutePart));

    // The minute part must be a constant, so
    // simply get the value.
    int minute = Integer.parseInt(minutePart);

    // The schedule is based on hours.
    if (!isConstant(hourPart)) {

        int hourModulus = isWildCard(hourPart) ? 1 : getInterval(hourPart);

        DateTime next = currentTime.withMinuteOfHour(minute);

        while (next.isBefore(current) || !(next.getHourOfDay() % hourModulus == 0)) {

            next = next.plusHours(1);
        }

        return next.toInstant();
    }

    int hour = Integer.parseInt(hourPart);

    // The schedule is based on days, and therfore the day cannot
    // be a constant. This is is checked in validation as well.
    assert (!isConstant(dayPart));

    DateTime next = currentTime.withMinuteOfHour(minute).withHourOfDay(hour);

    while (next.isBefore(current)) {

        next = next.plusDays(1);
    }

    return next.toInstant();
}

From source file:org.kuali.kpme.tklm.time.rules.shiftdifferential.service.ShiftDifferentialRuleServiceImpl.java

License:Educational Community License

@Override
public void processShiftDifferentialRules(TimesheetDocument timesheetDocument, TkTimeBlockAggregate aggregate) {
    DateTimeZone zone = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
    List<List<TimeBlock>> blockDays = aggregate.getDayTimeBlockList();
    DateTime periodStartDateTime = timesheetDocument.getCalendarEntry().getBeginPeriodLocalDateTime()
            .toDateTime(zone);//from ww w  .  jav a2s.com
    Map<Long, Set<ShiftDifferentialRule>> jobNumberToShifts = getJobNumberToShiftRuleMap(timesheetDocument);

    // If there are no shift differential rules, we have an early exit.
    if (jobNumberToShifts.isEmpty()) {
        return;
    }

    // Get the last day of the previous pay period. We need this to determine
    // if there are hours from the previous pay period that will effect the
    // shift rule on the first day of the currently-being-processed pay period.
    //
    // Will be set to null if not applicable.
    boolean previousPayPeriodPrevDay = true;
    Map<Long, List<TimeBlock>> jobNumberToTimeBlocksPreviousDay = getPreviousPayPeriodLastDayJobToTimeBlockMap(
            timesheetDocument, jobNumberToShifts);

    // We are going to look at the time blocks grouped by Days.
    //
    // This is a very large outer loop.
    for (int pos = 0; pos < blockDays.size(); pos++) {
        List<TimeBlock> blocks = blockDays.get(pos); // Timeblocks for this day.
        if (blocks.isEmpty())
            continue; // No Time blocks, no worries.

        DateTime currentDay = periodStartDateTime.plusDays(pos);
        Interval virtualDay = new Interval(currentDay, currentDay.plusHours(24));

        // Builds our JobNumber to TimeBlock for Current Day List.
        //
        // Shift Differential Rules are also grouped by Job number, this
        // provides a quick way to do the lookup / reference.
        // We don't need every time block, only the ones that will be
        // applicable to the shift rules.
        Map<Long, List<TimeBlock>> jobNumberToTimeBlocks = new HashMap<Long, List<TimeBlock>>();
        for (TimeBlock block : blocks) {
            Long jobNumber = block.getJobNumber();
            if (jobNumberToShifts.containsKey(jobNumber)) {
                List<TimeBlock> jblist = jobNumberToTimeBlocks.get(jobNumber);
                if (jblist == null) {
                    jblist = new ArrayList<TimeBlock>();
                    jobNumberToTimeBlocks.put(jobNumber, jblist);
                }
                jblist.add(block);
            }
        }

        // Large Outer Loop to look at applying the Shift Rules based on
        // the current JobNumber.
        //
        // This loop will handle previous day boundary time as well as the
        // current day.
        //
        // There is room for refactoring here!
        for (Map.Entry<Long, Set<ShiftDifferentialRule>> entry : jobNumberToShifts.entrySet()) {
            Set<ShiftDifferentialRule> shiftDifferentialRules = entry.getValue();
            // Obtain and sort our previous and current time blocks.
            List<TimeBlock> ruleTimeBlocksPrev = null;
            List<TimeBlock> ruleTimeBlocksCurr = jobNumberToTimeBlocks.get(entry.getKey());
            if (ruleTimeBlocksCurr != null && ruleTimeBlocksCurr.size() > 0) {
                if (jobNumberToTimeBlocksPreviousDay != null)
                    ruleTimeBlocksPrev = jobNumberToTimeBlocksPreviousDay.get(entry.getKey());
                if (ruleTimeBlocksPrev != null && ruleTimeBlocksPrev.size() > 0)
                    this.sortTimeBlocksInverse(ruleTimeBlocksPrev);
                this.sortTimeBlocksNatural(ruleTimeBlocksCurr);
            } else {
                // Skip to next job, there is nothing for this job
                // on this day, and because of this we don't care
                // about the previous day either.
                continue;
            }

            for (ShiftDifferentialRule rule : shiftDifferentialRules) {
                Set<String> fromEarnGroup = HrServiceLocator.getEarnCodeGroupService()
                        .getEarnCodeListForEarnCodeGroup(rule.getFromEarnGroup(), timesheetDocument
                                .getCalendarEntry().getBeginPeriodFullDateTime().toLocalDate());

                LocalTime ruleStart = new LocalTime(rule.getBeginTime(), zone);
                LocalTime ruleEnd = new LocalTime(rule.getEndTime(), zone);

                DateTime shiftEnd = ruleEnd.toDateTime(currentDay);
                DateTime shiftStart = ruleStart.toDateTime(currentDay);

                if (shiftEnd.isBefore(shiftStart) || shiftEnd.isEqual(shiftStart)) {
                    shiftEnd = shiftEnd.plusDays(1);
                }
                Interval shiftInterval = new Interval(shiftStart, shiftEnd);

                // Set up buckets to handle previous days time accumulations
                BigDecimal hoursBeforeVirtualDay = BigDecimal.ZERO;

                // Check current day first block to see if start time gap from virtual day start is greater than max gap
                // if so, we can skip the previous day checks.
                TimeBlock firstBlockOfCurrentDay = null;
                for (TimeBlock b : ruleTimeBlocksCurr) {
                    if (timeBlockHasEarnCode(fromEarnGroup, b)) {
                        firstBlockOfCurrentDay = b;
                        break;
                    }
                }

                // Previous Day :: We have prior block container of nonzero size, and the previous day is active.
                Interval previousDayShiftInterval = new Interval(shiftStart.minusDays(1),
                        shiftEnd.minusDays(1));

                // Blank initialization pointer for picking which interval to pass to applyPremium()
                Interval evalInterval = null;
                if (ruleTimeBlocksPrev != null && ruleTimeBlocksPrev.size() > 0
                        && dayIsRuleActive(currentDay.minusDays(1), rule)) {
                    // Simple heuristic to see if we even need to worry about
                    // the Shift rule for this set of data.
                    if (shiftEnd.isAfter(virtualDay.getEnd())) {
                        // Compare first block of previous day with first block of current day for max gaptitude.
                        TimeBlock firstBlockOfPreviousDay = null;
                        for (TimeBlock b : ruleTimeBlocksPrev) {
                            if (timeBlockHasEarnCode(fromEarnGroup, b)) {
                                firstBlockOfPreviousDay = b;
                                break;
                            }
                        }
                        // Only if we actually have at least one block.
                        // Adding Assumption: We must have both a valid current and previous block. Max Gap can not be more than a virtual day.
                        // If this assumption does not hold, additional logic will be needed to iteratively go back in time to figure out which
                        // blocks are valid.
                        if ((firstBlockOfPreviousDay != null) && (firstBlockOfCurrentDay != null)) {
                            Interval previousBlockInterval = new Interval(
                                    firstBlockOfPreviousDay.getEndDateTime().withZone(zone),
                                    firstBlockOfCurrentDay.getBeginDateTime().withZone(zone));
                            Duration blockGapDuration = previousBlockInterval.toDuration();
                            BigDecimal bgdHours = TKUtils.convertMillisToHours(blockGapDuration.getMillis());
                            // if maxGap is 0, ignore gaps and assign shift to time blocks within the hours
                            if (rule.getMaxGap().compareTo(BigDecimal.ZERO) == 0
                                    || bgdHours.compareTo(rule.getMaxGap()) <= 0) {
                                // If we are here, we know we have at least one valid time block to pull some hours forward from.

                                // These are inversely sorted.
                                for (int i = 0; i < ruleTimeBlocksPrev.size(); i++) {
                                    TimeBlock b = ruleTimeBlocksPrev.get(i);
                                    if (timeBlockHasEarnCode(fromEarnGroup, b)) {
                                        Interval blockInterval = new Interval(
                                                b.getBeginDateTime().withZone(zone),
                                                b.getEndDateTime().withZone(zone));

                                        // Calculate Block Gap, the duration between clock outs and clock ins of adjacent time blocks.
                                        if (previousBlockInterval != null) {
                                            blockGapDuration = new Duration(b.getEndDateTime().withZone(zone),
                                                    previousBlockInterval.getStart());
                                            bgdHours = TKUtils
                                                    .convertMillisToHours(blockGapDuration.getMillis());
                                        }

                                        // Check Gap, if good, sum hours, if maxGap is 0, ignore gaps
                                        if (rule.getMaxGap().compareTo(BigDecimal.ZERO) == 0
                                                || bgdHours.compareTo(rule.getMaxGap()) <= 0) {
                                            // Calculate Overlap and add it to hours before virtual day bucket.
                                            if (blockInterval.overlaps(previousDayShiftInterval)) {
                                                BigDecimal hrs = TKUtils.convertMillisToHours(blockInterval
                                                        .overlap(previousDayShiftInterval).toDurationMillis());
                                                hoursBeforeVirtualDay = hoursBeforeVirtualDay.add(hrs);
                                            }

                                        } else {
                                            // Time blocks are reverse sorted, we can jump out as soon as the max gap is exceeded.
                                            break;
                                        }

                                        previousBlockInterval = blockInterval;

                                    }
                                }
                            } else {
                                // DO NOTHING!
                            }
                        }
                    }
                }

                BigDecimal hoursToApply = BigDecimal.ZERO;
                BigDecimal hoursToApplyPrevious = BigDecimal.ZERO;
                // If the hours before virtual day are less than or equal to
                // min hours, we have already applied the time, so we don't
                // set hoursToApplyPrevious
                if (hoursBeforeVirtualDay.compareTo(rule.getMinHours()) <= 0) {
                    // we need to apply these hours.
                    hoursToApplyPrevious = hoursBeforeVirtualDay;
                }

                //  Current Day

                TimeBlock previous = null; // Previous Time Block
                List<TimeBlock> accumulatedBlocks = new ArrayList<TimeBlock>(); // TimeBlocks we MAY or MAY NOT apply Shift Premium to.
                List<Interval> accumulatedBlockIntervals = new ArrayList<Interval>(); // To save recompute time when checking timeblocks for application we store them as we create them.
                // Iterate over sorted list, checking time boundaries vs Shift Intervals.
                long accumulatedMillis = TKUtils.convertHoursToMillis(hoursBeforeVirtualDay);

                boolean previousDayOnly = false; // IF the rule is not active today, but was on the previous day, we need to still look at time blocks.
                if (!dayIsRuleActive(currentDay, rule)) {
                    if (dayIsRuleActive(currentDay.minusDays(1), rule)) {
                        previousDayOnly = true;
                    } else {
                        // Nothing to see here, move to next rule.
                        continue;
                    }

                }

                /*
                 * We will touch each time block and accumulate time blocks that are applicable to
                 * the current rule we are on.
                 */

                // These blocks are only used for detail application
                // We don't want to pass along the previous pay period,
                // because we don't want to modify the time blocks on that
                // period. If null is passed, time will be placed on the
                // first block of the first period if the previous period
                // block had influence.
                List<TimeBlock> previousBlocksFiltered = (previousPayPeriodPrevDay) ? null
                        : filterBlocksByApplicableEarnGroup(fromEarnGroup, ruleTimeBlocksPrev);

                for (TimeBlock current : ruleTimeBlocksCurr) {
                    if (!timeBlockHasEarnCode(fromEarnGroup, current)) {
                        // TODO: WorkSchedule considerations somewhere in here?
                        continue;
                    }

                    Interval blockInterval = new Interval(current.getBeginDateTime().withZone(zone),
                            current.getEndDateTime().withZone(zone));

                    // Check both Intervals, since the time blocks could still
                    // be applicable to the previous day.  These two intervals should
                    // not have any overlap.
                    if (previousDayShiftInterval.overlaps(shiftInterval)) {
                        LOG.error("Interval of greater than 24 hours created in the rules processing.");
                        return;
                        //                     throw new RuntimeException("Interval of greater than 24 hours created in the rules processing.");
                    }

                    // This block of code handles cases where you have time
                    // that spills to multiple days and a shift rule that
                    // has a valid window on multiple consecutive days. Time
                    // must be applied with the correct shift interval.
                    Interval overlap = previousDayShiftInterval.overlap(blockInterval);
                    evalInterval = previousDayShiftInterval;
                    if (overlap == null) {
                        if (hoursToApplyPrevious.compareTo(BigDecimal.ZERO) > 0) {
                            // we have hours from previous day, and the shift
                            // window is going to move to current day.
                            // Need to apply this now, and move window forward
                            // for current time block.
                            BigDecimal accumHours = TKUtils.convertMillisToHours(accumulatedMillis);
                            this.applyAccumulatedWrapper(accumHours, evalInterval, accumulatedBlockIntervals,
                                    accumulatedBlocks, previousBlocksFiltered, hoursToApplyPrevious,
                                    hoursToApply, rule);
                            accumulatedMillis = 0L; // reset accumulated hours..
                            hoursToApply = BigDecimal.ZERO;
                            hoursToApplyPrevious = BigDecimal.ZERO;
                        }

                        // Because of our position in the loop, when we are at this point,
                        // we know we've passed any previous day shift intervals, so we can
                        // determine if we should skip the current day based on the boolean
                        // we set earlier.
                        if (previousDayOnly) {
                            continue;
                        }

                        overlap = shiftInterval.overlap(blockInterval);
                        evalInterval = shiftInterval;
                    }

                    // Time bucketing and application as normal:
                    //
                    if (overlap != null) {
                        // There IS overlap.
                        if (previous != null) {
                            // only check max gap if max gap of rule is not 0
                            if (rule.getMaxGap().compareTo(BigDecimal.ZERO) != 0
                                    && exceedsMaxGap(previous, current, rule.getMaxGap())) {
                                BigDecimal accumHours = TKUtils.convertMillisToHours(accumulatedMillis);
                                this.applyAccumulatedWrapper(accumHours, evalInterval,
                                        accumulatedBlockIntervals, accumulatedBlocks, previousBlocksFiltered,
                                        hoursToApplyPrevious, hoursToApply, rule);
                                accumulatedMillis = 0L; // reset accumulated hours..
                                hoursToApply = BigDecimal.ZERO;
                                hoursToApplyPrevious = BigDecimal.ZERO;
                            } else {
                                long millis = overlap.toDurationMillis();
                                accumulatedMillis += millis;
                                hoursToApply = hoursToApply.add(TKUtils.convertMillisToHours(millis));
                            }
                        } else {
                            // Overlap shift at first time block.
                            long millis = overlap.toDurationMillis();
                            accumulatedMillis += millis;
                            hoursToApply = hoursToApply.add(TKUtils.convertMillisToHours(millis));
                        }
                        accumulatedBlocks.add(current);
                        accumulatedBlockIntervals.add(blockInterval);
                        previous = current; // current can still apply to next.
                    } else {
                        // No Overlap / Outside of Rule
                        if (previous != null) {
                            BigDecimal accumHours = TKUtils.convertMillisToHours(accumulatedMillis);
                            this.applyAccumulatedWrapper(accumHours, evalInterval, accumulatedBlockIntervals,
                                    accumulatedBlocks, previousBlocksFiltered, hoursToApplyPrevious,
                                    hoursToApply, rule);
                            accumulatedMillis = 0L; // reset accumulated hours..
                            hoursToApply = BigDecimal.ZERO;
                            hoursToApplyPrevious = BigDecimal.ZERO;
                        }
                    }

                }

                // All time blocks are iterated over, check for remainders.
                // Check containers for time, and apply if needed.
                BigDecimal accumHours = TKUtils.convertMillisToHours(accumulatedMillis);
                this.applyAccumulatedWrapper(accumHours, evalInterval, accumulatedBlockIntervals,
                        accumulatedBlocks, previousBlocksFiltered, hoursToApplyPrevious, hoursToApply, rule);
            }
        }
        //    Keep track of previous as we move day by day.
        jobNumberToTimeBlocksPreviousDay = jobNumberToTimeBlocks;
        previousPayPeriodPrevDay = false;
    }

}

From source file:org.kuali.kpme.tklm.utils.TkTestUtils.java

License:Educational Community License

public static List<TimeBlock> createUniformTimeBlocks(DateTime start, int days, BigDecimal hours,
        String earnCode, Long jobNumber, Long workArea, Long task) {
    List<TimeBlock> blocks = new ArrayList<TimeBlock>();

    for (int i = 0; i < days; i++) {
        DateTime ci = start.plusDays(i);
        DateTime co = ci.plusHours(hours.intValue());
        TimeBlock block = TkTestUtils.createDummyTimeBlock(ci, co, hours, earnCode, jobNumber, workArea);
        block.setTask(task);//from ww w.j a  v a2 s.c o  m
        blocks.add(block);
    }

    return blocks;
}

From source file:org.kuali.kpme.tklm.utils.TkTestUtils.java

License:Educational Community License

public static TimeBlock createTimeBlock(TimesheetDocument timesheetDocument, int dayInPeriod, int numHours,
        String earnCode) {/* ww w  .  ja  va2 s  . co m*/
    TimeBlock timeBlock = new TimeBlock();
    DateTime beginPeriodDateTime = timesheetDocument.getCalendarEntry().getBeginPeriodFullDateTime();
    DateTime beginDateTime = beginPeriodDateTime.plusDays(dayInPeriod).withHourOfDay(8).withMinuteOfHour(0);
    DateTime endDateTime = beginDateTime.plusHours(numHours);

    timeBlock.setDocumentId(timesheetDocument.getDocumentId());
    timeBlock.setBeginDateTime(beginDateTime);
    timeBlock.setBeginTimeDisplay(beginDateTime);
    timeBlock.setEndDateTime(endDateTime);
    timeBlock.setEndTimeDisplay(endDateTime);
    timeBlock.setEarnCode(earnCode);
    timeBlock.setJobNumber(1L);
    timeBlock.setWorkArea(1234L);
    timeBlock.setTask(1L);
    timeBlock.setHours((new BigDecimal(numHours)).setScale(HrConstants.BIG_DECIMAL_SCALE,
            HrConstants.BIG_DECIMAL_SCALE_ROUNDING));

    return timeBlock;
}

From source file:org.kuali.kpme.tklm.utils.TkTestUtils.java

License:Educational Community License

/**
 * Helper method to generate time blocks suitable for db persistence in
 * unit tests.//from   ww  w .jav  a2 s  .  com
 */
public static List<TimeBlock> createUniformActualTimeBlocks(TimesheetDocument timesheetDocument,
        Assignment assignment, String earnCode, DateTime start, int days, BigDecimal hours, BigDecimal amount,
        String principalId) {
    TimeBlockService service = TkServiceLocator.getTimeBlockService();
    List<TimeBlock> blocks = new ArrayList<TimeBlock>();

    for (int i = 0; i < days; i++) {
        DateTime ci = start.plusDays(i);
        DateTime co = ci.plusHours(hours.intValue());

        blocks.addAll(service.buildTimeBlocks(assignment, earnCode, timesheetDocument, ci, co, hours, amount,
                false, false, principalId));
    }

    return blocks;
}

From source file:org.mythtv.service.guide.v25.ProgramGuideHelperV25.java

License:Open Source License

private static void downloadProgramGuide(final Context context, final LocationProfile locationProfile)
        throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
    Log.v(TAG, "downloadProgramGuide : enter");

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ProgramHelperV25.getInstance().deletePrograms(context, locationProfile, ops,
            ProgramConstants.CONTENT_URI_GUIDE, ProgramConstants.TABLE_NAME_GUIDE);
    RecordingHelperV25.getInstance().deleteRecordings(context, locationProfile, ops, ContentDetails.GUIDE);

    DateTime startDownloading = new DateTime();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int downloadDays = Integer.parseInt(sp.getString("preference_program_guide_days", "14"));
    Log.v(TAG, "downloadProgramGuide : downloadDays=" + downloadDays);

    DateTime start = new DateTime(DateTimeZone.getDefault()).withTimeAtStartOfDay();
    DateTime end = start.plusHours(3);
    for (int i = 0; i < ((downloadDays * 24) / 3); i++) {
        Log.i(TAG,/*from w  w  w .  j  av  a2  s  . com*/
                "downloadProgramGuide : starting download for [" + (i + 1) + " of " + ((downloadDays * 24) / 3)
                        + "] "
                        + DateUtils.getDateTimeUsingLocaleFormattingPretty(start,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType())
                        + ", end time=" + DateUtils.getDateTimeUsingLocaleFormattingPretty(end,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType()));

        EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile,
                "GetProgramGuide", String.valueOf(i));
        Log.d(TAG, "downloadProgramGuide : etag=" + etag.getValue());

        if (null == etag.getDate() || start.isAfter(etag.getDate())) {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has passed");

            ResponseEntity<ProgramGuide> responseEntity = mMythServicesTemplate.guideOperations()
                    .getProgramGuide(start, end, 1, null, false, etag);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 200 OK");
                ProgramGuide programGuide = responseEntity.getBody();

                if (null != programGuide) {

                    if (null != programGuide) {
                        load(context, locationProfile, programGuide);
                    }

                }

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setEndpoint("GetProgramGuide");
                    etag.setDataId(i);
                    etag.setDate(locationProfile.getNextMythFillDatabase());
                    etag.setMasterHostname(locationProfile.getHostname());
                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 304 Not Modified");

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            start = end;
            end = end.plusHours(3);

        } else {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has NOT passed!");
        }

    }

    Log.i(TAG, "downloadProgramGuide : interval=" + new Interval(startDownloading, new DateTime()).toString());

    Log.v(TAG, "downloadProgramGuide : exit");
}

From source file:org.mythtv.service.guide.v26.ProgramGuideHelperV26.java

License:Open Source License

private static void downloadProgramGuide(final Context context, final LocationProfile locationProfile)
        throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
    Log.v(TAG, "downloadProgramGuide : enter");

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ProgramHelperV26.getInstance().deletePrograms(context, locationProfile, ops,
            ProgramConstants.CONTENT_URI_GUIDE, ProgramConstants.TABLE_NAME_GUIDE);
    RecordingHelperV26.getInstance().deleteRecordings(context, locationProfile, ops, ContentDetails.GUIDE);

    DateTime startDownloading = new DateTime();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int downloadDays = Integer.parseInt(sp.getString("preference_program_guide_days", "14"));
    Log.v(TAG, "downloadProgramGuide : downloadDays=" + downloadDays);

    DateTime start = new DateTime(DateTimeZone.getDefault()).withTimeAtStartOfDay();
    DateTime end = start.plusHours(3);
    for (int i = 0; i < ((downloadDays * 24) / 3); i++) {
        Log.i(TAG,/*from ww  w  . j a  va 2 s. c  o m*/
                "downloadProgramGuide : starting download for [" + (i + 1) + " of " + ((downloadDays * 24) / 3)
                        + "] "
                        + DateUtils.getDateTimeUsingLocaleFormattingPretty(start,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType())
                        + ", end time=" + DateUtils.getDateTimeUsingLocaleFormattingPretty(end,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType()));

        EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile,
                "GetProgramGuide", String.valueOf(i));
        Log.d(TAG, "downloadProgramGuide : etag=" + etag.getValue());

        if (null == etag.getDate() || start.isAfter(etag.getDate())) {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has passed");

            ResponseEntity<ProgramGuide> responseEntity = mMythServicesTemplate.guideOperations()
                    .getProgramGuide(start, end, 1, null, false, etag);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 200 OK");
                ProgramGuide programGuide = responseEntity.getBody();

                if (null != programGuide) {

                    if (null != programGuide) {
                        load(context, locationProfile, programGuide);
                    }

                }

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setEndpoint("GetProgramGuide");
                    etag.setDataId(i);
                    etag.setDate(locationProfile.getNextMythFillDatabase());
                    etag.setMasterHostname(locationProfile.getHostname());
                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 304 Not Modified");

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            start = end;
            end = end.plusHours(3);

        } else {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has NOT passed!");
        }

    }

    Log.i(TAG, "downloadProgramGuide : interval=" + new Interval(startDownloading, new DateTime()).toString());

    Log.v(TAG, "downloadProgramGuide : exit");
}