Example usage for org.hibernate Criteria list

List of usage examples for org.hibernate Criteria list

Introduction

In this page you can find the example usage for org.hibernate Criteria list.

Prototype

public List list() throws HibernateException;

Source Link

Document

Get the results.

Usage

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java

License:Open Source License

/**
 * Loads all the bookings for the day into memory.
 * /* w w w  .  j  av a  2s .  c o  m*/
 * @return ses database session
 */
@SuppressWarnings("unchecked")
public void fullLoad(Session ses) {
    if (this.hasFullLoad)
        return;

    int num = 0;

    /* Load all the rigs that have bookings today. */
    for (Rig rig : (List<Rig>) ses.createCriteria(Rig.class).list()) {
        if (this.rigBookings.containsKey(rig.getName()))
            continue;

        if ((num = (Integer) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE))
                .add(this.addDayRange()).add(Restrictions.eq("resourceType", ResourcePermission.RIG_PERMISSION))
                .add(Restrictions.eq("rig", rig)).setProjection(Projections.rowCount()).uniqueResult()) == 0)
            continue;

        this.logger.debug(
                "Rig " + rig.getName() + " has " + num + " bookings, so loading it up for full day load.");
        this.getRigBookings(rig, ses);
    }

    /* Load all the rig types that have bookings today. */
    Criteria qu = ses.createCriteria(RigType.class);
    if (this.typeTargets.size() > 0)
        qu.add(Restrictions.not(Restrictions.in("name", this.typeTargets.keySet())));
    for (RigType type : (List<RigType>) qu.list()) {
        if (this.typeTargets.containsKey(type.getName()))
            continue;

        if ((num = (Integer) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE))
                .add(this.addDayRange())
                .add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION))
                .add(Restrictions.eq("rigType", type)).setProjection(Projections.rowCount())
                .uniqueResult()) == 0)
            continue;

        this.logger.debug("Rig type " + type.getName() + " has " + num + " bookings, so loading it up for"
                + " full day load.");

        Set<Rig> rigs = type.getRigs();
        if (rigs.size() == 0) {
            this.logger.warn("Rig type " + type.getName() + " has " + num + " bookings but not rigs so they all"
                    + " will be cancelled.");
            for (Bookings bk : (List<Bookings>) ses.createCriteria(Bookings.class)
                    .add(Restrictions.eq("active", Boolean.TRUE)).add(this.addDayRange())
                    .add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION))
                    .add(Restrictions.eq("rigType", type)).list()) {
                this.logger.warn("Cancelling booking for " + bk.getUser().qName() + " because booking rig type "
                        + type.getName() + " has no rigs.");
                bk.setActive(false);
                bk.setCancelReason("Booked rig type has no rigs.");

                new BookingNotification(bk).notifyCancel();
            }
            ses.beginTransaction();
            ses.flush();
            ses.getTransaction().commit();
            continue;
        }

        this.getRigBookings(rigs.iterator().next(), ses);
    }

    /* Load all the request capabilities that have bookings today. */
    qu = ses.createCriteria(RequestCapabilities.class);
    if (this.capsTargets.size() > 0)
        qu.add(Restrictions.not(Restrictions.in("capabilities", this.capsTargets.keySet())));
    for (RequestCapabilities caps : (List<RequestCapabilities>) qu.list()) {
        if (this.capsTargets.containsKey(caps.getCapabilities()))
            continue;

        if ((num = (Integer) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE))
                .add(this.addDayRange())
                .add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION))
                .add(Restrictions.eq("requestCapabilities", caps)).setProjection(Projections.rowCount())
                .uniqueResult()) == 0)
            continue;

        this.logger.debug("Request capabilities " + caps.getCapabilities() + " has " + num + " bookings, so "
                + "loading it up for full day load.");

        List<RequestCapabilities> capsList = new ArrayList<RequestCapabilities>();
        capsList.add(caps);
        this.loadRequestCapabilities(capsList, ses, true);

        if (!this.capsTargets.containsKey(caps.getCapabilities())) {
            this.logger.warn("Request capabilities " + caps.getCapabilities() + " has " + num + " bookings but "
                    + "not any matching rigs so they all will be cancelled.");
            for (Bookings bk : (List<Bookings>) ses.createCriteria(Bookings.class)
                    .add(Restrictions.eq("active", Boolean.TRUE)).add(this.addDayRange())
                    .add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION))
                    .add(Restrictions.eq("requestCapabilities", caps)).list()) {
                this.logger.warn("Cancelling booking for " + bk.getUser().qName() + " because booking request "
                        + "capabilities " + caps.getCapabilities() + " has no matching rigs.");
                bk.setActive(false);
                bk.setCancelReason("Booked request capabilities has no rigs.");

                new BookingNotification(bk).notifyCancel();
            }
            ses.beginTransaction();
            ses.flush();
            ses.getTransaction().commit();
        }
    }
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java

License:Open Source License

/**
 * Loads the request capabilities./* w w  w  .j  a va  2s  . c  o m*/
 * 
 * @param capsList capabilities list
 * @param ses database session
 */
