Example usage for org.joda.time Interval getStart

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

Introduction

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

Prototype

public DateTime getStart() 

Source Link

Document

Gets the start of this time interval, which is inclusive, as a DateTime.

Usage

From source file:cz.cesnet.shongo.client.web.models.RoomModel.java

/**
 * Constructor.//from   ww w .j a v  a  2  s  .co m
 *
 * @param roomExecutable    to initialize the {@link RoomModel} from
 * @param cacheProvider     which can be used for initializing
 * @param messageProvider   sets the {@link #messageProvider}
 * @param executableService which can be used for initializing
 * @param userSession       which can be used for initializing
 * @param services          specifies whether {@link #recordingService} should be loaded
 */
public RoomModel(AbstractRoomExecutable roomExecutable, CacheProvider cacheProvider,
        MessageProvider messageProvider, ExecutableService executableService, UserSession userSession,
        boolean services) {
    SecurityToken securityToken = cacheProvider.getSecurityToken();

    // Setup room
    this.messageProvider = messageProvider;
    this.id = roomExecutable.getId();
    this.slot = roomExecutable.getOriginalSlot();
    Interval slot = roomExecutable.getSlot();
    this.slotBefore = null;
    if (!slot.getStart().equals(this.slot.getStart())) {
        this.slotBefore = new Period(slot.getStart(), this.slot.getStart());
    }
    this.slotAfter = null;
    if (!slot.getEnd().equals(this.slot.getEnd())) {
        this.slotAfter = new Period(this.slot.getEnd(), slot.getEnd());
    }
    this.technology = TechnologyModel.find(roomExecutable.getTechnologies());
    this.aliases = roomExecutable.getAliases();
    for (Alias alias : roomExecutable.getAliases()) {
        if (alias.getType().equals(AliasType.ROOM_NAME)) {
            this.name = alias.getValue();
            break;
        }
    }
    loadRoomSettings(roomExecutable);

    // Add room participants from used executable
    if (roomExecutable instanceof UsedRoomExecutable) {
        UsedRoomExecutable usageExecutable = (UsedRoomExecutable) roomExecutable;
        AbstractRoomExecutable usedExecutable = (AbstractRoomExecutable) cacheProvider
                .getExecutable(usageExecutable.getReusedRoomExecutableId());
        RoomExecutableParticipantConfiguration participants = usedExecutable.getParticipantConfiguration();
        for (AbstractParticipant participant : participants.getParticipants()) {
            addParticipant(new Participant(usedExecutable.getId(), participant, cacheProvider));
        }
    }

    // Add room participants from executable
    for (AbstractParticipant participant : roomExecutable.getParticipantConfiguration().getParticipants()) {
        addParticipant(new Participant(this.id, participant, cacheProvider));
    }

    // Room type and license count and active usage
    this.licenseCount = roomExecutable.getLicenseCount();
    this.hasRecordingService = roomExecutable.hasRecordingService();
    this.hasRecordings = roomExecutable.hasRecordings();
    if (this.licenseCount == 0) {
        this.type = RoomType.PERMANENT_ROOM;

        // Get license count from active usage
        ExecutableListRequest usageRequest = new ExecutableListRequest();
        usageRequest.setSecurityToken(securityToken);
        usageRequest.setRoomId(this.id);
        usageRequest.setSort(ExecutableListRequest.Sort.SLOT);
        usageRequest.setSortDescending(true);
        ListResponse<ExecutableSummary> usageSummaries = executableService.listExecutables(usageRequest);
        for (ExecutableSummary usageSummary : usageSummaries) {
            Interval usageSlot = usageSummary.getSlot();
            if (usageSummary.getState().isAvailable()) {
                UsedRoomExecutable usage = (UsedRoomExecutable) cacheProvider
                        .getExecutable(usageSummary.getId());
                this.licenseCount = usage.getLicenseCount();
                this.licenseCountUntil = usageSlot.getEnd();
                this.usageId = usage.getId();
                this.usageState = usage.getState();
                RoomExecutableParticipantConfiguration participants = usage.getParticipantConfiguration();
                for (AbstractParticipant participant : participants.getParticipants()) {
                    addParticipant(new Participant(this.usageId, participant, cacheProvider));
                }
                loadRoomSettings(usage);
                if (services) {
                    this.recordingService = getRecordingService(executableService, securityToken, this.usageId);
                    this.hasRecordingService = this.recordingService != null;
                }
                break;
            }
        }
    } else {
        // Capacity or ad-hoc room
        if (roomExecutable instanceof UsedRoomExecutable) {
            this.type = RoomType.USED_ROOM;
        } else {
            this.type = RoomType.ADHOC_ROOM;
        }
        if (services) {
            this.recordingService = getRecordingService(executableService, securityToken, this.id);
            this.hasRecordingService = this.recordingService != null;
        }
    }

    // Room state
    this.state = RoomState.fromRoomState(roomExecutable.getState(), roomExecutable.getLicenseCount(),
            usageState);
    if (!this.state.isAvailable() && userSession.isAdministrationMode()) {
        this.stateReport = roomExecutable.getStateReport().toString(messageProvider.getLocale(),
                messageProvider.getTimeZone());
    }
}

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. jav a 2  s . com*/
        // 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.cesnet.shongo.controller.api.rpc.ReservationServiceImpl.java

