Example usage for org.joda.time Interval Interval

List of usage examples for org.joda.time Interval Interval

Introduction

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

Prototype

public Interval(Object interval, Chronology chronology) 

Source Link

Document

Constructs a time interval by converting or copying from another object, overriding the chronology.

Usage

From source file:com.wealdtech.utils.WealdInterval.java

License:Open Source License

/**
 * Obtain a Joda {@link Interval} from this Weald interval.
 * <p/>//from  w w  w .j a  va 2  s  . c  o m
 * <b>N.B.</b>
 * This loses information about the timezone in which the end datetime resides so should be used with caution.
 * @return A Joda interval
 */
@JsonIgnore
public Interval getInterval() {
    return new Interval(this.start, this.end);
}

From source file:com.xpn.xwiki.criteria.impl.Period.java

License:Open Source License

/**
 * Creates a new time Period from the specified start time to the specified end time. Both ends of the period are
 * given as time stamps (the number of milliseconds from 1970-01-01T00:00:00Z)
 * /*w w w .  java  2 s.c o  m*/
 * @param start The period start as the number of milliseconds from 1970-01-01T00:00:00Z
 * @param end The period end as the number of milliseconds from 1970-01-01T00:00:00Z
 */
public Period(long start, long end) {
    this.interval = new Interval(start, end);
}

From source file:com.yahoo.bard.webservice.data.metric.mappers.PartialDataResultSetMapper.java

License:Apache License

/**
 * Remove result records which are missing and not marked as volatile.
 * Any bucket which is partially volatile is not removed.  In the case of the All granularity, all data is
 * considered to be in a single bucket./*www .  j  a v a2s. c o m*/
 *
 * @param result   The result row being transformed
 * @param schema   The schema for that result
 * @return Null if the bucket this result falls in is missing but not volatile
 */
@Override
public Result map(Result result, ResultSetSchema schema) {
    Granularity grain = schema.getGranularity();

    if (grain.equals(AllGranularity.INSTANCE)) {
        return !volatileIntervalSupply.get().isEmpty() || missingIntervals.isEmpty() ? result : null;
    }

    // Currently any Granularity which isn't 'ALL' must currently be a TimeGrain
    Interval resultInterval = new Interval(result.getTimeStamp(), ((TimeGrain) grain).getPeriod());

    return getMissingNotVolatile().stream().anyMatch((it) -> it.overlaps(resultInterval)) ? null : result;
}

From source file:com.yahoo.bard.webservice.data.volatility.TimeOffsetVolatileIntervalsFunction.java

License:Apache License

@Override
public SimplifiedIntervalList getVolatileIntervals() {
    long now = currentTimeMillis.getAsLong();
    return new SimplifiedIntervalList(Collections.singletonList(new Interval(now - past, now + future)));
}

From source file:com.yahoo.bard.webservice.util.DateTimeUtils.java

License:Apache License

/**
 * Merge all contiguous and overlapping intervals in a set together and return the set with the merged intervals.
 *
 * @param unmergedIntervals A set of intervals that may abut or overlap
 *
 * @return The set of merged intervals/*ww  w  .j a  va2s . c  om*/
 */
public static Set<Interval> mergeIntervalSet(Set<Interval> unmergedIntervals) {
    // Create a self sorting set of intervals
    TreeSet<Interval> sortedIntervals = new TreeSet<>(IntervalStartComparator.INSTANCE);

    for (Interval mergingInterval : unmergedIntervals) {
        Iterator<Interval> it = sortedIntervals.iterator();
        while (it.hasNext()) {
            Interval sortedInterval = it.next();
            if (mergingInterval.overlaps(sortedInterval) || mergingInterval.abuts(sortedInterval)) {
                // Remove the interval being merged with
                it.remove();
                // find start and end of new interval
                DateTime start = (mergingInterval.getStart().isBefore(sortedInterval.getStart()))
                        ? mergingInterval.getStart()
                        : sortedInterval.getStart();
                DateTime end = (mergingInterval.getEnd().isAfter(sortedInterval.getEnd()))
                        ? mergingInterval.getEnd()
                        : sortedInterval.getEnd();
                mergingInterval = new Interval(start, end);
            }
        }
        sortedIntervals.add(mergingInterval);
    }
    return sortedIntervals;
}

From source file:com.yahoo.bard.webservice.util.DateTimeUtils.java

License:Apache License