private void loadRequestCapabilities(List<RequestCapabilities> capsList, Session ses,
        boolean ignoreNoBookings) {
    while (capsList.size() > 0) {
        RequestCapabilities reqCaps = capsList.get(0);
        this.logger.debug(
                "Attempting to load bookings for request capabilities " + reqCaps.getCapabilities() + '.');

        Criteria qu = ses.createCriteria(Bookings.class)
                .add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION))
                .add(Restrictions.eq("requestCapabilities", reqCaps))
                .add(Restrictions.eq("active", Boolean.TRUE)).add(this.addDayRange())
                .addOrder(Order.desc("duration"));
        @SuppressWarnings("unchecked")
        List<Bookings> bookings = qu.list();

        /* There are no bookings for this class so no need to load it
         * yet. */
        if (ignoreNoBookings && bookings.size() == 0) {
            this.logger.debug("Not going to load request capabilities " + reqCaps.getCapabilities()
                    + " because " + "it has no bookings.");
            capsList.remove(0);
            continue;
        }

        /* Find all the matching rigs. */
        List<Rig> matchingRigs = new ArrayList<Rig>();
        for (MatchingCapabilities match : reqCaps.getMatchingCapabilitieses()) {
            matchingRigs.addAll(match.getRigCapabilities().getRigs());
        }

        /* If the request capabilities has no matching rigs, we cannot load 
         * the request capabilities loop. */
        if (matchingRigs.size() == 0) {
            this.logger.debug("Cannot load up request capbilities resource loop for '"
                    + reqCaps.getCapabilities() + "' because it has no matching rigs.");
            capsList.remove(0);
            continue;
        }

        /* Make sure all the rigs are loaded. */
        for (Rig r : matchingRigs) {
            if (!this.rigBookings.containsKey(r.getName())) {
                RigBookings b = new RigBookings(r, this.day);
                this.loadRig(b, r, ses);
                this.rigBookings.put(r.getName(), b);
                /* By definition, since a rig wasn't loaded, it's type wasn't 
                 * loaded either. */
                this.loadRigType(r, ses, capsList);
            }
        }

        /* Complete the request capabilities resource loop. */
        RigBookings first = this.rigBookings.get(matchingRigs.get(0).getName());
        RigBookings prev = first;
        for (int i = 1; i < matchingRigs.size(); i++) {
            RigBookings next = this.rigBookings.get(matchingRigs.get(i).getName());
            prev.setCapsLoopNext(reqCaps, next);
            prev = next;
        }
        prev.setCapsLoopNext(reqCaps, first);

        /* Load the request capabilities bookings. */
        for (Bookings booking : bookings) {
            MBooking membooking = new MBooking(booking, this.day);
            RigBookings next = first;

            do {
                if (next.areSlotsFree(membooking)) {
                    if (next.commitBooking(membooking)) {
                        /* If there is a next booking, try load it to the next rig. */
                        first = next.getCapsLoopNext(reqCaps);
                        break;

                    } else {
                        this.logger.error(
                                "Failed to commit a booking to a slots that should have been empty. This "
                                        + "is a probable race condition. Ominous, but the loading search will continue regardless.");
                    }
                }
                next = next.getCapsLoopNext(reqCaps);
            } while (next != first);

            /* The assignment loop was completed and no position was found to put
             * the booking, so run load balance to try to free a resource. */
            if (!next.hasBooking(membooking)) {
                do {
                    if (this.innerLoadBalance(next, membooking, true)) {
                        if (next.commitBooking(membooking)) {
                            /* If there is a next booking, try load it to the next rig. */
                            first = next.getCapsLoopNext(reqCaps);
                            break;

                        } else {
                            this.logger
                                    .error("Failed to commit a booking to a slots that should have been empty. "
                                            + "This is a probable race condition. Ominous, but the loading search will "
                                            + "continue regardless.");
                        }
                    }
                    next = next.getCapsLoopNext(reqCaps);
                } while (next != first);
            }

            /* The balancing loop was completed and no position was found to put
             * the booking, so the booking will need to be canceled. */
            if (!next.hasBooking(membooking)) {
                this.logger.error("Request capabilities '" + reqCaps.getCapabilities() + "' is over commited "
                        + "and has over lapping bookings. The booking for '" + booking.getUserNamespace() + ':'
                        + booking.getUserName() + "' starting at " + booking.getStartTime()
                        + " is being cancelled.");
                booking.setActive(false);
                booking.setCancelReason("Request capabilities was overbooked.");
                ses.beginTransaction();
                ses.flush();
                ses.getTransaction().commit();

                new BookingNotification(booking).notifyCancel();
            }
        }

        this.capsTargets.put(capsList.remove(0).getCapabilities(), prev);
    }
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java

License:Open Source License

/**
 * Loads a rig type by creating the rig bookings type loop, then loading 
 * the rig type bookings to rigs.// w w w.j  a v  a 2  s  . co m
 * 
 * @param rig rig in type
 * @param ses database session
 * @param capsToLoad list of request capabilities that may need to be loaded from
 *      the rigs in type
 */