@Override
public ListResponse<ReservationRequestSummary> listReservationRequests(ReservationRequestListRequest request) {
    checkNotNull("request", request);
    SecurityToken securityToken = request.getSecurityToken();
    authorization.validate(securityToken);

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    try {/*from ww w . ja v  a  2  s  .  c o m*/
        QueryFilter queryFilter = new QueryFilter("reservation_request_summary", true);

        // List only reservation requests which is current user permitted to read
        queryFilter.addFilterId("allocation_id", authorization, securityToken, Allocation.class,
                ObjectPermission.READ);

        // List only reservation requests which are requested (but latest versions of them)
        if (request.getReservationRequestIds().size() > 0) {
            queryFilter.addFilter("reservation_request_summary.id IN ("
                    + " SELECT allocation.abstract_reservation_request_id"
                    + " FROM abstract_reservation_request"
                    + " LEFT JOIN allocation ON allocation.id = abstract_reservation_request.allocation_id"
                    + " WHERE abstract_reservation_request.id IN(:reservationRequestIds)" + ")");
            Set<Long> reservationRequestIds = new HashSet<Long>();
            for (String reservationRequestId : request.getReservationRequestIds()) {
                reservationRequestIds
                        .add(ObjectIdentifier.parseId(reservationRequestId, ObjectType.RESERVATION_REQUEST));
            }
            queryFilter.addFilterParameter("reservationRequestIds", reservationRequestIds);
        }
        // Else other filters
        else {
            // List only latest versions of a reservation requests (no it's modifications or deleted requests)
            queryFilter.addFilter("reservation_request_summary.state = 'ACTIVE'");

            // List only child reservation requests for specified parent reservation request
            String parentReservationRequestId = request.getParentReservationRequestId();
            if (parentReservationRequestId != null) {
                queryFilter.addFilter("reservation_request.parent_allocation_id IN("
                        + " SELECT DISTINCT abstract_reservation_request.allocation_id"
                        + " FROM abstract_reservation_request "
                        + " WHERE abstract_reservation_request.id = :parentReservationRequestId)");
                queryFilter.addFilterParameter("parentReservationRequestId",
                        ObjectIdentifier.parseId(parentReservationRequestId, ObjectType.RESERVATION_REQUEST));
            } else {
                // List only top reservation requests (no child requests created for a set of reservation requests)
                queryFilter.addFilter("reservation_request.parent_allocation_id IS NULL");
            }

            // List only reservation requests which specifies given technologies
            if (request.getSpecificationTechnologies().size() > 0) {
                queryFilter.addFilter("reservation_request_summary.id IN ("
                        + "  SELECT DISTINCT abstract_reservation_request.id"
                        + "  FROM abstract_reservation_request"
                        + "  LEFT JOIN specification_technologies ON specification_technologies.specification_id = "
                        + "            abstract_reservation_request.specification_id"
                        + "  WHERE specification_technologies.technologies IN(:technologies))");
                queryFilter.addFilterParameter("technologies", request.getSpecificationTechnologies());
            }

            // List only reservation requests which has specification of given classes
            if (request.getSpecificationTypes().size() > 0) {
                StringBuilder specificationTypes = new StringBuilder();
                for (ReservationRequestSummary.SpecificationType type : request.getSpecificationTypes()) {
                    if (specificationTypes.length() > 0) {
                        specificationTypes.append(",");
                    }
                    specificationTypes.append("'");
                    specificationTypes.append(type);
                    specificationTypes.append("'");
                }
                queryFilter.addFilter("specification_summary.type IN(" + specificationTypes.toString() + ")");
            }

            // Filter specification resource id
            String specificationResourceId = request.getSpecificationResourceId();
            if (specificationResourceId != null) {
                queryFilter.addFilter("specification_summary.resource_id = :resource_id");
                queryFilter.addFilterParameter("resource_id",
                        ObjectIdentifier.parseId(specificationResourceId, ObjectType.RESOURCE));
            }

            String reusedReservationRequestId = request.getReusedReservationRequestId();
            if (reusedReservationRequestId != null) {
                if (reusedReservationRequestId.equals(ReservationRequestListRequest.FILTER_EMPTY)) {
                    // List only reservation requests which hasn't reused any reservation request
                    queryFilter.addFilter("reservation_request_summary.reused_reservation_request_id IS NULL");
                } else if (reusedReservationRequestId.equals(ReservationRequestListRequest.FILTER_NOT_EMPTY)) {
                    // List only reservation requests which reuse any reservation request
                    queryFilter
                            .addFilter("reservation_request_summary.reused_reservation_request_id IS NOT NULL");
                } else {
                    // List only reservation requests which reuse given reservation request
                    Long persistenceId = ObjectIdentifier.parseId(reusedReservationRequestId,
                            ObjectType.RESERVATION_REQUEST);
                    queryFilter.addFilter("reservation_request_summary.reused_reservation_request_id = "
                            + ":reusedReservationRequestId");
                    queryFilter.addFilterParameter("reusedReservationRequestId", persistenceId);
                }
            }

            AllocationState allocationState = request.getAllocationState();
            if (allocationState != null) {
                queryFilter.addFilter("reservation_request_summary.allocation_state = :allocationState");
                queryFilter.addFilterParameter("allocationState", allocationState.toString());
            }

            Interval interval = request.getInterval();
            if (interval != null) {
                queryFilter.addFilter("reservation_request_summary.slot_start < :intervalEnd");
                queryFilter.addFilter("reservation_request_summary.slot_end > :intervalStart");
                queryFilter.addFilterParameter("intervalStart", interval.getStart().toDate());
                queryFilter.addFilterParameter("intervalEnd", interval.getEnd().toDate());
            }

            String userId = request.getUserId();
            if (userId != null) {
                queryFilter.addFilter("reservation_request_summary.created_by = :userId"
                        + " OR reservation_request_summary.updated_by = :userId"
                        + " OR reservation_request_summary.allocation_id IN("
                        + "   SELECT acl_object_identity.object_id FROM acl_entry"
                        + "   LEFT JOIN acl_identity ON acl_identity.id = acl_entry.acl_identity_id"
                        + "   LEFT JOIN acl_object_identity ON acl_object_identity.id = acl_entry.acl_object_identity_id"
                        + "   LEFT JOIN acl_object_class ON acl_object_class.id = acl_object_identity.acl_object_class_id"
                        + "   WHERE acl_object_class.class = 'RESERVATION_REQUEST' AND acl_identity.principal_id = :userId)");
                queryFilter.addFilterParameter("userId", userId);
            }

            String participantUserId = request.getParticipantUserId();
            if (participantUserId != null) {
                queryFilter.addFilter("reservation_request_summary.allocation_id IN("
                        + " SELECT reservation.allocation_id FROM reservation"
                        + " LEFT JOIN room_endpoint_participants ON room_endpoint_participants.room_endpoint_id = reservation.executable_id"
                        + " LEFT JOIN person_participant ON person_participant.id = abstract_participant_id"
                        + " LEFT JOIN person ON person.id = person_participant.person_id"
                        + " WHERE person.user_id = :participantUserId)");
                queryFilter.addFilterParameter("participantUserId", participantUserId);
            }

            String search = request.getSearch();
            if (search != null) {
                queryFilter.addFilter("LOWER(reservation_request_summary.description) LIKE :search"
                        + " OR LOWER(specification_summary.alias_room_name) LIKE :search"
                        + " OR LOWER(reused_specification_summary.alias_room_name) LIKE :search");
                queryFilter.addFilterParameter("search", "%" + search.toLowerCase() + "%");
            }
        }

        // Query order by
        String queryOrderBy;
        ReservationRequestListRequest.Sort sort = request.getSort();
        if (sort != null) {
            switch (sort) {
            case ALIAS_ROOM_NAME:
                queryOrderBy = "specification_summary.alias_room_name";
                break;
            case DATETIME:
                queryOrderBy = "reservation_request_summary.created_at";
                break;
            case REUSED_RESERVATION_REQUEST:
                queryOrderBy = "reservation_request_summary.reused_reservation_request_id IS NOT NULL";
                break;
            case ROOM_PARTICIPANT_COUNT:
                queryOrderBy = "specification_summary.room_participant_count";
                break;
            case SLOT:
                queryOrderBy = "reservation_request_summary.slot_end";
                break;
            case SLOT_NEAREST:
                queryOrderBy = "reservation_request_summary.slot_nearness_priority, reservation_request_summary.slot_nearness_value";
                break;
            case STATE:
                queryOrderBy = "reservation_request_summary.allocation_state, reservation_request_summary.executable_state";
                break;
            case TECHNOLOGY:
                queryOrderBy = "specification_summary.technologies";
                break;
            case TYPE:
                queryOrderBy = "specification_summary.type";
                break;
            case USER:
                queryOrderBy = "reservation_request_summary.created_by";
                break;
            default:
                throw new TodoImplementException(sort);
            }
        } else {
            queryOrderBy = "reservation_request_summary.id";
        }
        Boolean sortDescending = request.getSortDescending();
        sortDescending = (sortDescending != null ? sortDescending : false);
        if (sortDescending) {
            queryOrderBy = queryOrderBy + " DESC";
        }

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("filter", queryFilter.toQueryWhere());
        parameters.put("order", queryOrderBy);
        String query = NativeQuery.getNativeQuery(NativeQuery.RESERVATION_REQUEST_LIST, parameters);

        ListResponse<ReservationRequestSummary> response = new ListResponse<ReservationRequestSummary>();
        List<Object[]> records = performNativeListRequest(query, queryFilter, request, response, entityManager);
        for (Object[] record : records) {
            ReservationRequestSummary reservationRequestSummary = getReservationRequestSummary(record);
            response.addItem(reservationRequestSummary);
        }
        return response;
    } finally {
        entityManager.close();
    }
}