/**
 * Slices the intervals into smaller intervals of the timeGrain duration.
 *
 * @param interval  interval to be sliced
 * @param timeGrain  size of the slice//from w ww.j av a2  s. c  o m
 *
 * @return list of intervals obtained by slicing the larger interval
 *
 * @throws java.lang.IllegalArgumentException if the interval is not an even multiple of the time grain
 */
public static List<Interval> sliceIntervals(Interval interval, TimeGrain timeGrain) {
    // TODO: Refactor me to use a Period
    DateTime intervalEnd = interval.getEnd();
    DateTime sliceStart = interval.getStart();
    DateTime periodStart = timeGrain.roundFloor(sliceStart);

    if (!sliceStart.equals(periodStart)) {
        LOG.info("Interval {} is not aligned to TimeGrain {} starting {}", interval, timeGrain, periodStart);
        throw new IllegalArgumentException("Interval must be aligned to the TimeGrain starting " + periodStart);
    }

    List<Interval> intervalSlices = new ArrayList<>();
    while (sliceStart.isBefore(intervalEnd)) {
        // Find the end of the next slice
        DateTime sliceEnd = DateTimeUtils.addTimeGrain(sliceStart, timeGrain);

        // Make the next slice
        Interval slicedInterval = new Interval(sliceStart, sliceEnd);

        // Make sure that our slice is fully contained within our interval
        if (!interval.contains(slicedInterval)) {
            LOG.info("Interval {} is not a multiple of TimeGrain {}", interval, timeGrain);
            throw new IllegalArgumentException("Interval must be a multiple of the TimeGrain");
        }

        // Add the slice
        intervalSlices.add(slicedInterval);

        // Move the slicer forward
        sliceStart = sliceEnd;
    }
    LOG.debug("Sliced interval {} into {} slices of {} grain", interval, intervalSlices.size(), timeGrain);

    return intervalSlices;
}

From source file:com.yahoo.bard.webservice.util.IntervalPeriodIterator.java

License:Apache License

@Override
public Interval next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }//w  w w.  j a  v a  2  s .  co m
    position += 1;
    DateTime nextPosition = ObjectUtils.min(intervalEnd, boundaryAt(position));
    Interval result = new Interval(currentPosition, nextPosition);
    currentPosition = nextPosition;
    return result;
}

From source file:com.yahoo.bard.webservice.util.SimplifiedIntervalList.java

License:Apache License

/**
 * Given a sorted linked list of intervals, add the following interval to the end, merging the incoming interval
 * to any tail intervals which overlap or abut with it.
 * <p>/*  www  . j  a  v  a2s  . c  o m*/
 * In the case where added intervals are at the end of the list, this is efficient. In the case where they are not,
 * this degrades to an insertion sort.
 *
 * @param interval  The interval to be merged and added to this list
 */
private void appendWithMerge(Interval interval) {
    // Do not store empty intervals
    if (interval.toDurationMillis() == 0) {
        return;
    }

    if (isEmpty()) {
        addLast(interval);
        return;
    }
    final Interval previous = peekLast();

    // If this interval does not belong at the end, removeLast until it does
    if (interval.getStart().isBefore(previous.getStart())) {
        mergeInner(interval);
        return;
    }

    if (previous.gap(interval) != null) {
        addLast(interval);
        return;
    }
    removeLast();
    Interval newEnd = new Interval(Math.min(previous.getStartMillis(), interval.getStartMillis()),
            Math.max(previous.getEndMillis(), interval.getEndMillis()));
    addLast(newEnd);
}

From source file:com.yahoo.bard.webservice.util.SimplifiedIntervalList.java

License:Apache License

/**
 * Return the subtracted list of all intervals in this that are not in that.
 *
 * @param that  A simplified list of intervals
 *
 * @return A new simplified interval list whose intervals are all subintervals of this and not that
 *///from  ww w .  j ava  2s. c o  m