@SuppressWarnings("unchecked")
private void loadRigType(Rig rig, Session ses, List<RequestCapabilities> capsToLoad) {
    RigBookings first = this.rigBookings.get(rig.getName());
    RigBookings prev = first;

    /* Set up the rig type navigation loop. */
    RigType rigType = rig.getRigType();
    this.logger.debug("Loading rig type " + rigType.getName() + " for day " + this.day + '.');

    Set<Rig> rigs = rigType.getRigs();
    for (Rig r : rigs) {
        for (MatchingCapabilities match : r.getRigCapabilities().getMatchingCapabilitieses()) {
            RequestCapabilities reqCaps = match.getRequestCapabilities();
            if (!capsToLoad.contains(reqCaps)) {
                capsToLoad.add(reqCaps);
            }
        }

        /* Don't duplicate the initial rig. */
        if (r.equals(rig))
            continue;

        RigBookings next = new RigBookings(r, this.day);
        this.loadRig(next, r, ses);
        this.rigBookings.put(r.getName(), next);
        prev.setTypeLoopNext(next);
        prev = next;
    }

    /* Complete the type loop. */
    prev.setTypeLoopNext(first);

    /* Load up the type bookings. */
    Criteria qu = ses.createCriteria(Bookings.class)
            .add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION))
            .add(Restrictions.eq("rigType", rigType)).add(Restrictions.eq("active", Boolean.TRUE))
            .add(this.addDayRange()).addOrder(Order.desc("duration"));

    for (Bookings booking : (List<Bookings>) qu.list()) {
        MBooking membooking = new MBooking(booking, this.day);
        RigBookings next = first;

        do {
            if (next.areSlotsFree(membooking)) {
                if (next.commitBooking(membooking)) {
                    /* If there is a next booking, try load it to the next rig. */
                    first = next.getTypeLoopNext();
                    break;

                } else {
                    this.logger.error("Failed to commit a booking to a slots that should have been empty. This "
                            + "is a probable race condition. Ominous, but the loading search will continue regardless.");
                }
            }
            next = next.getTypeLoopNext();
        } while (next != first);

        /* The assignment loop was completed and no position was found to put
         * the booking, so run load balance to try to free a resource. */
        if (!next.hasBooking(membooking)) {
            do {
                if (this.innerLoadBalance(next, membooking, true)) {
                    if (next.commitBooking(membooking)) {
                        /* If there is a next booking, try load it to the next rig. */
                        first = next.getTypeLoopNext();
                        break;

                    } else {
                        this.logger.error("Failed to commit a booking to a slots that should have been empty. "
                                + "This is a probable race condition. Ominous, but the loading search will "
                                + "continue regardless.");
                    }
                }
                next = next.getTypeLoopNext();
            } while (next != first);
        }

        /* The balancing loop was completed and no position was found to put 
         * the booking, so the type was over-booked. The booking will need to be canceled. */
        if (!next.hasBooking(membooking)) {

            this.logger.error(
                    "Rig type '" + rigType.getName() + "' is over commited and has over lapping bookings. "
                            + "The booking for '" + booking.getUserNamespace() + ':' + booking.getUserName()
                            + "' starting at " + booking.getStartTime() + " is being cancelled.");
            booking.setActive(false);
            booking.setCancelReason("Rig type was overbooked.");
            ses.beginTransaction();
            ses.flush();
            ses.getTransaction().commit();

            new BookingNotification(booking).notifyCancel();
        }
    }

    this.typeTargets.put(rigType.getName(), first);
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java

License:Open Source License

/**
 * Loads the rig booking times for the rig. If the rig is over committed
 * (overlapping rig bookings), one of the bookings is canceled.
 * /*from  www.j av a  2 s .c  o  m*/
 * @param bookings rig bookings container
 * @param rig rig to load bookings from
 * @param ses database session
 */
@SuppressWarnings("unchecked")
private void loadRig(RigBookings bookings, Rig rig, Session ses) {
    /* Load the rig offline periods. */
    Criteria qu = ses.createCriteria(RigOfflineSchedule.class).add(Restrictions.eq("active", Boolean.TRUE))
            .add(Restrictions.eq("rig", rig)).add(this.addDayRange());
    for (RigOfflineSchedule off : (List<RigOfflineSchedule>) qu.list()) {
        bookings.commitBooking(new MBooking(off, this.day));
    }

    /* Load the rigs bookings. */
    qu = ses.createCriteria(Bookings.class)
            .add(Restrictions.eq("resourceType", ResourcePermission.RIG_PERMISSION))
            .add(Restrictions.eq("rig", rig)).add(Restrictions.eq("active", Boolean.TRUE))
            .add(this.addDayRange());

    for (Bookings booking : (List<Bookings>) qu.list()) {
        if (!bookings.commitBooking(new MBooking(booking, this.day))) {
            /* The rig has been over booked so this booking will 
             * need to be canceled. */
            this.logger.error("Rig '" + rig.getName() + "' is over commited and has over lapping bookings. "
                    + "The booking for '" + booking.getUserNamespace() + ':' + booking.getUserName()
                    + "' starting at " + booking.getStartTime() + " is being cancelled.");
            booking.setActive(false);
            booking.setCancelReason("Rig will be offline or was overbooked.");
            ses.beginTransaction();
            ses.flush();
            ses.getTransaction().commit();

            new BookingNotification(booking).notifyCancel();
        }
    }

}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsService.java

License:Open Source License