From source file:cz.cesnet.shongo.controller.api.rpc.ReservationServiceImpl.java

@Override
public ListResponse<ReservationSummary> listReservations(ReservationListRequest request) {
    checkNotNull("request", request);
    SecurityToken securityToken = request.getSecurityToken();
    authorization.validate(securityToken);

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    try {//w ww .ja  v  a  2s  .  c  o m
        QueryFilter queryFilter = new QueryFilter("reservation_summary");

        // List only reservations which is current user permitted to read or which allocates resource owned by the user
        Set<Long> readableReservationIds = authorization.getEntitiesWithPermission(securityToken,
                cz.cesnet.shongo.controller.booking.reservation.Reservation.class, ObjectPermission.READ);
        if (readableReservationIds != null) {
            Set<Long> ownedResourceIds = authorization.getEntitiesWithRole(securityToken,
                    cz.cesnet.shongo.controller.booking.resource.Resource.class, ObjectRole.OWNER);
            StringBuilder filterBuilder = new StringBuilder();
            filterBuilder.append("1=0");
            if (!readableReservationIds.isEmpty()) {
                filterBuilder.append(" OR reservation_summary.id IN(:readableReservationIds)");
                queryFilter.addFilterParameter("readableReservationIds", readableReservationIds);
            }
            if (!ownedResourceIds.isEmpty()) {
                filterBuilder.append(" OR reservation_summary.resource_id IN(:ownedResourceIds)");
                queryFilter.addFilterParameter("ownedResourceIds", ownedResourceIds);

            }
            queryFilter.addFilter(filterBuilder.toString());
        }

        // List only reservations of requested types
        if (request.getReservationTypes().size() > 0) {
            StringBuilder reservationTypes = new StringBuilder();
            for (ReservationSummary.Type reservationType : request.getReservationTypes()) {
                if (reservationTypes.length() > 0) {
                    reservationTypes.append(",");
                }
                reservationTypes.append("'");
                reservationTypes.append(reservationType);
                reservationTypes.append("'");
            }
            queryFilter.addFilter("reservation_summary.type IN(" + reservationTypes.toString() + ")");
        }

        // List only reservations which allocates requested resource
        if (!request.getResourceIds().isEmpty()) {
            queryFilter.addFilter("reservation_summary.resource_id IN(:resourceIds)");
            Set<Long> resourceIds = new HashSet<Long>();
            for (String resourceId : request.getResourceIds()) {
                resourceIds.add(ObjectIdentifier.parseId(resourceId, ObjectType.RESOURCE));
            }
            queryFilter.addFilterParameter("resourceIds", resourceIds);
        }

        // List only reservations in requested interval
        Interval interval = request.getInterval();
        if (interval != null) {
            queryFilter.addFilter("reservation_summary.slot_start < :slotEnd");
            queryFilter.addFilter("reservation_summary.slot_end > :slotStart");
            queryFilter.addFilterParameter("slotStart", interval.getStart().toDate());
            queryFilter.addFilterParameter("slotEnd", interval.getEnd().toDate());
        }

        // Sort query part
        String queryOrderBy;
        ReservationListRequest.Sort sort = request.getSort();
        if (sort != null) {
            switch (sort) {
            case SLOT:
                queryOrderBy = "reservation_summary.slot_start";
                break;
            default:
                throw new TodoImplementException(sort);
            }
        } else {
            queryOrderBy = "reservation_summary.id";
        }
        Boolean sortDescending = request.getSortDescending();
        sortDescending = (sortDescending != null ? sortDescending : false);
        if (sortDescending) {
            queryOrderBy = queryOrderBy + " DESC";
        }

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("filter", queryFilter.toQueryWhere());
        parameters.put("order", queryOrderBy);
        String query = NativeQuery.getNativeQuery(NativeQuery.RESERVATION_LIST, parameters);

        ListResponse<ReservationSummary> response = new ListResponse<ReservationSummary>();
        List<Object[]> records = performNativeListRequest(query, queryFilter, request, response, entityManager);
        for (Object[] record : records) {
            ReservationSummary reservationSummary = getReservationSummary(record);
            response.addItem(reservationSummary);
        }
        return response;
    } finally {
        entityManager.close();
    }
}

