List of usage examples for org.joda.time Interval contains
public boolean contains(long millisInstant)
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 ww w . ja va 2 s . c om*/ * * @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:controllers.ReportController.java
/** * Find all emergencies in a list that are within the given date range. * @param initialList list of emergencies to search through. * @param start start date of the interval. * @param end the end date of the interval. * @return // www . jav a 2s . c o m */ private static ArrayList<Emergency> findBetweenDates(ArrayList<Emergency> initialList, DateTime start, DateTime end) { ArrayList<Emergency> emergencyList = new ArrayList<>(); Interval interval = new Interval(start, end); for (Emergency instance : initialList) { if (interval.contains(instance.getDateCreated())) { emergencyList.add(instance); } } return emergencyList; }
From source file:cz.cesnet.shongo.controller.booking.recording.RecordingServiceReservationTask.java
@Override protected Reservation allocateReservation() throws SchedulerException { if (executable == null) { throw new IllegalStateException("Executable must be set."); }/* www.java2 s . c o m*/ Cache cache = getCache(); ResourceCache resourceCache = cache.getResourceCache(); Interval executableSlot = executable.getSlot(); // Check interval if (!executableSlot.contains(slot)) { throw new SchedulerReportSet.ExecutableServiceInvalidSlotException(executableSlot, slot); } // Check executable Set<Technology> technologies = new HashSet<Technology>(); if (executable instanceof RecordableEndpoint) { RecordableEndpoint recordableEndpoint = (RecordableEndpoint) executable; DeviceResource deviceResource = recordableEndpoint.getResource(); RecordingCapability recordingCapability = deviceResource.getCapability(RecordingCapability.class); // Set required technologies for recorder technologies.addAll(recordableEndpoint.getTechnologies()); // If room is not automatically recordable if (recordingCapability == null) { // Additional allocate something for executable if (executable instanceof RoomEndpoint) { // Allocate one room license for recording RoomProviderCapability roomProviderCapability = deviceResource .getCapabilityRequired(RoomProviderCapability.class); RoomReservationTask roomReservationTask = new RoomReservationTask(schedulerContext, this.slot); roomReservationTask.setRoomProviderCapability(roomProviderCapability); roomReservationTask.setParticipantCount(1); roomReservationTask.setAllocateRoomEndpoint(false); addChildReservation(roomReservationTask); } } else { // Check whether licenses aren't unlimited (otherwise the rooms are always recordable // and we shouldn't allocate the recording service for it) if (recordingCapability.getLicenseCount() == null) { throw new SchedulerReportSet.RoomEndpointAlwaysRecordableException( ObjectIdentifier.formatId(executable)); } } } else { throw new TodoImplementException( executable.getClass() + " doesn't implement " + RecordableEndpoint.class.getSimpleName() + "."); } // Find matching recording devices List<AvailableRecorder> availableRecorders = new LinkedList<AvailableRecorder>(); beginReport(new SchedulerReportSet.FindingAvailableResourceReport()); for (RecordingCapability recordingCapability : resourceCache.getCapabilities(RecordingCapability.class)) { DeviceResource deviceResource = recordingCapability.getDeviceResource(); if (this.resource != null && !deviceResource.getId().equals(this.resource.getId())) { continue; } if (technologies.size() > 0 && !deviceResource.hasTechnologies(technologies)) { continue; } // Get available recorder EntityManager entityManager = schedulerContext.getEntityManager(); ReservationManager reservationManager = new ReservationManager(entityManager); List<RecordingServiceReservation> roomReservations = reservationManager .getRecordingServiceReservations(recordingCapability, slot); schedulerContextState.applyReservations(recordingCapability.getId(), this.slot, roomReservations, RecordingServiceReservation.class); RangeSet<RecordingServiceReservation, DateTime> rangeSet = new RangeSet<RecordingServiceReservation, DateTime>(); for (RecordingServiceReservation roomReservation : roomReservations) { rangeSet.add(roomReservation, roomReservation.getSlotStart(), roomReservation.getSlotEnd()); } List<RangeSet.Bucket> roomBuckets = new LinkedList<RangeSet.Bucket>(); roomBuckets.addAll(rangeSet.getBuckets(slot.getStart(), slot.getEnd())); Collections.sort(roomBuckets, new Comparator<RangeSet.Bucket>() { @Override public int compare(RangeSet.Bucket roomBucket1, RangeSet.Bucket roomBucket2) { return -Double.compare(roomBucket1.size(), roomBucket2.size()); } }); int usedLicenseCount = 0; if (roomBuckets.size() > 0) { RangeSet.Bucket roomBucket = roomBuckets.get(0); usedLicenseCount = roomBucket.size(); } AvailableRecorder availableRecorder = new AvailableRecorder(recordingCapability, usedLicenseCount); if (Integer.valueOf(0).equals(availableRecorder.getAvailableLicenseCount())) { addReport(new SchedulerReportSet.ResourceRecordingCapacityExceededReport(deviceResource)); continue; } availableRecorders.add(availableRecorder); addReport(new SchedulerReportSet.ResourceReport(deviceResource)); } if (availableRecorders.size() == 0) { throw new SchedulerReportSet.ResourceNotFoundException(); } endReport(); // Sort recorders addReport(new SchedulerReportSet.SortingResourcesReport()); Collections.sort(availableRecorders, new Comparator<AvailableRecorder>() { @Override public int compare(AvailableRecorder first, AvailableRecorder second) { int result = -Double.compare(first.getFullnessRatio(), second.getFullnessRatio()); if (result != 0) { return result; } return 0; } }); // Allocate reservation in some matching recorder for (AvailableRecorder availableRecorder : availableRecorders) { RecordingCapability recordingCapability = availableRecorder.getRecordingCapability(); DeviceResource deviceResource = availableRecorder.getDeviceResource(); // Check whether alias provider can be allocated try { resourceCache.checkCapabilityAvailable(recordingCapability, this.slot, schedulerContext, this); } catch (SchedulerException exception) { addReport(exception.getReport()); continue; } beginReport(new SchedulerReportSet.AllocatingResourceReport(deviceResource)); // Allocate recording service RecordingService recordingService = new RecordingService(); recordingService.setRecordingCapability(recordingCapability); recordingService.setExecutable(executable); recordingService.setSlot(slot); if (enabled) { recordingService.setState(ExecutableService.State.PREPARED); } else { recordingService.setState(ExecutableService.State.NOT_ACTIVE); } // Allocate recording reservation RecordingServiceReservation recordingServiceReservation = new RecordingServiceReservation(); recordingServiceReservation.setRecordingCapability(recordingCapability); recordingServiceReservation.setSlot(slot); recordingServiceReservation.setExecutableService(recordingService); return recordingServiceReservation; } throw new SchedulerException(getCurrentReport()); }
From source file:cz.cesnet.shongo.controller.booking.room.RoomReservationTask.java
/** * Allocate {@link RoomEndpoint} for given {@code roomProviderVariant}. * * @param roomProviderVariant to be allocated * @param oldRoomEndpoint which is already allocated and which can be reallocated * @return (re)allocated {@link RoomEndpoint} or null if no executable should be allocated *///w w w . j a va 2s . co m private RoomEndpoint allocateRoomEndpoint(RoomProviderVariant roomProviderVariant, RoomEndpoint oldRoomEndpoint) throws SchedulerException { RoomProviderCapability roomProviderCapability = roomProviderVariant.getRoomProviderCapability(); Long deviceResourceId = roomProviderCapability.getDeviceResource().getId(); // Room configuration RoomConfiguration roomConfiguration = new RoomConfiguration(); roomConfiguration.setTechnologies(roomProviderVariant.getTechnologies()); roomConfiguration.setLicenseCount(roomProviderVariant.getLicenseCount()); for (RoomSetting roomSetting : roomSettings) { roomConfiguration.addRoomSetting(roomSetting.clone()); } AvailableExecutable<RoomEndpoint> availableRoomEndpoint = roomProviderVariant.getReusableRoomEndpoint(); // Reuse available room endpoint if (availableRoomEndpoint != null) { if (!availableRoomEndpoint.getType().equals(AvailableReservation.Type.REUSABLE)) { throw new RuntimeException("Available room endpoint should be reusable."); } Reservation originalReservation = availableRoomEndpoint.getOriginalReservation(); RoomEndpoint reusedRoomEndpoint = availableRoomEndpoint.getExecutable(); addReport(new SchedulerReportSet.ReservationReusingReport(originalReservation)); // Reuse available reservation which allocates the reusable room ExistingReservation existingReservation = new ExistingReservation(); existingReservation.setSlot(slot); existingReservation.setReusedReservation(originalReservation); addChildReservation(existingReservation); schedulerContextState.removeAvailableReservation(availableRoomEndpoint.getAvailableReservation()); // Reserve only the remaining capacity int allocatedLicenseCount = reusedRoomEndpoint.getRoomConfiguration().getLicenseCount(); int remainingLicenseCount = roomProviderVariant.getLicenseCount() - allocatedLicenseCount; roomConfiguration.setLicenseCount(remainingLicenseCount); addReport(new SchedulerReportSet.ExecutableReusingReport(reusedRoomEndpoint)); // Allocate room endpoint if (oldRoomEndpoint != null && oldRoomEndpoint instanceof UsedRoomEndpoint) { UsedRoomEndpoint usedRoomEndpoint = (UsedRoomEndpoint) oldRoomEndpoint; if (deviceResourceId.equals(usedRoomEndpoint.getResource().getId())) { // Reallocate existing room endpoint usedRoomEndpoint.clearAssignedAliases(); return usedRoomEndpoint; } else { throw new TodoImplementException("Schedule room migration."); } } else { // Create new used room endpoint UsedRoomEndpoint usedRoomEndpoint = new UsedRoomEndpoint(); usedRoomEndpoint.setReusedRoomEndpoint(reusedRoomEndpoint); usedRoomEndpoint.setRoomConfiguration(roomConfiguration); return usedRoomEndpoint; } } // Allocate UsedRoomEndpoint else if (reusedRoomEndpoint != null) { Interval reusedRoomEndpointSlot = reusedRoomEndpoint.getSlot(); // Check slot if (!reusedRoomEndpointSlot.contains(slot)) { throw new SchedulerReportSet.ExecutableInvalidSlotException(reusedRoomEndpoint, reusedRoomEndpointSlot); } // Check availability EntityManager entityManager = schedulerContext.getEntityManager(); ReservationManager reservationManager = new ReservationManager(entityManager); List<RoomReservation> reusedRoomEndpointReservations = reservationManager .getRoomReservationsByReusedRoomEndpoint(reusedRoomEndpoint, slot); schedulerContextState.applyAvailableReservations(reusedRoomEndpointReservations, RoomReservation.class); if (reusedRoomEndpointReservations.size() > 0) { RoomReservation roomReservation = reusedRoomEndpointReservations.get(0); Interval usageSlot = roomReservation.getSlot(); Reservation usageReservation = roomReservation.getTopReservation(); AbstractReservationRequest usageReservationRequest = usageReservation.getReservationRequest(); throw new SchedulerReportSet.ExecutableAlreadyUsedException(reusedRoomEndpoint, usageReservationRequest, usageSlot); } addReport(new SchedulerReportSet.ExecutableReusingReport(reusedRoomEndpoint)); // Allocate new UsedRoomEndpoint UsedRoomEndpoint usedRoomEndpoint = new UsedRoomEndpoint(); usedRoomEndpoint.setReusedRoomEndpoint(reusedRoomEndpoint); usedRoomEndpoint.setRoomConfiguration(roomConfiguration); return usedRoomEndpoint; } // Allocate ResourceRoomEndpoint else { addReport(new SchedulerReportSet.AllocatingExecutableReport()); if (oldRoomEndpoint != null && oldRoomEndpoint instanceof ResourceRoomEndpoint) { // Reallocate ResourceRoomEndpoint ResourceRoomEndpoint resourceRoomEndpoint = (ResourceRoomEndpoint) oldRoomEndpoint; if (deviceResourceId.equals(resourceRoomEndpoint.getResource().getId())) { // Reallocate existing room endpoint resourceRoomEndpoint.clearAssignedAliases(); return resourceRoomEndpoint; } else { throw new TodoImplementException("Schedule room migration."); } } else { // Reallocate new ResourceRoomEndpoint ResourceRoomEndpoint resourceRoomEndpoint = new ResourceRoomEndpoint(); resourceRoomEndpoint.setRoomProviderCapability(roomProviderCapability); resourceRoomEndpoint.setRoomConfiguration(roomConfiguration); return resourceRoomEndpoint; } } }
From source file:cz.cesnet.shongo.controller.scheduler.SchedulerContext.java
/** * @param allocation/*ww w . j a v a 2s. c o m*/ * @param slot * @return {@link Reservation} which can be reused from given {@code allocation} for {@code slot} * @throws SchedulerException */ public Reservation getReusableReservation(Allocation allocation, Interval slot) throws SchedulerException { AbstractReservationRequest reservationRequest = allocation.getReservationRequest(); // Find reusable reservation Reservation reusableReservation = null; Interval reservationInterval = null; for (Reservation reservation : allocation.getReservations()) { reservationInterval = reservation.getSlot(); if (reservationInterval.contains(slot)) { reusableReservation = reservation; break; } } if (reusableReservation == null) { throw new SchedulerReportSet.ReservationRequestInvalidSlotException(reservationRequest, reservationInterval); } // Check the reusable reservation ReservationManager reservationManager = new ReservationManager(entityManager); List<ExistingReservation> existingReservations = reservationManager .getExistingReservations(reusableReservation, slot); state.applyAvailableReservations(existingReservations, ExistingReservation.class); if (existingReservations.size() > 0) { ExistingReservation existingReservation = existingReservations.get(0); Interval usageSlot = existingReservation.getSlot(); Reservation usageReservation = existingReservation.getTopReservation(); AbstractReservationRequest usageReservationRequest = usageReservation.getReservationRequest(); throw new SchedulerReportSet.ReservationAlreadyUsedException(reusableReservation, reservationRequest, usageReservationRequest, usageSlot); } return reusableReservation; }
From source file:de.avanux.smartapplianceenabler.appliance.Schedule.java
License:Open Source License
/** * Returns the current or next timeframe if the remaining time is greater than maximum running time; otherwise the next timeframe is returned. * @param now the time reference//from w w w . j a va 2s. com * @param schedules the list of timeframes to choose from (current timeframe has to be first) * @param onlyAlreadyStarted consider only timeframe intervals already started * @param onlySufficient if true consider timeframe already started only if time to interval end exceeds min running time * @return the next timeframe becoming valid or null */ public static TimeframeInterval getCurrentOrNextTimeframeInterval(LocalDateTime now, List<Schedule> schedules, boolean onlyAlreadyStarted, boolean onlySufficient) { if (schedules == null || schedules.size() == 0) { return null; } Map<Long, TimeframeInterval> startDelayOfTimeframeInterval = new TreeMap<>(); for (Schedule schedule : schedules) { Timeframe timeframe = schedule.getTimeframe(); timeframe.setSchedule(schedule); List<TimeframeInterval> timeframeIntervals = timeframe.getIntervals(now); for (TimeframeInterval timeframeInterval : timeframeIntervals) { Interval interval = timeframeInterval.getInterval(); if (interval.contains(now.toDateTime())) { // interval already started ... if (onlySufficient) { if (now.plusSeconds(schedule.getMaxRunningTime()).plusSeconds(additionalRunningTime) .isBefore(new LocalDateTime(interval.getEnd()))) { // ... with remaining running time sufficient return timeframeInterval; } } else { return timeframeInterval; } } else if (!onlyAlreadyStarted) { // interval starts in future startDelayOfTimeframeInterval.put(interval.getStartMillis() - now.toDateTime().getMillis(), timeframeInterval); } } } if (startDelayOfTimeframeInterval.size() > 0) { Long startDelay = startDelayOfTimeframeInterval.keySet().iterator().next(); return startDelayOfTimeframeInterval.get(startDelay); } return null; }
From source file:de.avanux.smartapplianceenabler.appliance.Schedule.java
License:Open Source License
/** * Returns schedules starting within the given interval. * @param considerationInterval/*from w w w . j ava 2s . com*/ * @return a (possibly empty) list of timeframes */ public static List<TimeframeInterval> findTimeframeIntervals(LocalDateTime now, Interval considerationInterval, List<Schedule> schedules) { List<TimeframeInterval> matchingTimeframeIntervals = new ArrayList<>(); if (schedules != null) { for (Schedule schedule : schedules) { Timeframe timeframe = schedule.getTimeframe(); List<TimeframeInterval> timeframeIntervals = timeframe.getIntervals(now); for (TimeframeInterval timeframeInterval : timeframeIntervals) { if (considerationInterval.contains(timeframeInterval.getInterval().getStart())) { matchingTimeframeIntervals.add(timeframeInterval); } } } } return matchingTimeframeIntervals; }
From source file:de.hpi.bpmn2_0.replay.TimeUtilities.java
License:Open Source License
private static Integer getIntervalCount(Interval interval, Map<Interval, Integer> intervalMap) { for (Interval mapInterval : intervalMap.keySet()) { if (mapInterval.contains(interval)) { return intervalMap.get(mapInterval); }//from w ww. ja va 2s. co m } return 0; }
From source file:de.rwth.idsg.xsharing.router.core.routing.strategy.inavailability.bike.DefaultBikeInavailabilityStrategy.java
License:Open Source License
@Override public boolean overlaps(int stayTime, RouteLegList legs, SharingStation startStation, RouteLegWrapper bikeWrapper) {// ww w . j a v a 2 s .c o m // We always set stay time. Depending on DurationCheckStrategy it will be used or not. bikeWrapper.setStayTime(stayTime); // ------------------------------------------------------------------------- // 1) If in future, be optimistic and assume always available // ------------------------------------------------------------------------- Interval nowTimeWindow = DateTimeUtils.getNowTimeWindow(); DateTime timeAtStartStation = legs.getAfterLastLeg(); boolean startIsNow = nowTimeWindow.contains(timeAtStartStation); if (!startIsNow) { return false; } // ------------------------------------------------------------------------- // 2) Check actual intervals for availability // ------------------------------------------------------------------------- int duration = durationCheckStrategy.getDurationToCheck(bikeWrapper); Interval interval = legs.getIntervalAfterPossibleLeg(duration); return overlaps(startStation, interval); }
From source file:de.rwth.idsg.xsharing.router.core.routing.strategy.inavailability.bike.WithReturnBikeInavailabilityStrategy.java
License:Open Source License
/** * start | end | overlaps?/*w ww. j av a 2s . co m*/ * ---------+--------+-------------------------------------------------- * now | now | check inavailability at both stations * now | future | check inavailability at start station, be optimistic about end station * future | now | false. cannot happen, chronologically not possible * future | future | false. both in future => be optimistic, no check */ @Override public boolean overlaps(int stayTime, RouteLegList legs, SharingStation startStation, RouteLegWrapper bikeWrapper, SharingStation endStation, RouteLegWrapper walkWrapper) { // We always set stay time. Depending on DurationCheckStrategy it will be used or not. walkWrapper.setStayTime(stayTime); // ------------------------------------------------------------------------- // 1) If in future, be optimistic and assume always available // ------------------------------------------------------------------------- Interval nowTimeWindow = getNowTimeWindow(); DateTime timeAtStartStation = legs.getAfterLastLeg(); boolean startIsNow = nowTimeWindow.contains(timeAtStartStation); if (!startIsNow) { return false; } // ------------------------------------------------------------------------- // 2) Check actual intervals for availability // ------------------------------------------------------------------------- int bikeLegDuration = bikeWrapper.getLeg().getDuration(); int durationAfterStartStation = bikeLegDuration + durationCheckStrategy.getDurationToCheck(walkWrapper); DateTime timeAtReturnStation = timeAtStartStation.plusSeconds(durationAfterStartStation); boolean endIsNow = nowTimeWindow.contains(timeAtReturnStation); if (endIsNow) { // Check bike availability for "HinFahrt" at start station and "RckFahrt" at end station return overlapsAtStation(legs, startStation, bikeLegDuration) || overlapsAtStation(legs, endStation, durationAfterStartStation); } else { // Check bike availability for "HinFahrt" at start station return overlapsAtStation(legs, startStation, bikeLegDuration); } }