Example usage for org.joda.time Interval getEnd

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

Introduction

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

Prototype

public DateTime getEnd() 

Source Link

Document

Gets the end of this time interval, which is exclusive, as a DateTime.

Usage

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

License:Apache License

/**
 * Constructor.//from ww  w.j av a 2  s.  co m
 *
 * @param period  The period to divide the interval by
 * @param baseInterval  The raw interval which is to be divided
 */
public IntervalPeriodIterator(@NotNull ReadablePeriod period, Interval baseInterval) {
    this.period = period;
    intervalStart = baseInterval.getStart();
    intervalEnd = baseInterval.getEnd();
    position = 0;
    currentPosition = boundaryAt(0);

    // Chronology accepts null periods, we must not do so or this iterator is non-terminating
    if (period == null) {
        throw new IllegalArgumentException("Period cannot be null");
    }
}

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

License:Apache License

/**
 * Find a valid timegrain for the interval based on the start and end date of the interval.
 *
 * @param interval  The interval to find a timegrain for.
 * @return the valid timegrain spanned by the interval.
 *//*w ww . j a  v  a2  s  .  c o m*/
public static Optional<TimeGrain> getTimeGrain(Interval interval) {
    return StandardGranularityParser.getDefaultGrainMap().values().stream()
            .filter(granularity -> granularity instanceof TimeGrain).map(granularity -> (TimeGrain) granularity)
            .filter(timeGrain -> timeGrain.aligns(interval))
            .filter(timeGrain -> interval.getStart().plus(timeGrain.getPeriod()).equals(interval.getEnd()))
            .findFirst();
}

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.
 *///ww  w.  jav  a  2s  .co 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 w w w . j a v a 2 s .co 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:csv.CSVCreator.java

/**
 * Converts a duration object to a descriptive string of that object
 *
 * @param interval/*from  www.j a  v  a2  s  . c o m*/
 * @return a descriptive string of the given input
 */
private String convertDurationToString(Interval interval) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();

    DateTimeFormatter df = DateTimeFormat.forPattern("y-MM-dd");

    return df.print(start) + " - " + df.print(end);
}

From source file:cz.cesnet.shongo.client.web.controllers.RoomController.java

/**
 * Handle data request for list of rooms.
 *///from ww w . j  ava 2  s.co  m
@RequestMapping(value = ClientWebUrl.ROOM_LIST_DATA, method = RequestMethod.GET)
@ResponseBody
public Map handleRoomListData(Locale locale, DateTimeZone timeZone, SecurityToken securityToken,
        @RequestParam(value = "start", required = false) Integer start,
        @RequestParam(value = "count", required = false) Integer count,
        @RequestParam(value = "sort", required = false, defaultValue = "SLOT") ExecutableListRequest.Sort sort,
        @RequestParam(value = "sort-desc", required = false, defaultValue = "true") boolean sortDescending,
        @RequestParam(value = "room-id", required = false) String roomId,
        @RequestParam(value = "participant-user-id", required = false) String participantUserId) {
    ExecutableListRequest request = new ExecutableListRequest();
    request.setSecurityToken(securityToken);
    request.setStart(start);
    request.setCount(count);
    request.setSort(sort);
    request.setSortDescending(sortDescending);
    if (roomId != null) {
        request.addType(ExecutableSummary.Type.USED_ROOM);
        request.setRoomId(roomId);
    } else {
        if (participantUserId != null) {
            request.setRoomLicenseCount(ExecutableListRequest.FILTER_NON_ZERO);
            request.addType(ExecutableSummary.Type.USED_ROOM);
        }
        request.addType(ExecutableSummary.Type.ROOM);
    }
    request.setParticipantUserId(participantUserId);
    ListResponse<ExecutableSummary> response = executableService.listExecutables(request);

    // Build response
    DateTimeFormatter formatter = DateTimeFormatter.getInstance(DateTimeFormatter.SHORT, locale, timeZone);
    List<Map<String, Object>> items = new LinkedList<Map<String, Object>>();
    for (ExecutableSummary executableSummary : response.getItems()) {
        Map<String, Object> item = new HashMap<String, Object>();
        item.put("id", executableSummary.getId());
        item.put("type", executableSummary.getType());
        item.put("name", executableSummary.getRoomName());
        item.put("description", executableSummary.getRoomDescription());

        TechnologyModel technology = TechnologyModel.find(executableSummary.getRoomTechnologies());
        if (technology != null) {
            item.put("technology", technology);
            item.put("technologyTitle", technology.getTitle());
        }

        RoomState roomState = RoomState.fromRoomState(executableSummary.getState(),
                executableSummary.getRoomLicenseCount(), executableSummary.getRoomUsageState());
        RoomType roomType = RoomType.fromExecutableSummary(executableSummary);

        item.put("state", roomState);
        item.put("stateAvailable", roomState.isAvailable());
        item.put("stateMessage", roomState.getMessage(messageSource, locale, roomType));
        item.put("stateHelp", roomState.getHelp(messageSource, locale, roomType));

        Interval slot = executableSummary.getRoomUsageSlot();
        if (slot == null) {
            slot = executableSummary.getSlot();
        }
        item.put("slot", formatter.formatInterval(slot));

        boolean isDeprecated;
        switch (roomState) {
        case STARTED:
        case STARTED_AVAILABLE:
            isDeprecated = false;
            break;
        default:
            isDeprecated = slot.getEnd().isBeforeNow();
            break;
        }
        item.put("isDeprecated", isDeprecated);

        Integer licenseCount = executableSummary.getRoomUsageLicenseCount();
        if (licenseCount == null) {
            licenseCount = executableSummary.getRoomLicenseCount();
        }
        item.put("licenseCount", licenseCount);
        item.put("licenseCountMessage", messageSource.getMessage("views.room.participants.value",
                new Object[] { licenseCount }, locale));

        item.put("usageCount", executableSummary.getRoomUsageCount());

        items.add(item);
    }
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("start", response.getStart());
    data.put("count", response.getCount());
    data.put("sort", sort);
    data.put("sort-desc", sortDescending);
    data.put("items", items);
    return data;
}

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

/**
 * Constructor./*from ww  w.java2  s.  c  o  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 {/* w  ww  .  j a  v a 2 s. c  om*/
        // 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 {/*www. j ava  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  w w .  j  a v  a 2  s.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();
    }
}