From source file:cz.cesnet.shongo.controller.booking.room.RoomEndpoint.java

/**
 * @param slot// w  ww  .j  a  v  a 2s.c o m
 * @param slotBefore
 * @param slotAfter
 * @return original slot from given {@code slot} and {@code slotBefore} and {@code slotAfter}
 */
public static Interval getOriginalSlot(Interval slot, Period slotBefore, Period slotAfter) {
    DateTime start = slot.getStart().plus(slotBefore);
    DateTime end = slot.getEnd().minus(slotAfter);
    if (end.isBefore(start)) {
        end = start;
    }
    return new Interval(start, end);
}

From source file:cz.cesnet.shongo.controller.booking.room.RoomReservationTask.java

/**
 * Constructor./* w w w . j  a  va2  s  .  c o m*/
 *
 * @param schedulerContext  sets the {@link #schedulerContext}
 * @param slot              sets the {@link #slot}
 * @param slotMinutesBefore sets the {@link #slotMinutesBefore}
 * @param slotMinutesAfter  sets the {@link #slotMinutesAfter}
 */
public RoomReservationTask(SchedulerContext schedulerContext, Interval slot, int slotMinutesBefore,
        int slotMinutesAfter) {
    super(schedulerContext, new Interval(slot.getStart().minusMinutes(slotMinutesBefore),
            slot.getEnd().plusMinutes(slotMinutesAfter)));
    this.slotMinutesBefore = slotMinutesBefore;
    this.slotMinutesAfter = slotMinutesAfter;
}

From source file:cz.cesnet.shongo.controller.scheduler.SchedulerContext.java

/**
 * @param roomProviderCapability//from   w  w w . j ava 2s.c o m
 * @param slot
 * @param reservationTask
 * @return {@link AvailableRoom} for given {@code roomProviderCapability} in given {@code interval}
 */
public AvailableRoom getAvailableRoom(RoomProviderCapability roomProviderCapability, Interval slot,
        ReservationTask reservationTask) {
    int usedLicenseCount = 0;
    ResourceCache resourceCache = cache.getResourceCache();
    if (resourceCache.isResourceAvailable(roomProviderCapability.getResource(), slot, this, reservationTask)) {
        ReservationManager reservationManager = new ReservationManager(entityManager);
        List<RoomReservation> roomReservations = reservationManager.getRoomReservations(roomProviderCapability,
                slot);
        state.applyReservations(roomProviderCapability.getId(), slot, roomReservations, RoomReservation.class);
        RangeSet<RoomReservation, DateTime> rangeSet = new RangeSet<RoomReservation, DateTime>() {
            @Override
            protected Bucket<DateTime, RoomReservation> createBucket(DateTime rangeValue) {
                return new RoomBucket(rangeValue);
            }
        };
        for (RoomReservation roomReservation : roomReservations) {
            rangeSet.add(roomReservation, roomReservation.getSlotStart(), roomReservation.getSlotEnd());
        }

        List<RoomBucket> roomBuckets = new LinkedList<RoomBucket>();
        roomBuckets.addAll(rangeSet.getBuckets(slot.getStart(), slot.getEnd(), RoomBucket.class));
        Collections.sort(roomBuckets, new Comparator<RoomBucket>() {
            @Override
            public int compare(RoomBucket roomBucket1, RoomBucket roomBucket2) {
                return -Double.compare(roomBucket1.getLicenseCount(), roomBucket2.getLicenseCount());
            }
        });
        if (roomBuckets.size() > 0) {
            RoomBucket roomBucket = roomBuckets.get(0);
            usedLicenseCount = roomBucket.getLicenseCount();
        }
    } else {
        usedLicenseCount = roomProviderCapability.getLicenseCount();
    }
    return new AvailableRoom(roomProviderCapability, usedLicenseCount);
}

From source file:de.alpharogroup.date.IntervalUtils.java

License:Open Source License

public static boolean isBetween(final Interval timeRange, final Interval timeRangeToCheck) {
    if (timeRange.getStart() != null && !timeRange.getStart().isAfter(timeRangeToCheck.getEnd())) {
        if (timeRange.getEnd() != null && !timeRange.getEnd().isBefore(timeRangeToCheck.getStart())) {
            return true;
        }/*ww  w .  j a  v a2s.  c o m*/
    }
    return false;
}

From source file:de.avanux.smartapplianceenabler.appliance.DayTimeframe.java

License:Open Source License

@Override
public List<TimeframeInterval> getIntervals(LocalDateTime now) {
    List<TimeframeInterval> intervals = new ArrayList<>();
    if (start != null && end != null) {
        Interval interval = buildMidnightAdjustedInterval(now);
        List<Integer> dowValues = getDaysOfWeekValues();
        // if today's interval already ended we ignore today
        int dayOffset = (interval.getEnd().isBefore(now.toDateTime()) ? 1 : 0);
        for (int i = dayOffset; i < 7 + dayOffset; i++) {
            DateTime timeFrameStart = interval.getStart().plusDays(i);
            DateTime timeFrameEnd = interval.getEnd().plusDays(i);
            if (dowValues != null) {
                int dow = timeFrameStart.getDayOfWeek();
                if (dowValues.contains(DOW_HOLIDAYS) && isHoliday(timeFrameStart.toLocalDate())) {
                    dow = DOW_HOLIDAYS;/*from  ww  w. ja  v  a 2 s .c  om*/
                }
                if (dowValues.contains(dow)) {
                    intervals.add(new TimeframeInterval(this, new Interval(timeFrameStart, timeFrameEnd)));
                }
            } else {
                intervals.add(new TimeframeInterval(this, new Interval(timeFrameStart, timeFrameEnd)));
            }
        }
    }
    return intervals;
}

From source file:de.avanux.smartapplianceenabler.semp.webservice.SempController.java

License:Open Source License

protected de.avanux.smartapplianceenabler.semp.webservice.Timeframe createSempTimeFrame(
        ApplianceLogger applianceLogger, String deviceId, Schedule schedule, Interval interval,
        long minRunningTime, long maxRunningTime, LocalDateTime now) {
    Long earliestStart = 0l;//w w w  . j av  a  2s .c  o  m
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();
    if (start.isAfter(now.toDateTime())) {
        earliestStart = Double.valueOf(new Interval(now.toDateTime(), start).toDurationMillis() / 1000)
                .longValue();
    }
    LocalDateTime nowBeforeEnd = new LocalDateTime(now);
    if (now.toDateTime().isAfter(end)) {
        nowBeforeEnd = now.minusHours(24);
    }
    Long latestEnd = Double.valueOf(new Interval(nowBeforeEnd.toDateTime(), end).toDurationMillis() / 1000)
            .longValue();
    return createSempTimeFrame(applianceLogger, deviceId, earliestStart, latestEnd, minRunningTime,
            maxRunningTime);
}