Example usage for org.joda.time Interval overlaps

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

Introduction

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

Prototype

public boolean overlaps(ReadableInterval interval) 

Source Link

Document

Does this time interval overlap the specified time interval.

Usage

From source file:com.tmathmeyer.sentinel.models.client.net.CachingDisplayableClient.java

License:Open Source License

/**
 * Gets all visible events in the range [from..to]
 * //from  www .ja  va 2s .c  o m
 * @param from
 * @param to
 * @return list of visible events
 */
public List<T> getRange(DateTime from, DateTime to) {
    validateCache();
    // set up to filter events based on booleans in MainPanel
    List<T> filteredEvents = new ArrayList<T>();
    final Interval range = new Interval(from, to);

    // loop through and add only if isProjectEvent() matches corresponding
    // boolean
    for (T e : cache.values()) {
        if (range.overlaps(e.getInterval()) && filter(e)) {
            filteredEvents.add(e);
        }
    }
    return filteredEvents;
}

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//w w w .jav  a 2s  .  c o m
 */
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.SimplifiedIntervalList.java

License:Apache License

/**
 * Return the intersection of all subintervals in two interval lists.
 *
 * @param that  A simplified list of intervals
 *
 * @return A new simplified interval list whose intervals are all subintervals of this and that.
 *///from  w  ww.j a  v  a 2s. c  o m
public SimplifiedIntervalList intersect(SimplifiedIntervalList that) {
    Iterator<Interval> theseIntervals = this.iterator();
    Iterator<Interval> thoseIntervals = that.iterator();
    Interval thisCurrent = getNextIfAvailable.apply(theseIntervals);
    Interval thatCurrent = getNextIfAvailable.apply(thoseIntervals);
    List<Interval> collected = new ArrayList<>();

    while (thisCurrent != null && thatCurrent != null) {
        if (thisCurrent.overlaps(thatCurrent)) {
            collected.add(thisCurrent.overlap(thatCurrent));
        }
        if (thisCurrent.isBefore(thatCurrent.getEnd())) {
            thisCurrent = getNextIfAvailable.apply(theseIntervals);
        } else {
            thatCurrent = getNextIfAvailable.apply(thoseIntervals);
        }
    }
    return new SimplifiedIntervalList(collected);
}

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  2  s .  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:cz.cesnet.shongo.controller.api.rpc.ReservationServiceImpl.java

@Override
public Object checkAvailability(AvailabilityCheckRequest request) {
    checkNotNull("request", request);
    SecurityToken securityToken = request.getSecurityToken();
    authorization.validate(securityToken);

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    ReservationRequestManager reservationRequestManager = new ReservationRequestManager(entityManager);
    try {/*from  w  w w.ja  v  a  2s.  c o  m*/
        // We must check only the future (because scheduler allocates only in future)
        DateTime minimumDateTime = DateTime.now();
        Interval slot = request.getSlot();
        if (slot.getEnd().isBefore(minimumDateTime)) {
            throw new ControllerReportSet.ReservationRequestEmptyDurationException();
        }
        if (slot.getStart().isBefore(minimumDateTime)) {
            slot = slot.withStart(minimumDateTime);
        }

        Specification specificationApi = request.getSpecification();
        cz.cesnet.shongo.controller.booking.specification.Specification specification = null;
        Interval allocationSlot = slot;
        if (specificationApi != null) {
            specification = cz.cesnet.shongo.controller.booking.specification.Specification
                    .createFromApi(specificationApi, entityManager);
            if (specification instanceof SpecificationIntervalUpdater) {
                SpecificationIntervalUpdater intervalUpdater = (SpecificationIntervalUpdater) specification;
                allocationSlot = intervalUpdater.updateInterval(allocationSlot, minimumDateTime);
            }
        }

        // Create scheduler context
        SchedulerContext schedulerContext = new SchedulerContext(DateTime.now(), cache, entityManager,
                new AuthorizationManager(entityManager, authorization));
        schedulerContext.setPurpose(request.getPurpose());

        // Ignore reservations for already allocated reservation request
        SchedulerContextState schedulerContextState = schedulerContext.getState();
        String ignoredReservationRequestId = request.getIgnoredReservationRequestId();
        if (ignoredReservationRequestId != null) {
            ObjectIdentifier objectId = ObjectIdentifier.parse(ignoredReservationRequestId,
                    ObjectType.RESERVATION_REQUEST);
            cz.cesnet.shongo.controller.booking.request.AbstractReservationRequest ignoredReservationRequest = reservationRequestManager
                    .get(objectId.getPersistenceId());
            for (cz.cesnet.shongo.controller.booking.reservation.Reservation reservation : ignoredReservationRequest
                    .getAllocation().getReservations()) {
                if (allocationSlot.overlaps(reservation.getSlot())) {
                    schedulerContextState.addAvailableReservation(reservation,
                            AvailableReservation.Type.REALLOCATABLE);
                }
            }

            for (cz.cesnet.shongo.controller.booking.request.ReservationRequest childReservationRequest : ignoredReservationRequest
                    .getAllocation().getChildReservationRequests()) {
                for (cz.cesnet.shongo.controller.booking.reservation.Reservation reservation : childReservationRequest
                        .getAllocation().getReservations()) {
                    if (reservation.getSlot().overlaps(slot)) {
                        schedulerContextState.addAvailableReservation(reservation,
                                AvailableReservation.Type.REALLOCATABLE);
                    }
                }
            }
        }

        try {
            // Check reservation request reusability
            String reservationRequestId = request.getReservationRequestId();
            if (reservationRequestId != null) {
                ObjectIdentifier objectId = ObjectIdentifier.parse(reservationRequestId,
                        ObjectType.RESERVATION_REQUEST);
                cz.cesnet.shongo.controller.booking.request.AbstractReservationRequest reservationRequest = reservationRequestManager
                        .get(objectId.getPersistenceId());
                schedulerContext.setReusableAllocation(reservationRequest.getAllocation(), slot);
            }

            // Check specification availability
            if (specification != null) {
                if (specification instanceof ReservationTaskProvider) {
                    try {
                        entityManager.getTransaction().begin();
                        ReservationTaskProvider reservationTaskProvider = (ReservationTaskProvider) specification;
                        ReservationTask reservationTask = reservationTaskProvider
                                .createReservationTask(schedulerContext, slot);
                        reservationTask.perform();
                    } finally {
                        entityManager.getTransaction().rollback();
                    }
                } else {
                    throw new SchedulerReportSet.SpecificationNotAllocatableException(specification);
                }
            }
        } catch (SchedulerException exception) {
            // Specification cannot be allocated or reservation request cannot be reused in requested time slot
            return exception.getReport().toAllocationStateReport(
                    authorization.isAdministrator(securityToken) ? Report.UserType.DOMAIN_ADMIN
                            : Report.UserType.USER);
        }

        // Request is available
        return Boolean.TRUE;
    } finally {
        entityManager.close();
    }
}