public SimplifiedIntervalList subtract(SimplifiedIntervalList that) {
    Iterator<Interval> theseIntervals = this.iterator();
    Interval thisCurrent = getNextIfAvailable.apply(theseIntervals);

    if (thisCurrent == null) {
        return new SimplifiedIntervalList();
    }

    Iterator<Interval> thoseIntervals = that.iterator();

    Interval thatCurrent = getNextIfAvailable.apply(thoseIntervals);
    List<Interval> collected = new ArrayList<>();

    while (thisCurrent != null && thatCurrent != null) {
        if (thisCurrent.isBefore(thatCurrent)) {
            // Non overlapping intervals are simply collected
            collected.add(thisCurrent);
        } else if (thisCurrent.overlaps(thatCurrent)) {
            // Take any part of the source interval that lies before an overlap
            if (thisCurrent.getStart().isBefore(thatCurrent.getStart())) {
                collected.add(new Interval(thisCurrent.getStart(), thatCurrent.getStart()));
            }
            // Truncate out any overlap from the source interval and continue
            if (!thisCurrent.getEnd().isBefore(thatCurrent.getEnd())) {
                thisCurrent = new Interval(thatCurrent.getEnd(), thisCurrent.getEnd());
            }
        }
        // Advance to the next interval to consider
        if (thisCurrent.isBefore(thatCurrent.getEnd())) {
            thisCurrent = getNextIfAvailable.apply(theseIntervals);
        } else {
            thatCurrent = getNextIfAvailable.apply(thoseIntervals);
        }
    }
    if (thatCurrent == null) {
        collected.add(thisCurrent);
        while (theseIntervals.hasNext()) {
            collected.add(theseIntervals.next());
        }
    }
    return new SimplifiedIntervalList(collected);
}

From source file:com.yahoo.bard.webservice.web.apirequest.ApiRequestImpl.java

License:Apache License

/**
 * Extracts the set of intervals from the api request.
 *
 * @param now The 'now' for which time macros will be relatively calculated
 * @param apiIntervalQuery  API string containing the intervals in ISO 8601 format, values separated by ','.
 * @param granularity  The granularity to generate the date based on period or macros.
 * @param dateTimeFormatter  The formatter to parse date time interval segments
 *
 * @return Set of jodatime interval objects.
 * @throws BadApiRequestException if the requested interval is not found.
 *//*w ww . j av a2 s . c om*/
protected static List<Interval> generateIntervals(DateTime now, String apiIntervalQuery,
        Granularity granularity, DateTimeFormatter dateTimeFormatter) throws BadApiRequestException {
    try (TimedPhase timer = RequestLog.startTiming("GeneratingIntervals")) {
        List<Interval> generated = new ArrayList<>();
        if (apiIntervalQuery == null || apiIntervalQuery.equals("")) {
            LOG.debug(INTERVAL_MISSING.logFormat());
            throw new BadApiRequestException(INTERVAL_MISSING.format());
        }
        List<String> apiIntervals = Arrays.asList(apiIntervalQuery.split(","));
        // Split each interval string into the start and stop instances, parse them, and add the interval to the
        // list

        for (String apiInterval : apiIntervals) {
            String[] split = apiInterval.split("/");

            // Check for both a start and a stop
            if (split.length != 2) {
                String message = "Start and End dates are required.";
                LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, message));
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, message));
            }

            try {
                String start = split[0].toUpperCase(Locale.ENGLISH);
                String end = split[1].toUpperCase(Locale.ENGLISH);
                //If start & end intervals are period then marking as invalid interval.
                //Becacuse either one should be macro or actual date to generate an interval
                if (start.startsWith("P") && end.startsWith("P")) {
                    LOG.debug(INTERVAL_INVALID.logFormat(start));
                    throw new BadApiRequestException(INTERVAL_INVALID.format(apiInterval));
                }

                Interval interval;
                //If start interval is period, then create new interval with computed end date
                //possible end interval could be next,current, date
                if (start.startsWith("P")) {
                    interval = new Interval(Period.parse(start),
                            getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                    //If end string is period, then create an interval with the computed start date
                    //Possible start & end string could be a macro or an ISO 8601 DateTime
                } else if (end.startsWith("P")) {
                    interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                            Period.parse(end));
                } else {
                    //start and end interval could be either macros or actual datetime
                    interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                            getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                }

                // Zero length intervals are invalid
                if (interval.toDuration().equals(Duration.ZERO)) {
                    LOG.debug(INTERVAL_ZERO_LENGTH.logFormat(apiInterval));
                    throw new BadApiRequestException(INTERVAL_ZERO_LENGTH.format(apiInterval));
                }
                generated.add(interval);
            } catch (IllegalArgumentException iae) {
                // Handle poor JodaTime message (special case)
                String internalMessage = iae.getMessage().equals("The end instant must be greater the start")
                        ? "The end instant must be greater than the start instant"
                        : iae.getMessage();
                LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, internalMessage), iae);
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, internalMessage),
                        iae);
            }
        }
        return generated;
    }
}