Example usage for org.hibernate Criteria addOrder

List of usage examples for org.hibernate Criteria addOrder

Introduction

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

Prototype

public Criteria addOrder(Order order);

Source Link

Document

Add an Order ordering to the result set.

Usage

From source file:at.ac.tuwien.ifs.tita.dao.GenericHibernateDao.java

License:Apache License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public List<T> findAllOrdered(Order... orders) {

    List<T> myList = null;/* w  ww .  j  a  va 2 s  . c o m*/

    try {
        Criteria crit = getSession().createCriteria(this.persistenceClass);
        for (Order order : orders) {
            crit.addOrder(order);
        }
        crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        myList = crit.list();
    } catch (Exception e) {
        throw new PersistenceException("Failure during reading entities. Class="
                + this.persistenceClass.getSimpleName() + "\n" + e.getMessage(), e);
    }

    return myList;
}

From source file:at.ac.tuwien.ifs.tita.dao.GenericHibernateDao.java

License:Apache License

/**
 * Search by use of the specified search criterions, order by specified
 * order criterions.// w  ww.j  a  va2s  .c  o m
 *
 * @param criterions - search criterions
 * @param orders - order criterions
 * @param aliases list of aliasnames
 * @return List of result records
 */
@SuppressWarnings("unchecked")
protected List<T> findByCriteriaOrdered(Criterion criterions[], Order orders[], String aliases[]) {
    Criteria crit = getSession().createCriteria(this.persistenceClass);
    if (aliases != null) {
        for (String alias : aliases) {
            crit.createAlias(alias, alias);
        }
    }

    for (int i = 0; i < criterions.length; i++) {
        crit.add(criterions[i]);
    }
    for (int j = 0; j < orders.length; j++) {
        crit.addOrder(orders[j]);
    }
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return crit.list();
}

From source file:at.ac.tuwien.ifs.tita.dao.project.TiTAProjectDao.java

License:Apache License

/** {@inheritDoc} **/
@SuppressWarnings("unchecked")
@Override//from w  ww . j  a  v  a 2s . c o  m
public List<TiTAProject> findProjectsOrderedByName(int maxResult, String orderBy) throws PersistenceException {
    Criteria crit = getSession().createCriteria(TiTAProject.class);

    if (maxResult > 0) {
        crit.setMaxResults(maxResult);
    }

    crit.add(Restrictions.eq("deleted", false));

    crit.addOrder(Order.asc(orderBy));
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    return crit.list();
}

From source file:at.ac.tuwien.ifs.tita.dao.user.UserDAO.java

License:Apache License

/** {@inheritDoc} **/
@Override//from   w ww .j  av  a 2  s  .c o m
@SuppressWarnings("unchecked")
public List<TiTAUser> findUsersOrdered(int maxResult) throws PersistenceException {
    Criteria crit = getSession().createCriteria(TiTAUser.class);

    if (maxResult > 0) {
        crit.setMaxResults(maxResult);
    }

    crit.addOrder(Order.asc("userName"));
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    return crit.list();
}

From source file:at.molindo.esi4j.module.hibernate.scrolling.DefaultQueryScrollingSession.java

License:Apache License

@Override
public List<?> fetch(Session session, int batchSize) {
    Criteria criteria = session.createCriteria(_type);
    if (_lastId != null) {
        criteria.add(Restrictions.gt("id", _lastId));
    }//  w  w w  .  j  a  v a2s.  com
    criteria.addOrder(Order.asc("id"));
    criteria.setMaxResults(batchSize);
    criteria.setCacheable(false);

    for (Map.Entry<String, FetchMode> e : _fetchModes.entrySet()) {
        criteria.setFetchMode(e.getKey(), e.getValue());
    }

    List<?> list = criteria.list();

    if (list.size() > 0) {
        ClassMetadata meta = session.getSessionFactory().getClassMetadata(_type);

        Object last = list.get(list.size() - 1);
        _lastId = meta.getIdentifier(last, (SessionImpl) session);
    }

    return list;
}

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);//  w  ww.j ava 2  s.c o m

    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.ja  v a  2 s . c o 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);//w w w  . j a  va 2  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.RigLogDao.java

License:Open Source License

/**
 * Finds all the stored logs for the specified period for a specific
 * rig. The logs are ordered by their time stamp with the earliest log 
 * first./*from   w ww  .j  ava  2 s  . com*/
 * 
 * @param rig rig to find the logs for
 * @param begin beginning of a period
 * @param end end of a period
 * @return list of logs
 */
@SuppressWarnings("unchecked")
public List<RigLog> findLogs(Rig rig, Date begin, Date end) {
    Criteria cri = this.session.createCriteria(RigLog.class);
    cri.add(Restrictions.eq("rig", rig));
    cri.add(Restrictions.gt("timeStamp", begin));
    cri.add(Restrictions.lt("timeStamp", end));
    cri.addOrder(Order.asc("timeStamp"));
    return cri.list();
}

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

License:Open Source License

/**
 * Finds all the stored logs for the specified period for a specific
 * rig, filtered for a specific state. The logs are ordered by their
 * time stamp with the earliest log first.
 * /*from   w  ww .j a v  a 2  s.c o m*/
 * @param rig rig to find the logs for
 * @param begin beginning of a period
 * @param end end of a period
 * @return list of logs
 */
@SuppressWarnings("unchecked")
public List<RigLog> findLogsOfState(Rig rig, String state, Date begin, Date end) {
    Criteria cri = this.session.createCriteria(RigLog.class);
    cri.add(Restrictions.eq("rig", rig));
    cri.add(Restrictions.gt("timeStamp", begin));
    cri.add(Restrictions.lt("timeStamp", end));
    cri.add(Restrictions.eq("newState", state));
    cri.addOrder(Order.asc("timeStamp"));
    return cri.list();
}