@Override
public FindFreeBookingsResponse findFreeBookings(FindFreeBookings findFreeBookings) {
    /* --------------------------------------------------------------------
     * -- Read request parameters.                                       --
     * -------------------------------------------------------------------- */
    FindBookingSlotType request = findFreeBookings.getFindBookingSlots();
    String debug = "Received " + this.getClass().getSimpleName() + "#findFreeBookings with params: ";

    UserIDType uid = request.getUserID();
    debug += " user ID=" + uid.getUserID() + ", user namespace=" + uid.getUserNamespace() + ", user name="
            + uid.getUserName() + " user QName=" + uid.getUserQName();

    PermissionIDType reqPermission = request.getPermissionID();
    if (reqPermission != null)
        debug += " permission ID=" + reqPermission.getPermissionID();

    ResourceIDType reqResource = request.getResourceID();
    if (reqResource != null)
        debug += " resource type= " + reqResource.getType() + ", ID=" + request.getResourceID().getResourceID()
                + ", name=" + reqResource.getResourceName();

    Calendar reqStart = request.getPeriod().getStartTime();
    Calendar reqEnd = request.getPeriod().getEndTime();
    this.dstHack(reqStart);
    this.dstHack(reqEnd);

    debug += " period start=" + reqStart.getTime() + ", period end=" + reqEnd.getTime();
    this.logger.debug(debug);

    /* --------------------------------------------------------------------
     * -- Generate valid, blank request parameters.                      --
     * -------------------------------------------------------------------- */
    FindFreeBookingsResponse response = new FindFreeBookingsResponse();
    BookingSlotListType slots = new BookingSlotListType();
    response.setFindFreeBookingsResponse(slots);

    PermissionIDType permission = new PermissionIDType();
    slots.setPermissionID(permission);//from  w ww . j a  va2  s  .  c om

    ResourceIDType resource = new ResourceIDType();
    resource.setType("TYPE");
    slots.setResourceID(resource);

    Session ses = DataAccessActivator.getNewSession();
    try {
        /* ----------------------------------------------------------------
         * -- Load the user.                                             --
         * ---------------------------------------------------------------- */
        User user = this.getUserFromUserID(uid, ses);
        if (user == null) {
            this.logger.info("Unable to provide free times because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Load the permission.                                             --
         * ---------------------------------------------------------------- */
        ResourcePermission perm = null;
        if (reqPermission != null) {
            ResourcePermissionDao resPermissionDao = new ResourcePermissionDao(ses);
            perm = resPermissionDao.get(Long.valueOf(reqPermission.getPermissionID()));
        } else if (reqResource != null) {
            Criteria qu = ses.createCriteria(ResourcePermission.class);

            /* Add resource restrictions. */
            qu.add(Restrictions.eq("type", reqResource.getType()));
            if (ResourcePermission.TYPE_PERMISSION.equals(reqResource.getType())) {
                if (reqResource.getResourceID() > 0) {
                    qu.add(Restrictions.eq("rigType.id", Long.valueOf(reqResource.getResourceID())));
                }
                if (reqResource.getResourceName() != null) {
                    qu.createCriteria("rigType").add(Restrictions.eq("name", reqResource.getResourceName()));
                }
            } else if (ResourcePermission.RIG_PERMISSION.equals(reqResource.getType())) {
                if (reqResource.getResourceID() > 0) {
                    qu.add(Restrictions.eq("rig.id", Long.valueOf(reqResource.getResourceID())));
                }
                if (reqResource.getResourceName() != null) {
                    qu.createCriteria("rig").add(Restrictions.eq("name", reqResource.getResourceName()));
                }
            } else if (ResourcePermission.CAPS_PERMISSION.equals(reqResource.getType())) {
                if (reqResource.getResourceID() > 0) {
                    qu.add(Restrictions.eq("requestCapabilities.id",
                            Long.valueOf(reqResource.getResourceID())));
                }
                if (reqResource.getResourceName() != null) {
                    qu.createCriteria("requestCapabilities")
                            .add(Restrictions.eq("capabilities", reqResource.getResourceName()));
                }
            } else {
                this.logger.warn("Unable to provide free times because resource type " + reqResource.getType()
                        + " is not understood.");
                return response;
            }

            List<UserClass> uc = new ArrayList<UserClass>();
            for (UserAssociation assoc : user.getUserAssociations())
                uc.add(assoc.getUserClass());

            /* The permission user class must be active and bookable. */
            qu.createCriteria("userClass").add(Restrictions.eq("active", Boolean.TRUE))
                    .add(Restrictions.eq("bookable", Boolean.TRUE));
            qu.add(Restrictions.in("userClass", uc));

            /* Add order in case we need to count in range, latest first. */
            qu.addOrder(Order.desc("startTime"));

            @SuppressWarnings("unchecked")
            List<ResourcePermission> rpList = qu.list();
            if (rpList.size() == 1) {
                /* One permission so good to go. */
                perm = rpList.get(0);
            } else if (rpList.size() > 1) {
                Date rsd = reqStart.getTime();
                Date red = reqEnd.getTime();
                /* Multiple permissions so we take the permission in time range. */
                for (ResourcePermission rp : rpList) {
                    if (rp.getStartTime().before(rsd) && rp.getExpiryTime().after(rsd)
                            || rp.getStartTime().before(red) && rp.getExpiryTime().after(red)
                            || rp.getStartTime().after(rsd) && rp.getExpiryTime().before(red)) {
                        perm = rp;
                        break;
                    }
                }

                /* Nothing in range so it doesn't matter which resource we give. */
                if (perm == null)
                    perm = rpList.get(0);
            }
        }

        /* If no permission is specified, either it doesn't exist or it wasn't
         * specified. Either way, we can't provide any information. */
        if (perm == null) {
            this.logger
                    .warn("Unable to provide free times because no permission or resource has been specified "
                            + "or found to provide the free times of.");
            return response;
        }

        /* Make sure the permission a valid booking permission. */
        if (!(perm.getUserClass().isActive() && perm.getUserClass().isBookable())) {
            this.logger.warn(
                    "Unable to provide free times because the permission is not a valid booking permission.");
            return response;
        }

        /* There is a permission, but the user doesn't have it. */
        if (!this.checkPermission(user, perm)) {
            this.logger.warn("Unable to provide free times to user " + user.getNamespace() + ':'
                    + user.getName() + " because they do not have permission " + perm.getId() + ".");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Populate the response with permission parameters.          --
         * ---------------------------------------------------------------- */
        permission.setPermissionID(perm.getId().intValue());
        resource.setType(perm.getType());
        if (ResourcePermission.RIG_PERMISSION.equals(perm.getType())) {
            Rig rig = perm.getRig();
            if (rig == null) {
                this.logger.warn("Unable to provide free times because the rig permission with ID="
                        + perm.getId() + " is not set with a rig.");
                return response;
            }
            resource.setResourceID(rig.getId().intValue());
            resource.setResourceName(rig.getName());
        } else if (ResourcePermission.TYPE_PERMISSION.equals(perm.getType())) {
            RigType rigType = perm.getRigType();
            if (rigType == null) {
                this.logger.warn("Unable to provide free times because the rig type permission with ID="
                        + perm.getId() + " is not set with a rig type.");
                return response;
            }
            resource.setResourceID(rigType.getId().intValue());
            resource.setResourceName(rigType.getName());
        } else if (ResourcePermission.CAPS_PERMISSION.equals(perm.getType())) {
            RequestCapabilities caps = perm.getRequestCapabilities();
            if (caps == null) {
                this.logger.warn(
                        "Unable to provide free times because the request capabilities permission with ID="
                                + perm.getId() + " is not set with a request capabilities.");
                return response;
            }
            resource.setResourceID(caps.getId().intValue());
            resource.setResourceName(caps.getCapabilities());
        } else {
            this.logger.warn("Unable to provide free times because the permission with ID=" + perm.getId()
                    + " has type '" + perm.getType() + "' which is not understood.");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Check permission times to make sure the request is within  --
         * -- the permission start and expiry range.                     --
         * ---------------------------------------------------------------- */
        Calendar permStart = Calendar.getInstance();
        permStart.setTime(perm.getStartTime());

        /* The /actual/ permission start time may either be the permission 
         * start time or the time horizon time. This is a second offset from
         * the current time (i.e. it atleast stops bookings being made for
         * the past. */
        Calendar horizonTime = Calendar.getInstance();
        horizonTime.add(Calendar.SECOND, perm.getUserClass().getTimeHorizon());
        if (horizonTime.after(permStart)) {
            /* Which ever comes later. */
            permStart = TimeUtil.coerceToNextSlotTime(horizonTime);
        }

        Calendar permEnd = Calendar.getInstance();
        permEnd.setTime(perm.getExpiryTime());

        if (reqEnd.before(permStart) || reqStart.after(permEnd) || permEnd.before(permStart)) {
            /* In this case the requested range is, after the end of the 
             * permission region, before the start of the permission 
             * region or the permission start is after the permission end
             * (the permission start is always sliding for horizion). */
            BookingSlotType slot = new BookingSlotType();
            slot.setSlot(request.getPeriod());
            slot.setState(SlotState.NOPERMISSION);
            slots.addBookingSlot(slot);

            return response;
        }

        if (reqStart.before(permStart)) {
            /* Here the permission start time is after the requested start time 
             * so the start partial date has no permission. */
            TimePeriodType tp = new TimePeriodType();
            tp.setStartTime(reqStart);
            tp.setEndTime(permStart);
            BookingSlotType slot = new BookingSlotType();
            slot.setSlot(tp);
            slot.setState(SlotState.NOPERMISSION);
            slots.addBookingSlot(slot);

            /* The permission start time is now the search start time. */
            reqStart = permStart;
        }

        Calendar searchEnd = reqEnd;
        if (reqEnd.after(permEnd)) {
            /* Here the permission end time is before the requested end time
             * so the end partial date has no permission. We will search the free
             * search end to the permission end but add the no permission period
             * last. */
            searchEnd = permEnd;
        }

        /* ----------------------------------------------------------------
         * -- Get the free times for the permission resource.            --
         * ---------------------------------------------------------------- */
        List<TimePeriod> free = null;
        resource.setType(perm.getType());
        if (ResourcePermission.RIG_PERMISSION.equals(perm.getType())) {
            free = this.engine.getFreeTimes(perm.getRig(), new TimePeriod(reqStart, searchEnd),
                    perm.getSessionDuration() / 2, ses);
        } else if (ResourcePermission.TYPE_PERMISSION.equals(perm.getType())) {
            free = this.engine.getFreeTimes(perm.getRigType(), new TimePeriod(reqStart, searchEnd),
                    perm.getSessionDuration() / 2, ses);
        } else if (ResourcePermission.CAPS_PERMISSION.equals(perm.getType())) {
            free = this.engine.getFreeTimes(perm.getRequestCapabilities(), new TimePeriod(reqStart, searchEnd),
                    perm.getSessionDuration() / 2, ses);
        }

        /* ----------------------------------------------------------------
         * -- Populate the resource with free and booked time            --
         * ---------------------------------------------------------------- */
        Calendar c = reqStart;

        if (free.size() > 0) {
            for (TimePeriod period : free) {
                if (Math.abs(period.getStartTime().getTimeInMillis() - c.getTimeInMillis()) > 60000) {
                    /* The difference with the last time and the next time is
                     * more than a minute, then there should be a booked period. */
                    TimePeriodType tp = new TimePeriodType();
                    tp.setStartTime(c);
                    tp.setEndTime(period.getStartTime());
                    BookingSlotType slot = new BookingSlotType();
                    slot.setSlot(tp);
                    slot.setState(SlotState.BOOKED);
                    slots.addBookingSlot(slot);
                }

                TimePeriodType tp = new TimePeriodType();
                tp.setStartTime(period.getStartTime());
                tp.setEndTime(period.getEndTime());
                BookingSlotType slot = new BookingSlotType();
                slot.setSlot(tp);
                slot.setState(SlotState.FREE);
                slots.addBookingSlot(slot);

                c = period.getEndTime();
            }

            /* There is a booked spot at the end. */
            if (Math.abs(searchEnd.getTimeInMillis() - c.getTimeInMillis()) > 60000) {
                /* The difference with the last time and the next time is
                 * more than a minute, then there should be a booked period. */
                TimePeriodType tp = new TimePeriodType();
                tp.setStartTime(c);
                tp.setEndTime(searchEnd);
                BookingSlotType slot = new BookingSlotType();
                slot.setSlot(tp);
                slot.setState(SlotState.BOOKED);
                slots.addBookingSlot(slot);
            }
        } else {
            /* There is no free times on the day. */
            TimePeriodType tp = new TimePeriodType();
            tp.setStartTime(reqStart);
            tp.setEndTime(reqEnd);
            BookingSlotType slot = new BookingSlotType();
            slot.setSlot(tp);
            slot.setState(SlotState.BOOKED);
            slots.addBookingSlot(slot);
        }

        if (reqEnd.after(permEnd)) {
            /* Add a no permission at the end. */
            TimePeriodType tp = new TimePeriodType();
            tp.setStartTime(permEnd);
            tp.setEndTime(reqEnd);
            BookingSlotType slot = new BookingSlotType();
            slot.setSlot(tp);
            slot.setState(SlotState.NOPERMISSION);
            slots.addBookingSlot(slot);
        }
    } finally {
        ses.close();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsService.java

License:Open Source License

@Override
public GetBookingsResponse getBookings(GetBookings getBookings) {
    BookingsRequestType request = getBookings.getGetBookings();
    String debug = "Received " + this.getClass().getSimpleName() + "#getBookings with params:";
    if (request.getUserID() != null)
        debug += " user ID=" + request.getUserID().getUserID() + ", user name="
                + request.getUserID().getUserName() + ", user namespace="
                + request.getUserID().getUserNamespace() + " user QName=" + request.getUserID().getUserQName();
    if (request.getPermissionID() != null)
        debug += " permission ID=" + request.getPermissionID().getPermissionID();
    if (request.getResourceID() != null)
        debug += "resource type=" + request.getResourceID().getType() + ", resource ID="
                + request.getResourceID().getResourceID() + ", resource name="
                + request.getResourceID().getResourceName();
    debug += " show cancelled=" + request.showCancelled() + " show finished=" + request.showFinished();
    this.logger.debug(debug);

    GetBookingsResponse response = new GetBookingsResponse();
    BookingListType bookings = new BookingListType();
    response.setGetBookingsResponse(bookings);

    BookingsDao dao = new BookingsDao();
    try {/*  w w w.  j  a  va 2  s . co  m*/
        Session ses = dao.getSession();
        Criteria cri = ses.createCriteria(Bookings.class);

        /* If user specificed, add that to query. */
        User user = null;
        if (request.getUserID() != null && (user = this.getUserFromUserID(request.getUserID(), ses)) != null) {
            cri.add(Restrictions.eq("user", user));
        }

        /* If permission was specified, add that to query. */
        if (request.getPermissionID() != null) {
            cri.add(Restrictions.eq("resourcePermission.id",
                    Long.valueOf(request.getPermissionID().getPermissionID())));
        }

        /* If resource was specified, add that to query. */
        ResourceIDType rid = request.getResourceID();
        if (rid != null) {
            if (ResourcePermission.RIG_PERMISSION.equals(rid.getType())) {
                cri.add(Restrictions.eq("resourceType", ResourcePermission.RIG_PERMISSION));
                if (rid.getResourceID() > 0)
                    cri.add(Restrictions.eq("rig.id", Long.valueOf(rid.getResourceID())));
                if (rid.getResourceName() != null) {
                    cri.createCriteria("rig").add(Restrictions.eq("name", rid.getResourceName()));
                }
            } else if (ResourcePermission.TYPE_PERMISSION.equals(rid.getType())) {
                cri.add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION));
                if (rid.getResourceID() > 0)
                    cri.add(Restrictions.eq("rigType.id", Long.valueOf(rid.getResourceID())));
                if (rid.getResourceName() != null) {
                    cri.createCriteria("rigType").add(Restrictions.eq("name", rid.getResourceName()));
                }
            } else if (ResourcePermission.CAPS_PERMISSION.equals(rid.getType())) {
                cri.add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION));
                if (rid.getResourceID() > 0) {
                    cri.add(Restrictions.eq("requestCapabilities.id", Long.valueOf(rid.getResourceID())));
                }
                if (rid.getResourceName() != null) {
                    cri.createCriteria("requestCapabilities")
                            .add(Restrictions.eq("capabilities", rid.getResourceName()));
                }
            } else {
                this.logger.warn("Not added a resource restriction to existing booking search because the "
                        + "resourece type '" + rid.getType() + "' is not one of '"
                        + ResourcePermission.RIG_PERMISSION + "' '" + ResourcePermission.TYPE_PERMISSION + "' '"
                        + ResourcePermission.CAPS_PERMISSION + "'.");
            }
        }

        /* Other constraints specified. */
        if (!request.showCancelled() && !request.showFinished()) {
            cri.add(Restrictions.eq("active", Boolean.TRUE));
        } else if (!request.showFinished()) {
            cri.add(Restrictions.or(Restrictions.isNotNull("cancelReason"),
                    Restrictions.eq("active", Boolean.TRUE)));
        } else if (!request.showCancelled()) {
            cri.add(Restrictions.isNull("cancelReason"));
        }

        /* Order the results be booking start time. */
        cri.addOrder(Order.asc("startTime"));

        @SuppressWarnings("unchecked")
        List<Bookings> list = cri.list();
        for (Bookings booking : list) {
            bookings.addBookings(this.populateBookingType(new BookingType(), booking));
        }
    } finally {
        dao.closeSession();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsSOAPImpl.java

License:Open Source License

@Override
public FindFreeBookingsResponse findFreeBookings(FindFreeBookings findFreeBookings) {
    /* --------------------------------------------------------------------
     * -- Read request parameters.                                       --
     * -------------------------------------------------------------------- */
    FindBookingSlotType request = findFreeBookings.getFindBookingSlots();
    String debug = "Received " + this.getClass().getSimpleName() + "#findFreeBookings with params: ";

    UserIDType uid = request.getUserID();
    debug += " user ID=" + uid.getUserID() + ", user namespace=" + uid.getUserNamespace() + ", user name="
            + uid.getUserName() + " user QName=" + uid.getUserQName();

    PermissionIDType reqPermission = request.getPermissionID();
    if (reqPermission != null)
        debug += " permission ID=" + reqPermission.getPermissionID();

    ResourceIDType reqResource = request.getResourceID();
    if (reqResource != null)
        debug += " resource type= " + reqResource.getType() + ", ID=" + request.getResourceID().getResourceID()
                + ", name=" + reqResource.getResourceName();

    Calendar reqStart = request.getPeriod().getStartTime();
    Calendar reqEnd = request.getPeriod().getEndTime();
    this.dstHack(reqStart);
    this.dstHack(reqEnd);

    debug += " period start=" + reqStart.getTime() + ", period end=" + reqEnd.getTime();
    this.logger.debug(debug);

    /* --------------------------------------------------------------------
     * -- Generate valid, blank request parameters.                      --
     * -------------------------------------------------------------------- */
    FindFreeBookingsResponse response = new FindFreeBookingsResponse();
    BookingSlotListType slots = new BookingSlotListType();
    response.setFindFreeBookingsResponse(slots);

    PermissionIDType permission = new PermissionIDType();
    slots.setPermissionID(permission);/*from  www.  j  ava2 s .  co m*/

    ResourceIDType resource = new ResourceIDType();
    resource.setType("TYPE");
    slots.setResourceID(resource);

    Session db = DataAccessActivator.getNewSession();
    try {
        /* ----------------------------------------------------------------
         * -- Load the user.                                             --
         * ---------------------------------------------------------------- */
        User user = this.getUserFromUserID(uid, db);
        if (user == null) {
            this.logger.info("Unable to provide free times because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Load the permission.                                             --
         * ---------------------------------------------------------------- */
        ResourcePermission perm = null;
        if (reqPermission != null) {
            ResourcePermissionDao resPermissionDao = new ResourcePermissionDao(db);
            perm = resPermissionDao.get(Long.valueOf(reqPermission.getPermissionID()));
        } else if (reqResource != null) {
            Criteria qu = db.createCriteria(ResourcePermission.class);

            /* Add resource restrictions. */
            qu.add(Restrictions.eq("type", reqResource.getType()));
            if (ResourcePermission.TYPE_PERMISSION.equals(reqResource.getType())) {
                if (reqResource.getResourceID() > 0) {
                    qu.add(Restrictions.eq("rigType.id", Long.valueOf(reqResource.getResourceID())));
                }
                if (reqResource.getResourceName() != null) {
                    qu.createCriteria("rigType").add(Restrictions.eq("name", reqResource.getResourceName()));
                }
            } else if (ResourcePermission.RIG_PERMISSION.equals(reqResource.getType())) {
                if (reqResource.getResourceID() > 0) {
                    qu.add(Restrictions.eq("rig.id", Long.valueOf(reqResource.getResourceID())));
                }
                if (reqResource.getResourceName() != null) {
                    qu.createCriteria("rig").add(Restrictions.eq("name", reqResource.getResourceName()));
                }
            } else if (ResourcePermission.CAPS_PERMISSION.equals(reqResource.getType())) {
                if (reqResource.getResourceID() > 0) {
                    qu.add(Restrictions.eq("requestCapabilities.id",
                            Long.valueOf(reqResource.getResourceID())));
                }
                if (reqResource.getResourceName() != null) {
                    qu.createCriteria("requestCapabilities")
                            .add(Restrictions.eq("capabilities", reqResource.getResourceName()));
                }
            } else {
                this.logger.warn("Unable to provide free times because resource type " + reqResource.getType()
                        + " is not understood.");
                return response;
            }

            List<UserClass> uc = new ArrayList<UserClass>();
            for (UserAssociation assoc : user.getUserAssociations())
                uc.add(assoc.getUserClass());

            /* The permission user class must be active and bookable. */
            qu.createCriteria("userClass").add(Restrictions.eq("active", Boolean.TRUE))
                    .add(Restrictions.eq("bookable", Boolean.TRUE));
            qu.add(Restrictions.in("userClass", uc));

            /* Add order in case we need to count in range, latest first. */
            qu.addOrder(Order.desc("startTime"));

            @SuppressWarnings("unchecked")
            List<ResourcePermission> rpList = qu.list();
            if (rpList.size() == 1) {
                /* One permission so good to go. */
                perm = rpList.get(0);
            } else if (rpList.size() > 1) {
                Date rsd = reqStart.getTime();
                Date red = reqEnd.getTime();
                /* Multiple permissions so we take the permission in time range. */
                for (ResourcePermission rp : rpList) {
                    if (rp.getStartTime().before(rsd) && rp.getExpiryTime().after(rsd)
                            || rp.getStartTime().before(red) && rp.getExpiryTime().after(red)
                            || rp.getStartTime().after(rsd) && rp.getExpiryTime().before(red)) {
                        perm = rp;
                        break;
                    }
                }

                /* Nothing in range so it doesn't matter which resource we give. */
                if (perm == null)
                    perm = rpList.get(0);
            }
        }

        /* If no permission is specified, either it doesn't exist or it wasn't
         * specified. Either way, we can't provide any information. */
        if (perm == null) {
            this.logger
                    .warn("Unable to provide free times because no permission or resource has been specified "
                            + "or found to provide the free times of.");
            return response;
        }

        /* There is a permission, but the user doesn't have it. */
        if (!this.checkPermission(user, perm)) {
            this.logger.warn("Unable to provide free times to user " + user.getNamespace() + ':'
                    + user.getName() + " because they do not have permission " + perm.getId() + ".");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Populate the response with permission parameters.          --
         * ---------------------------------------------------------------- */
        permission.setPermissionID(perm.getId().intValue());
        resource.setType(perm.getType());
        if (ResourcePermission.RIG_PERMISSION.equals(perm.getType())) {
            Rig rig = perm.getRig();
            if (rig == null) {
                this.logger.warn("Unable to provide free times because the rig permission with ID="
                        + perm.getId() + " is not set with a rig.");
                return response;
            }
            resource.setResourceID(rig.getId().intValue());
            resource.setResourceName(rig.getName());
        } else if (ResourcePermission.TYPE_PERMISSION.equals(perm.getType())) {
            RigType rigType = perm.getRigType();
            if (rigType == null) {
                this.logger.warn("Unable to provide free times because the rig type permission with ID="
                        + perm.getId() + " is not set with a rig type.");
                return response;
            }
            resource.setResourceID(rigType.getId().intValue());
            resource.setResourceName(rigType.getName());
        } else if (ResourcePermission.CAPS_PERMISSION.equals(perm.getType())) {
            RequestCapabilities caps = perm.getRequestCapabilities();
            if (caps == null) {
                this.logger.warn(
                        "Unable to provide free times because the request capabilities permission with ID="
                                + perm.getId() + " is not set with a request capabilities.");
                return response;
            }
            resource.setResourceID(caps.getId().intValue());
            resource.setResourceName(caps.getCapabilities());
        } else if (ResourcePermission.CONSUMER_PERMISSION.equalsIgnoreCase(perm.getType())) {
            resource.setResourceID(-1); // Faking ID.
            resource.setResourceName("Fake");
        } else {
            this.logger.warn("Unable to provide free times because the permission with ID=" + perm.getId()
                    + " has type '" + perm.getType() + "' which is not understood.");
            return response;
        }

        BookingsPeriod period = new BookingsServiceImpl().getFreeBookings(reqStart, reqEnd, perm, db);
        for (BookingSlot slot : period.getSlots()) {
            TimePeriodType tp = new TimePeriodType();
            tp.setStartTime(slot.getStart());
            tp.setEndTime(slot.getEnd());

            BookingSlotType bst = new BookingSlotType();
            bst.setSlot(tp);
            bst.setState(SlotState.Factory.fromValue(slot.getState()));

            slots.addBookingSlot(bst);
        }
    } finally {
        db.close();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.AcademicPermissionDao.java

License:Open Source License

/**
 * Gets all the academic permissions for the specified user. 
 * /*from w  w w.ja  va  2 s .  c  o  m*/
 * @param user user to find permissions for 
 * @return list of academic permissions 
 */
@SuppressWarnings("unchecked")
public List<AcademicPermission> getByUser(User user) {
    Criteria cri = this.session.createCriteria(AcademicPermission.class);
    cri.add(Restrictions.eq("user", user));
    return cri.list();
}

From source file:au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.AcademicPermissionDao.java

License:Open Source License

/**
 * Gets all the academic permissions for the specified user class.
 * //  w  ww.j av a  2s. c o  m
 * @param uClass user class to find permissions for
 * @return list of academic permissions 
 */
@SuppressWarnings("unchecked")
public List<AcademicPermission> getByUserClass(UserClass uClass) {
    Criteria cri = this.session.createCriteria(AcademicPermission.class);
    cri.add(Restrictions.eq("userClass", uClass));
    return cri.list();
}

From source file:au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.AcademicPermissionDao.java

License:Open Source License

/**
 * Gets the academic permission for the specified user and user class. If it is
 * not found <code>null</code>. If more than one permission is found, the first
 * is used./*from   ww  w.jav  a  2s  .c  o  m*/
 * 
 * @param user user constraint
 * @param uClass user class constraint
 * @return permission or <code>null</code>
 */
@SuppressWarnings("unchecked")
public AcademicPermission getForUserAndUserClass(User user, UserClass uClass) {
    Criteria cri = this.session.createCriteria(AcademicPermission.class);
    cri.add(Restrictions.eq("user", user)).add(Restrictions.eq("userClass", uClass));

    List<AcademicPermission> perms = cri.list();
    if (perms.size() == 0) {
        return null;
    } else if (perms.size() > 1) {
        this.logger.warn("Found more than one academic permission for the user " + user.getName() + " and "
                + "user class " + uClass.getName() + ". Using the first found permission.");
    }
    return perms.get(0);
}