From source file:cz.PA165.vozovyPark.controller.DriveController.java

public boolean isIntervalFree(DriveDTO drive) {
    Interval range = new Interval(drive.getDateFrom(), drive.getDateTo());
    VehicleDTO vehicle = drive.getVehicle();
    for (DriveDTO d : driveService.findAll()) {
        Interval i = new Interval(d.getDateFrom(), d.getDateTo());
        if (range.overlaps(i) && d.getVehicle().equals(vehicle)) {
            return false;
        }/*from ww w. ja  va2 s  .  com*/
    }
    return true;
}

From source file:de.rwth.idsg.xsharing.router.utils.DateTimeUtils.java

License:Open Source License

public static boolean contains(List<Interval> intervals, Interval query) {
    try {/*from  w w  w  .j a  v  a2s .c  o m*/
        for (Interval in : intervals) {
            if (in.overlaps(query)) {
                return true;
            }
        }
        return false;
    } catch (Exception e) {
        log.warn("Failed to check whether {} overlaps with {}", query, intervals);
        return false;
    }
}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.models.client.CachingDisplayableClient.java

License:Open Source License

/**
 * Gets all visible events in the range [from..to]
 * @param from/*  ww  w.ja v  a2  s  .  c  o m*/
 * @param to
 * @return list of visible events
 */
protected List<T> getRange(DateTime from, DateTime to) {
    validateCache();
    // set up to filter events based on booleans in MainPanel
    List<T> filteredEvents = new ArrayList<T>();
    final Interval range = new Interval(from, to);

    // loop through and add only if isProjectEvent() matches corresponding
    // boolean
    for (T e : cache.values()) {
        if (range.overlaps(e.getInterval()) && filter(e)) {
            filteredEvents.add(e);
        }
    }
    return filteredEvents;
}

From source file:io.coala.dsol.util.DsolUtil.java

License:Apache License

/**
 * @return overlap of specified interval within replication run period
 *         (after warm-up and before run length)
 *///w w w. ja  v  a2  s.c o m
public static Interval crop(final Interval interval, final Treatment treatment) {
    final Interval runPeriod = getRunInterval(treatment);
    if (interval.overlaps(runPeriod)) {
        final long croppedStart = Math.max(interval.getStartMillis(), runPeriod.getStartMillis());
        final long croppedEnd = Math.min(interval.getEndMillis(), runPeriod.getEndMillis());
        return new Interval(croppedStart, croppedEnd);
    }
    return interval;
}

From source file:io.druid.indexing.overlord.IndexerMetadataStorageAdapter.java

License:Apache License

public int deletePendingSegments(String dataSource, Interval deleteInterval) {
    // Check the given interval overlaps the interval(minCreatedDateOfActiveTasks, MAX)
    final Optional<DateTime> minCreatedDateOfActiveTasks = taskStorageQueryAdapter.getActiveTasks().stream()
            .map(task -> Preconditions.checkNotNull(taskStorageQueryAdapter.getCreatedTime(task.getId()),
                    "Can't find the createdTime for task[%s]", task.getId()))
            .min(Comparator.naturalOrder());

    final Interval activeTaskInterval = new Interval(minCreatedDateOfActiveTasks.orElse(DateTimes.MAX),
            DateTimes.MAX);/*  w  w  w .  j av  a2s .co  m*/

    Preconditions.checkArgument(!deleteInterval.overlaps(activeTaskInterval),
            "Cannot delete pendingSegments because there is at least one active task created at %s",
            activeTaskInterval.getStart());

    return indexerMetadataStorageCoordinator.deletePendingSegments(dataSource, deleteInterval);
}