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.permissions.pages.UserClassesPage.java

License:Open Source License

/**
 * Loads a list of resources for a specified resource type.
 * /*  w w w.  ja  v  a  2 s .c o m*/
 * @param request
 * @return response
 */
public JSONArray loadResources(HttpServletRequest request) {
    Criteria qu = null;

    if ("RIG".equals(request.getParameter("type"))) {
        qu = this.db.createCriteria(Rig.class).addOrder(Order.asc("name"))
                .setProjection(Property.forName("name"));
    } else if ("RIGTYPE".equals(request.getParameter("type"))) {
        qu = this.db.createCriteria(RigType.class).addOrder(Order.asc("name"))
                .setProjection(Property.forName("name"));
    } else if ("CAPABILITIES".equals(request.getParameter("type"))) {
        qu = this.db.createCriteria(RequestCapabilities.class).addOrder(Order.asc("capabilities"))
                .setProjection(Property.forName("capabilities"));
    } else {
        this.logger.warn("Unable to provide resource list because resource type '"
                + request.getParameter("type") + "' is not one of 'RIG', 'RIGTYPE' or 'CAPABILITIES'.");
        return new JSONArray();
    }

    return new JSONArray(qu.list());
}

From source file:au.edu.uts.eng.remotelabs.schedserver.permissions.pages.UsersPage.java

License:Open Source License

/**
 * Gets a list of users with a specific search term. The users may be 
 * excluded from a specific class. // w  w  w.j  a  va 2 s .  co m
 * 
 * @param request
 * @return response
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public JSONArray list(HttpServletRequest request) throws JSONException {
    JSONArray arr = new JSONArray();

    Criteria qu = this.db.createCriteria(User.class);

    String search = request.getParameter("search");
    if (search != null) {
        /* Search filter. */
        qu.add(Restrictions.disjunction().add(Restrictions.like("name", search, MatchMode.ANYWHERE))
                .add(Restrictions.like("firstName", search, MatchMode.ANYWHERE))
                .add(Restrictions.like("lastName", search, MatchMode.ANYWHERE)));
    }

    if (request.getParameter("max") != null) {
        /* Max results. */
        qu.setMaxResults(Integer.parseInt(request.getParameter("max")));
    }

    if (request.getParameter("in") != null) {
        /* Users in class. */
        UserClass inClass = new UserClassDao(this.db).findByName(request.getParameter("in"));
        if (inClass == null) {
            this.logger.warn("Not going to add in class as a user list restriction because the class '"
                    + request.getParameter("in") + "' was not found.");
        } else {
            qu.createCriteria("userAssociations").add(Restrictions.eq("userClass", inClass));
        }
    }

    if (request.getParameter("notIn") != null) {
        /* Users not in class. */
        UserClass notInClass = new UserClassDao(this.db).findByName(request.getParameter("notIn"));
        if (notInClass == null) {
            this.logger.warn("Not going to add not in class as a user list restriction because the class '"
                    + request.getParameter("notIn") + "' was not found.");
        } else {
            DetachedCriteria subQu = DetachedCriteria.forClass(User.class)
                    .setProjection(Property.forName("name")).createCriteria("userAssociations")
                    .add(Restrictions.eq("userClass", notInClass));

            List<String> names = subQu.getExecutableCriteria(this.db).list();
            if (names.size() > 0) {
                qu.add(Restrictions.not(Restrictions.in("name", names)));
            }
        }
    }

    qu.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    qu.addOrder(Order.asc("lastName"));
    qu.addOrder(Order.asc("name"));

    for (User user : (List<User>) qu.list()) {
        JSONObject uo = new JSONObject();
        uo.put("name", user.getNamespace() + "-_-" + user.getName());

        if (user.getFirstName() == null || user.getLastName() == null) {
            uo.put("display", user.getName());
        } else {
            uo.put("display", user.getLastName() + ", " + user.getFirstName());
        }

        arr.put(uo);
    }

    return arr;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.queuer.impl.Queue.java

License:Open Source License

/**
 * Runs rig type assigning by loading free rigs in the type and calling
 * rig assignment./*from  ww w .  jav a2  s  . c  o  m*/
 *
 * @param id rig type id
 * @param db database session
 */
public synchronized void runTypeAssignment(Long id, org.hibernate.Session db) {
    RigType type = new RigTypeDao(db).get(id);
    if (type == null)
        return;

    /* Create a query to find a free rig in the rig type. */
    Criteria query = db.createCriteria(Rig.class);
    query.add(Restrictions.eq("rigType", type)).add(Restrictions.eq("active", true))
            .add(Restrictions.eq("online", true)).add(Restrictions.eq("inSession", false))
            .addOrder(Order.asc("lastUpdateTimestamp"));

    @SuppressWarnings("unchecked")
    List<Rig> freeRigs = query.list();
    for (Rig freeRig : freeRigs) {
        if (!this.typeQueues.containsKey(id) || this.typeQueues.get(id).size() == 0) {
            return;
        }
        this.runRigAssignment(freeRig.getId(), db);
    }
}

From source file:au.edu.uts.eng.remotelabs.schedserver.queuer.impl.QueueStaleSessionTask.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// ww  w  .  j  a va2  s  .  c om
public void run() {
    org.hibernate.Session db = null;
    try {
        db = DataAccessActivator.getNewSession();
        Date now = new Date();

        Criteria query = db.createCriteria(Session.class);
        query.add(Restrictions.eq("active", Boolean.TRUE)) // Session must be active.
                .add(Restrictions.isNull("assignmentTime")) // Only sessions in the queue
                .add(Restrictions.isNull("codeReference")); // Only interactive sessions
        List<Session> sessions = query.list();

        /* For each of the sessions, if any of the sessions are stale, remove
         * them from queue. */
        for (Session s : sessions) {
            if ((System.currentTimeMillis() - s.getActivityLastUpdated().getTime()) / 1000 > s
                    .getResourcePermission().getQueueActivityTimeout()) {
                this.logger.warn("Removing stale queue session with id=" + s.getId() + ". Last activity at"
                        + s.getActivityLastUpdated().toString() + ", current time is " + now.toString() + ".");

                Queue.getInstance().removeEntry(s, db);
                s.setActive(false);
                s.setRemovalReason("Queue activity timeout.");
                s.setRemovalTime(now);
                db.beginTransaction();
                db.flush();
                db.getTransaction().commit();
            }
        }
    } catch (HibernateException hex) {
        this.logger.error("Failed to query database to check stale sessions (Exception: "
                + hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");

        if (db != null && db.getTransaction() != null) {
            try {
                db.getTransaction().rollback();
            } catch (HibernateException ex) {
                this.logger.error("Exception rolling back up stale session transaction (Exception: "
                        + ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
            }
        }
    } finally {
        try {
            if (db != null)
                db.close();
        } catch (HibernateException ex) {
            this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName()
                    + "," + " Message: " + ex.getMessage() + ").");
        }
    }
}

From source file:au.edu.uts.eng.remotelabs.schedserver.queuer.intf.Queuer.java

License:Open Source License

/**
 * Gets queue information for the specified resource permission.
 * /*from w  ww  .  j a v  a 2 s .  c o m*/
 * @param perm resource permission
 * @param ses database session
 * @return queue information
 */
@SuppressWarnings("unchecked")
private QueueType getQueueForPermission(ResourcePermission perm, org.hibernate.Session ses) {
    /* Default values. */
    QueueType queue = new QueueType();
    queue.setViable(false);
    queue.setHasFree(false);
    queue.setIsQueuable(false);
    queue.setIsCodeAssignable(false);
    queue.setIsSlaveable(false);
    ResourceIDType resource = new ResourceIDType();
    queue.setQueuedResource(resource);
    resource.setType("NOTFOUND");

    if (perm == null)
        return queue;

    /* Queuable is based on the resource class. */
    boolean rights = perm.getControlLevel().ordinal() > 0;
    queue.setIsQueuable(perm.getUserClass().isQueuable() && rights);
    queue.setIsBookable(perm.getUserClass().isBookable() && rights);
    queue.setIsSlaveable((perm.getControlLevel().ordinal() & 1) == 0);
    String type = perm.getType();
    resource.setType(type);
    boolean free = false;
    if (ResourcePermission.RIG_PERMISSION.equals(type)) {
        /* Rig resource. */
        Rig rig = perm.getRig();
        resource.setResourceID(rig.getId().intValue());
        resource.setResourceName(rig.getName());

        queue.setHasFree(this.isRigFree(rig, perm, ses));
        queue.setViable(rig.isOnline());

        /* Code assignable is defined by the rig type of the rig. */
        queue.setIsCodeAssignable(rig.getRigType().isCodeAssignable());

        /* Only one resource, the actual rig. */
        QueueTargetType target = new QueueTargetType();
        target.setViable(rig.isOnline());
        target.setIsFree(this.isRigFree(rig, perm, ses));
        target.setResource(resource);
        queue.addQueueTarget(target);

    } else if (ResourcePermission.TYPE_PERMISSION.equals(type)) {
        /* Rig type resource. */
        RigType rigType = perm.getRigType();
        resource.setResourceID(rigType.getId().intValue());
        resource.setResourceName(rigType.getName());
        queue.setIsCodeAssignable(rigType.isCodeAssignable());

        /* The targets are the rigs in the rig type. */
        for (Rig rig : rigType.getRigs()) {
            if (rig.isOnline())
                queue.setViable(true);
            if (free = this.isRigFree(rig, perm, ses))
                queue.setHasFree(true);

            QueueTargetType target = new QueueTargetType();
            target.setViable(rig.isOnline());
            target.setIsFree(free);
            ResourceIDType resourceRig = new ResourceIDType();
            resourceRig.setType(ResourcePermission.RIG_PERMISSION);
            resourceRig.setResourceID(rig.getId().intValue());
            resourceRig.setResourceName(rig.getName());
            target.setResource(resourceRig);
            queue.addQueueTarget(target);
        }
    } else if (ResourcePermission.CAPS_PERMISSION.equals(type)) {
        /* Capabilities resource. */
        RequestCapabilities requestCaps = perm.getRequestCapabilities();
        resource.setResourceID(requestCaps.getId().intValue());
        resource.setResourceName(requestCaps.getCapabilities());

        /* For code assignable to be true, all rigs who match the
         * request capabilities, must be code assignable. */
        queue.setIsCodeAssignable(true);

        /* Are all the rigs who have match rig capabilities to the
         * request capabilities. */
        Criteria qu = ses.createCriteria(Rig.class).addOrder(Order.asc("name"))
                .createCriteria("rigCapabilities").createCriteria("matchingCapabilitieses")
                .add(Restrictions.eq("requestCapabilities", requestCaps));

        /* Are all the rigs who have match rig capabilities to the
         * request capabilities. */
        for (Rig capRig : (List<Rig>) qu.list()) {
            if (!capRig.getRigType().isCodeAssignable())
                queue.setIsCodeAssignable(false);

            /* To be viable, only one rig needs to be online. */
            if (capRig.isOnline())
                queue.setViable(true);

            /* To be 'has free', only one rig needs to be free. */
            if (free = this.isRigFree(capRig, perm, ses))
                queue.setHasFree(true);

            /* Add target. */
            QueueTargetType target = new QueueTargetType();
            target.setViable(capRig.isOnline());
            target.setIsFree(free);
            queue.addQueueTarget(target);
            ResourceIDType resTarget = new ResourceIDType();
            resTarget.setType(ResourcePermission.RIG_PERMISSION);
            resTarget.setResourceID(capRig.getId().intValue());
            resTarget.setResourceName(capRig.getName());
            target.setResource(resTarget);
        }
    }

    return queue;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.queuer.intf.Queuer.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from www  .ja  v a2s .c o m
public CheckResourceAvailabilityResponse checkResourceAvailability(final CheckResourceAvailability request) {
    /* Request parameters. */
    ResourceIDType resReq = request.getCheckResourceAvailability();
    long rId = resReq.getResourceID();
    String type = resReq.getType(), name = resReq.getResourceName();
    this.logger.debug("Received " + this.getClass().getSimpleName() + "#checkResourceAvailability with params "
            + "resource type=" + type + ", resource identifier=" + rId + ", resource name=" + name + '.');

    /* Response parameters. */
    CheckResourceAvailabilityResponse resp = new CheckResourceAvailabilityResponse();
    QueueType queue = new QueueType();
    resp.setCheckResourceAvailabilityResponse(queue);
    queue.setViable(false);
    queue.setHasFree(false);
    queue.setIsCodeAssignable(false);

    /* This is always true because queueable/bookab;e is stored as a user 
     * class permission. There isn't enough information to determine this
     * so the best case is assumed. */
    queue.setIsQueuable(true);
    queue.setIsBookable(true);

    ResourceIDType resource = new ResourceIDType();
    queue.setQueuedResource(resource);
    resource.setType(type);

    if (!this.checkPermission(resReq)) {
        this.logger.warn("Unable to provide resource information because of insufficient permission.");
        return resp;
    }

    RigDao rigDao = new RigDao();
    try {
        Rig rig;
        RigTypeDao typeDao = new RigTypeDao(rigDao.getSession());
        RigType rigType;
        RequestCapabilitiesDao capsDao = new RequestCapabilitiesDao(rigDao.getSession());
        RequestCapabilities requestCaps;
        if (ResourcePermission.RIG_PERMISSION.equals(type) && ((rId > 0 && (rig = rigDao.get(rId)) != null)
                || (name != null && (rig = rigDao.findByName(name)) != null))) {
            /* Rig resource. */
            resource.setResourceID(rig.getId().intValue());
            resource.setResourceName(rig.getName());

            queue.setHasFree(rig.isOnline() && !rig.isInSession());
            queue.setViable(rig.isOnline());

            /* Code assignable is defined by the rig type of the rig. */
            queue.setIsCodeAssignable(rig.getRigType().isCodeAssignable());

            /* Only one resource, the actual rig. */
            QueueTargetType target = new QueueTargetType();
            target.setViable(rig.isOnline());
            target.setIsFree(rig.isOnline() && !rig.isInSession());
            target.setResource(resource);
            queue.addQueueTarget(target);

        } else if (ResourcePermission.TYPE_PERMISSION.equals(type)
                && ((rId > 0 && (rigType = typeDao.get(rId)) != null)
                        || (name != null && (rigType = typeDao.findByName(name)) != null))) {
            /* Rig type resource. */
            resource.setResourceID(rigType.getId().intValue());
            resource.setResourceName(rigType.getName());

            queue.setIsCodeAssignable(rigType.isCodeAssignable());

            /* The targets are the rigs in the rig type. */
            for (Rig r : rigType.getRigs()) {
                if (r.isOnline())
                    queue.setViable(true);
                if (r.isOnline() && !r.isInSession())
                    queue.setHasFree(true);

                QueueTargetType target = new QueueTargetType();
                target.setViable(r.isOnline());
                target.setIsFree(r.isOnline() && !r.isInSession());
                ResourceIDType resourceRig = new ResourceIDType();
                resourceRig.setType(ResourcePermission.RIG_PERMISSION);
                resourceRig.setResourceID(r.getId().intValue());
                resourceRig.setResourceName(r.getName());
                target.setResource(resourceRig);
                queue.addQueueTarget(target);
            }
        } else if (ResourcePermission.CAPS_PERMISSION.equals(type)
                && ((rId > 0 && (requestCaps = capsDao.get(rId)) != null)
                        || (name != null && (requestCaps = capsDao.findCapabilites(name)) != null))) {
            /* Capabilities resource. */
            resource.setResourceID(requestCaps.getId().intValue());
            resource.setResourceName(requestCaps.getCapabilities());

            /* For code assignable to be true, all rigs who match the
             * request capabilities, must be code assignable. */
            queue.setIsCodeAssignable(true);

            /* Are all the rigs who have match rig capabilities to the
             * request capabilities. */
            Criteria qu = rigDao.getSession().createCriteria(Rig.class).addOrder(Order.asc("name"))
                    .createCriteria("rigCapabilities").createCriteria("matchingCapabilitieses")
                    .add(Restrictions.eq("requestCapabilities", requestCaps));

            for (Rig capRig : (List<Rig>) qu.list()) {
                if (!capRig.getRigType().isCodeAssignable())
                    queue.setIsCodeAssignable(false);

                /* To be viable, only one rig needs to be online. */
                if (capRig.isOnline())
                    queue.setViable(true);

                /* To be 'has free', only one rig needs to be free. */
                if (capRig.isOnline() && !capRig.isInSession())
                    queue.setHasFree(true);

                /* Add target. */
                QueueTargetType target = new QueueTargetType();
                target.setViable(capRig.isOnline());
                target.setIsFree(capRig.isOnline() && !capRig.isInSession());
                queue.addQueueTarget(target);
                ResourceIDType resTarget = new ResourceIDType();
                resTarget.setType(ResourcePermission.RIG_PERMISSION);
                resTarget.setResourceID(capRig.getId().intValue());
                resTarget.setResourceName(capRig.getName());
                target.setResource(resTarget);
            }
        } else {
            this.logger.info(
                    "Unable to find resource of type " + type + " with ID " + rId + " and name " + name + '.');
            resource.setType("NOTFOUND");
        }
    } finally {
        rigDao.closeSession();
    }

    return resp;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  www.j  a  va  2 s  .c o  m*/
public QueryInfoResponse queryInfo(final QueryInfo queryInfo) {
    /** Request parameters. **/
    final QueryInfoType qIReq = queryInfo.getQueryInfo();
    String debug = "Received " + this.getClass().getSimpleName() + "#queryInfo with params:";
    debug += "Requestor: " + qIReq.getRequestor() + ", QuerySelect: " + qIReq.getQuerySelect();
    if (qIReq.getQueryFilter() != null) {
        debug += ", QueryFilter: " + qIReq.getQueryFilter();
    }
    debug += ", limit: " + qIReq.getLimit();
    this.logger.debug(debug);
    final RequestorType uid = qIReq.getRequestor();

    /** Response parameters. */
    final QueryInfoResponse resp = new QueryInfoResponse();
    final QueryInfoResponseType respType = new QueryInfoResponseType();
    respType.setTypeForQuery(TypeForQuery.RIG);
    resp.setQueryInfoResponse(respType);

    final org.hibernate.Session ses = DataAccessActivator.getNewSession();

    /* First Query Filter - this contains the main selection type to be selected */
    final QueryFilterType query0 = qIReq.getQuerySelect();

    try {
        Criteria cri;

        /* ----------------------------------------------------------------
         * -- Load the requestor.                                             --
         * ---------------------------------------------------------------- */
        final User user = this.getUserFromUserID(uid, ses);
        if (user == null) {
            this.logger.info("Unable to generate report because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return resp;
        }
        final String persona = user.getPersona();

        /* Check for type of query to determine selection parameters */
        if (query0.getTypeForQuery() == TypeForQuery.RIG) {
            /* ----------------------------------------------------------------
             * -- Rig Information only available to ADMIN, to be mediated    --
             * -- by interface. No criteria on Requestor                     --
             * ---------------------------------------------------------------- */

            cri = ses.createCriteria(Rig.class);
            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());

            cri.addOrder(Order.asc("name"));
            for (final Rig o : (List<Rig>) cri.list()) {
                respType.addSelectionResult(o.getName());
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.RIG_TYPE) {
            /* ----------------------------------------------------------------
             * -- Rig Type Information only available to ADMIN, to be        -- 
             * -- mediated by interface. No criteria on Requestor            --
             * ---------------------------------------------------------------- */
            cri = ses.createCriteria(RigType.class);

            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("name"));
            for (final RigType o : (List<RigType>) cri.list()) {
                respType.addSelectionResult(o.getName());
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.USER_CLASS) {
            cri = ses.createCriteria(UserClass.class);

            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("name"));

            /* ----------------------------------------------------------------
            * Check that the requestor has permissions to request the report.
            * If persona = USER, no reports (USERs will not get here)
            * If persona = ADMIN, any report 
            * If persona = ACADEMIC, only for classes they own if they can generate reports
            * ---------------------------------------------------------------- */

            if (User.ACADEMIC.equals(persona)) {
                DetachedCriteria apList = DetachedCriteria.forClass(AcademicPermission.class, "ap")
                        .add(Restrictions.eq("ap.canGenerateReports", true))
                        .setProjection(Property.forName("userClass"));

                cri.add(Subqueries.propertyIn("id", apList));

                for (final UserClass o : (List<UserClass>) cri.list()) {
                    respType.addSelectionResult(o.getName());
                }
            } else if (User.ADMIN.equals(persona)) {
                for (final UserClass o : (List<UserClass>) cri.list()) {
                    respType.addSelectionResult(o.getName());
                }
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.USER) {
            cri = ses.createCriteria(User.class, "u");

            /* ----------------------------------------------------------------
             * If persona = USER, no reports (USERs will not get here)
             * If persona = ADMIN, any report 
             * If persona = ACADEMIC, only for users in classes they own if they can genrate reports
             * ---------------------------------------------------------------- */

            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("name"));

            if (User.ACADEMIC.equals(persona)) {
                DetachedCriteria apList = DetachedCriteria.forClass(AcademicPermission.class, "ap")
                        .add(Restrictions.eq("ap.canGenerateReports", true))
                        .setProjection(Property.forName("userClass"));

                DetachedCriteria userList = DetachedCriteria.forClass(UserAssociation.class, "ua")
                        .add(Subqueries.propertyIn("ua.userClass", apList))
                        .setProjection(Property.forName("user.id"));

                cri.add(Subqueries.propertyIn("id", userList));

                for (final User o : (List<User>) cri.list()) {
                    respType.addSelectionResult(o.getNamespace() + ':' + o.getName());
                }
            } else if (User.ADMIN.equals(persona)) {
                for (final User o : (List<User>) cri.list()) {
                    respType.addSelectionResult(o.getNamespace() + ':' + o.getName());
                }
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.REQUEST_CAPABILITIES) {
            cri = ses.createCriteria(RequestCapabilities.class);
            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("capabilities", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("capabilities"));
            final List<RequestCapabilities> list = cri.list();
            for (final RequestCapabilities o : list) {
                respType.addSelectionResult(o.getCapabilities());
            }
        } else {
            this.logger.error(
                    "QueryInfo request failed because TypeForQuery does not have a valid value.  Value is "
                            + query0.getTypeForQuery().toString());
            return resp;
        }

        final QueryFilterType filter[] = qIReq.getQueryFilter();
        if (filter != null) {
            //DODGY Designed, not implemented
        }
    } finally {
        ses.close();
    }

    respType.setTypeForQuery(query0.getTypeForQuery());
    resp.setQueryInfoResponse(respType);

    return resp;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w w w  .j  a v a2 s . c  om*/
public QuerySessionAccessResponse querySessionAccess(final QuerySessionAccess querySessionAccess) {
    /* Request parameters. */
    final QuerySessionAccessType request = querySessionAccess.getQuerySessionAccess();
    final QueryFilterType filter = request.getQuerySelect();

    String debug = "Received " + this.getClass().getSimpleName()
            + "#querySessionAccess with params: select operator=" + filter.getOperator() + ", type="
            + filter.getTypeForQuery().toString() + ", like=" + filter.getQueryLike();
    if (request.getStartTime() != null)
        debug += ", start=" + request.getStartTime().getTime();
    if (request.getEndTime() != null)
        debug += ", end=" + request.getEndTime().getTime();
    this.logger.debug(debug);

    /* Response parameters. */
    final QuerySessionAccessResponse response = new QuerySessionAccessResponse();
    final QuerySessionAccessResponseType respType = new QuerySessionAccessResponseType();
    final PaginationType page = new PaginationType();
    page.setNumberOfPages(1);
    page.setPageLength(0);
    page.setPageNumber(1);
    respType.setPagination(page);
    response.setQuerySessionAccessResponse(respType);

    final org.hibernate.Session db = DataAccessActivator.getNewSession();
    try {
        RequestorType uid = request.getRequestor();
        final User requestor = this.getUserFromUserID(uid, db);
        if (requestor == null) {
            this.logger.info("Unable to generate report because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return response;
        }

        /* We are only interested in sessions that are complete. */
        Criteria query = db.createCriteria(Session.class).add(Restrictions.eq("active", Boolean.FALSE))
                .add(Restrictions.isNotNull("removalTime")).addOrder(Order.asc("requestTime"));

        /* If the user has requested a time period, only add that to query. */
        if (request.getStartTime() != null)
            query.add(Restrictions.ge("requestTime", request.getStartTime().getTime()));
        if (request.getEndTime() != null)
            query.add(Restrictions.le("requestTime", request.getEndTime().getTime()));

        if (request.getPagination() != null) {
            /* Add the requested pagination. */
            final PaginationType pages = request.getPagination();
            final int noPages = pages.getNumberOfPages();
            final int pageNumber = pages.getPageNumber();
            final int pageLength = pages.getPageLength();

            if (noPages > 1)
                query.setMaxResults(pageLength);
            if (pageNumber > 1)
                query.setFirstResult((pageNumber - 1) * pageLength);
        }

        if (filter.getTypeForQuery() == TypeForQuery.RIG) {
            /* Only administrators can do rig queries. */
            if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona()
                        + "' does not allow rig reporting.");
                return response;
            }

            query.add(Restrictions.eq("assignedRigName", filter.getQueryLike()));
        } else if (filter.getTypeForQuery() == TypeForQuery.RIG_TYPE) {
            /* Only administrators can do rig type queries. */
            if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona()
                        + "' does not allow rig type reporting.");
                return response;
            }

            final RigType rigType = new RigTypeDao(db).findByName(filter.getQueryLike());
            if (rigType == null) {
                this.logger.warn("Cannot provide session report because rig type '" + filter.getQueryLike()
                        + "' not found.");
                return response;
            }

            query.createCriteria("rig").add(Restrictions.eq("rigType", rigType));
        } else if (filter.getTypeForQuery() == TypeForQuery.REQUEST_CAPABILITIES) {
            /* Only administrators can do request capabilities queries. */
            if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona()
                        + "' does not allow request capabilities reporting.");
                return response;
            }

            final RequestCapabilities reqCaps = new RequestCapabilitiesDao(db)
                    .findCapabilites(filter.getQueryLike());
            if (reqCaps == null) {
                this.logger.warn("Cannot provide session report because request capabilities '"
                        + filter.getQueryLike() + "' not found.");
                return response;
            }

            List<Rig> capRigs = new ArrayList<Rig>();
            for (MatchingCapabilities match : reqCaps.getMatchingCapabilitieses()) {
                capRigs.addAll(match.getRigCapabilities().getRigs());
            }

            if (capRigs.size() == 0) {
                this.logger.warn(
                        "Cannot provide session report because there are no rigs with request capabilities '"
                                + reqCaps.getCapabilities() + "'.");
                return response;
            }

            query.add(Restrictions.in("rig", capRigs));
        } else if (filter.getTypeForQuery() == TypeForQuery.USER_CLASS) {
            final UserClass userClass = new UserClassDao(db).findByName(filter.getQueryLike());
            if (userClass == null) {
                this.logger.warn("Cannot provide session report because user class '" + filter.getQueryLike()
                        + "' was not found.");
                return response;
            }

            if (User.ACADEMIC.equals(requestor.getPersona())) {
                /* An academic may only generate reports for the classes 
                 * they have have reporting permission in. */
                boolean hasPerm = false;

                final Iterator<AcademicPermission> it = requestor.getAcademicPermissions().iterator();
                while (it.hasNext()) {
                    final AcademicPermission ap = it.next();
                    if (ap.getUserClass().getId().equals(userClass.getId()) && ap.isCanGenerateReports()) {
                        hasPerm = true;
                        break;
                    }
                }

                if (!hasPerm) {
                    this.logger.info("Unable to generate report for user class " + userClass.getName()
                            + " because the user " + requestor.qName()
                            + " does not own or have permission to report it.");
                    return response;
                }

                this.logger.debug("Academic " + requestor.qName()
                        + " has permission to generate report from user class " + userClass.getName() + '.');
            } else if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide a user session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona() + "' does not allow reporting.");
                return response;
            }

            query.createCriteria("resourcePermission").add(Restrictions.eq("userClass", userClass));
        } else if (filter.getTypeForQuery() == TypeForQuery.USER) {
            final User user = new UserDao(db).findByQName(filter.getQueryLike());
            if (user == null) {
                this.logger.warn("Cannot provide session report because user  '" + filter.getQueryLike()
                        + "' was not found.");
                return response;
            }

            if (User.ACADEMIC.equals(requestor.getPersona())) {
                /* The report can only contain sessions originating from the user
                 * classes the academic has reporting permission in. */
                List<ResourcePermission> perms = new ArrayList<ResourcePermission>();

                final Iterator<AcademicPermission> it = requestor.getAcademicPermissions().iterator();
                while (it.hasNext()) {
                    final AcademicPermission ap = it.next();
                    if (!ap.isCanGenerateReports())
                        continue;

                    perms.addAll(ap.getUserClass().getResourcePermissions());
                }

                if (perms.size() == 0) {
                    this.logger.info("Unable to generate report for user " + user.qName() + " because the user "
                            + requestor.qName() + " does not own or have permission to report "
                            + "on any of the users permissions.");
                    return response;
                }

                query.add(Restrictions.in("resourcePermission", perms));
            } else if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide a user session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona() + "' does not allow reporting.");
                return response;
            }

            query.add(Restrictions.eq("user", user));
        } else {
            this.logger.error("Cannot provide a session report because the query type '"
                    + filter.getTypeForQuery().toString() + "' was not understood.");
            return response;
        }

        for (final Session s : (List<Session>) query.list()) {
            final AccessReportType report = new AccessReportType();

            /* Set user who was in session. */
            final RequestorType sUser = new RequestorType();
            final UserNSNameSequence nsSequence = new UserNSNameSequence();
            nsSequence.setUserName(s.getUserName());
            nsSequence.setUserNamespace(s.getUserNamespace());
            sUser.setRequestorNSName(nsSequence);
            sUser.setUserQName(s.getUserNamespace() + ':' + s.getUserName());
            report.setUser(sUser);

            /* User class. */
            if (s.getResourcePermission() != null)
                report.setUserClass(s.getResourcePermission().getUserClass().getName());

            /* Rig details. */
            report.setRigName(s.getAssignedRigName());
            if (s.getRig() != null)
                report.setRigType(s.getRig().getRigType().getName());

            /* Session start. */
            Calendar cal = Calendar.getInstance();
            cal.setTime(s.getRequestTime());
            report.setQueueStartTime(cal);

            /* Session timings. */
            if (s.getAssignmentTime() != null) {
                final int queueD = (int) ((s.getAssignmentTime().getTime() - s.getRequestTime().getTime())
                        / 1000);
                report.setQueueDuration(queueD);
                cal = Calendar.getInstance();
                cal.setTime(s.getAssignmentTime());
                report.setSessionStartTime(cal);
                final int sessionD = (int) ((s.getRemovalTime().getTime() - s.getAssignmentTime().getTime())
                        / 1000);
                report.setSessionDuration(sessionD);
            } else {
                final int queueD = (int) ((s.getRemovalTime().getTime() - s.getRequestTime().getTime()) / 1000);
                report.setQueueDuration(queueD);

                cal = Calendar.getInstance();
                cal.setTime(s.getRemovalTime());
                report.setSessionStartTime(cal);
                report.setSessionDuration(0);
            }

            /* Session end. */
            cal = Calendar.getInstance();
            cal.setTime(s.getRemovalTime());
            report.setSessionEndTime(cal);
            report.setReasonForTermination(s.getRemovalReason());

            respType.addAccessReportData(report);
        }

    } finally {
        db.close();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w w w  .  j  a va2 s. c o m
public QuerySessionReportResponse querySessionReport(final QuerySessionReport querySessionReport) {
    /** Request parameters. **/
    final QuerySessionReportType qSRReq = querySessionReport.getQuerySessionReport();
    String debug = "Received " + this.getClass().getSimpleName() + "#querySessionReport with params:";
    debug += "Requestor: " + qSRReq.getRequestor() + ", QuerySelect: " + qSRReq.getQuerySelect().toString();
    if (qSRReq.getQueryConstraints() != null) {
        debug += ", QueryConstraints: " + qSRReq.getQueryConstraints().toString(); //DODGY only first displayed
    }
    debug += ", start time: " + qSRReq.getStartTime() + ", end time: " + qSRReq.getEndTime() + ", pagination: "
            + qSRReq.getPagination();
    this.logger.debug(debug);
    final RequestorType uid = qSRReq.getRequestor();

    /** Response parameters. */
    final QuerySessionReportResponse resp = new QuerySessionReportResponse();
    final QuerySessionReportResponseType respType = new QuerySessionReportResponseType();
    final PaginationType page = new PaginationType();
    page.setNumberOfPages(1);
    page.setPageLength(0);
    page.setPageNumber(1);
    respType.setPagination(page);
    respType.setSessionCount(0);
    respType.setTotalQueueDuration(0);
    respType.setTotalSessionDuration(0);
    resp.setQuerySessionReportResponse(respType);

    final org.hibernate.Session ses = DataAccessActivator.getNewSession();

    /* Set up query from request parameters*/
    try {
        /* ----------------------------------------------------------------
         * -- Load the requestor.                                             --
         * ---------------------------------------------------------------- */
        final User user = this.getUserFromUserID(uid, ses);
        if (user == null) {
            this.logger.info("Unable to generate report because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return resp;
        }
        final String persona = user.getPersona();

        final Criteria cri = ses.createCriteria(Session.class);
        // Order by request time
        cri.addOrder(Order.asc("requestTime"));

        /* Add restriction - removal time cannot be null - these are in session records */
        cri.add(Restrictions.isNotNull("removalTime"));

        /* First Query Filter - this contains grouping for the query */
        final QueryFilterType query0 = qSRReq.getQuerySelect();

        /* ----------------------------------------------------------------
         * -- Get the Query type and process accordingly                 --
         * -- 1. Rig                                                     --
         * -- 2. Rig Type                                                --
         * -- 3. User Class                                              --
         * -- 4. User                                                    --
         * -- 5. Capabilities (not yet implemented)                      --
         * ---------------------------------------------------------------- */
        if (query0.getTypeForQuery() == TypeForQuery.RIG) {
            /* ----------------------------------------------------------------
             * -- 1. Rig Information only available to ADMIN, to be mediated --
             * --    by interface. No criteria on Requestor                  --
             * ---------------------------------------------------------------- */

            /* ----------------------------------------------------------------
             * -- 1a. Get Sessions that match the rig                        --
             * ---------------------------------------------------------------- */

            cri.add(Restrictions.eq("assignedRigName", query0.getQueryLike()));
            // Select time period
            if (qSRReq.getStartTime() != null) {
                cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime()));
            }
            if (qSRReq.getEndTime() != null) {
                cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime()));
            }

            Long idCount = new Long(-1);
            final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>(
                    new UserComparator());
            /* Contains list of users without user_id in session.  Indexed with namespace:name */
            final Map<String, SessionStatistics> userMap = new HashMap<String, SessionStatistics>();

            final List<Session> list = cri.list();
            for (final Session o : list) {
                /* ----------------------------------------------------------------
                 * -- 1b. Iterate through sessions and create user records       --
                 * ---------------------------------------------------------------- */

                /* Create check for user_id not being null - deleted user */
                if (o.getUser() != null) {
                    final User u = o.getUser();

                    if (recordMap.containsKey(u)) {
                        recordMap.get(u).addRecord(o);
                    } else {
                        final SessionStatistics userRec = new SessionStatistics();
                        userRec.addRecord(o);
                        recordMap.put(u, userRec);
                    }
                } else {
                    final String nameIndex = o.getUserNamespace() + QNAME_DELIM + o.getUserName();
                    /* Does 'namespace:name' indexed list contain user */
                    if (userMap.containsKey(nameIndex)) {
                        userMap.get(nameIndex).addRecord(o);
                    } else {
                        final User u = new User();
                        u.setName(o.getUserName());
                        u.setNamespace(o.getUserNamespace());
                        u.setId(idCount);
                        idCount--;

                        final SessionStatistics userRec = new SessionStatistics();
                        userRec.addRecord(o);
                        recordMap.put(u, userRec);
                        userMap.put(nameIndex, userRec);
                    }
                }
            }

            /* ----------------------------------------------------------------
             * -- 1c. Get pagination requirements so correct records are     -- 
             * --     returned.                                              --
             * ---------------------------------------------------------------- */

            int pageNumber = 1;
            int pageLength = recordMap.size();
            int recordCount = 0;
            int totalSessionCount = 0;
            int totalSessionDuration = 0;
            int totalQueueDuration = 0;

            if (qSRReq.getPagination() != null) {
                final PaginationType pages = qSRReq.getPagination();
                pageNumber = pages.getPageNumber();
                pageLength = pages.getPageLength();

                respType.setPagination(page);

            }

            /* ----------------------------------------------------------------
             * -- 1d. Iterate through user records and calculate report data --
             * ---------------------------------------------------------------- */

            for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) {
                recordCount++;
                totalSessionCount += e.getValue().getSessionCount();
                totalQueueDuration += e.getValue().getTotalQueueDuration();
                totalSessionDuration += e.getValue().getTotalSessionDuration();
                if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) {
                    final SessionReportType reportType = new SessionReportType();

                    //Get user from session object
                    final RequestorType user0 = new RequestorType();
                    final UserNSNameSequence nsSequence = new UserNSNameSequence();
                    nsSequence.setUserName(e.getKey().getName());
                    nsSequence.setUserNamespace(e.getKey().getNamespace());
                    user0.setRequestorNSName(nsSequence);
                    reportType.setUser(user0);

                    reportType.setRigName(query0.getQueryLike());

                    reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration());
                    reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration());
                    reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration());
                    reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration());
                    reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration());

                    reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration());
                    reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration());
                    reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration());
                    reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration());
                    reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration());

                    reportType.setSessionCount(e.getValue().getSessionCount());

                    respType.addSessionReport(reportType);
                }

            }

            respType.setSessionCount(totalSessionCount);
            respType.setTotalQueueDuration(totalQueueDuration);
            respType.setTotalSessionDuration(totalSessionDuration);

            resp.setQuerySessionReportResponse(respType);
        }

        else if (query0.getTypeForQuery() == TypeForQuery.RIG_TYPE) {
            /* ----------------------------------------------------------------
             * -- 2. Rig Type Information only available to ADMIN, to be     -- 
             * --    mediated by interface. No criteria on Requestor         --
             * ---------------------------------------------------------------- */

            final RigTypeDao rTypeDAO = new RigTypeDao(ses);
            final RigType rType = rTypeDAO.findByName(query0.getQueryLike());

            if (rType == null) {
                this.logger.warn("No valid rig type found - " + query0.getTypeForQuery().toString());
                return resp;
            }

            /* ----------------------------------------------------------------
             * -- 2a. Get Sessions that match the rig type                   --
             * ---------------------------------------------------------------- */

            // Select Sessions where rig value is of the correct Rig Type
            cri.createCriteria("rig").add(Restrictions.eq("rigType", rType));

            // Select time period
            if (qSRReq.getStartTime() != null) {
                cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime()));
            }
            if (qSRReq.getEndTime() != null) {
                cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime()));
            }

            Long idCount = new Long(-1);

            final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>(
                    new UserComparator());
            /* Contains list of users without user_id in session.  Indexed with namespace:name */
            final Map<String, SessionStatistics> userMap = new HashMap<String, SessionStatistics>();

            final List<Session> list = cri.list();
            for (final Session o : list) {
                /* ----------------------------------------------------------------
                 * -- 2b. Iterate through sessions and create user records       --
                 * ---------------------------------------------------------------- */

                /* Create check for user_id not being null - deleted user */
                if (o.getUser() != null) {
                    final User u = o.getUser();

                    if (recordMap.containsKey(u)) {
                        recordMap.get(u).addRecord(o);
                    } else {
                        final SessionStatistics userRec = new SessionStatistics();
                        userRec.addRecord(o);
                        recordMap.put(u, userRec);
                    }
                } else {
                    final String nameIndex = o.getUserNamespace() + QNAME_DELIM + o.getUserName();
                    /* Does 'namespace:name' indexed list contain user */
                    if (userMap.containsKey(nameIndex)) {
                        userMap.get(nameIndex).addRecord(o);
                    } else {
                        final User u = new User();
                        u.setName(o.getUserName());
                        u.setNamespace(o.getUserNamespace());
                        u.setId(idCount);
                        idCount--;

                        final SessionStatistics userRec = new SessionStatistics();
                        userRec.addRecord(o);
                        recordMap.put(u, userRec);
                        userMap.put(nameIndex, userRec);
                    }
                }

            }

            /* ----------------------------------------------------------------
             * -- 2c. Get pagination requirements so correct records are     -- 
             * --     returned.                                              --
             * ---------------------------------------------------------------- */

            int pageNumber = 1;
            int pageLength = recordMap.size();
            int recordCount = 0;
            int totalSessionCount = 0;
            int totalSessionDuration = 0;
            int totalQueueDuration = 0;

            if (qSRReq.getPagination() != null) {
                final PaginationType pages = qSRReq.getPagination();
                pageNumber = pages.getPageNumber();
                pageLength = pages.getPageLength();
            }

            /* ----------------------------------------------------------------
             * -- 2d. Iterate through user records and calculate report data --
             * ---------------------------------------------------------------- */

            for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) {
                recordCount++;
                totalSessionCount += e.getValue().getSessionCount();
                totalQueueDuration += e.getValue().getTotalQueueDuration();
                totalSessionDuration += e.getValue().getTotalSessionDuration();
                if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) {
                    final SessionReportType reportType = new SessionReportType();

                    //Get user from session object
                    final RequestorType user0 = new RequestorType();
                    final UserNSNameSequence nsSequence = new UserNSNameSequence();
                    nsSequence.setUserName(e.getKey().getName());
                    nsSequence.setUserNamespace(e.getKey().getNamespace());
                    user0.setRequestorNSName(nsSequence);
                    reportType.setUser(user0);

                    reportType.setRigType(rType.getName());

                    reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration());
                    reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration());
                    reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration());
                    reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration());
                    reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration());

                    reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration());
                    reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration());
                    reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration());
                    reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration());
                    reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration());

                    reportType.setSessionCount(e.getValue().getSessionCount());

                    respType.addSessionReport(reportType);
                }
            }

            respType.setSessionCount(totalSessionCount);
            respType.setTotalQueueDuration(totalQueueDuration);
            respType.setTotalSessionDuration(totalSessionDuration);

            resp.setQuerySessionReportResponse(respType);

        }

        else if (query0.getTypeForQuery() == TypeForQuery.USER_CLASS) {
            /* ----------------------------------------------------------------
             * -- 3. User Class Information only available to ADMIN and      -- 
             * --    ACADEMIC users with permissions to generate reports     --
             * --    for this class.                                         --
             * ---------------------------------------------------------------- */

            final UserClassDao uClassDAO = new UserClassDao(ses);
            final UserClass uClass = uClassDAO.findByName(query0.getQueryLike());
            if (uClass == null) {
                this.logger.warn("No valid user class found - " + query0.getTypeForQuery().toString());
                return resp;
            }

            /* ----------------------------------------------------------------
             * Check that the requestor has permissions to request the report.
             * If persona = USER, no reports (USERs will not get here)
             * If persona = ADMIN, any report 
             * If persona = ACADEMIC, only for classes they own if they can genrate reports
             * ---------------------------------------------------------------- */
            if (User.ACADEMIC.equals(persona)) {
                /* An academic may generate reports for their own classes only. */
                boolean hasPerm = false;

                final Iterator<AcademicPermission> apIt = user.getAcademicPermissions().iterator();
                while (apIt.hasNext()) {
                    final AcademicPermission ap = apIt.next();
                    if (ap.getUserClass().getId().equals(uClass.getId()) && ap.isCanGenerateReports()) {
                        hasPerm = true;
                        break;
                    }
                }

                if (!hasPerm) {
                    this.logger.info("Unable to generate report for user class " + uClass.getName()
                            + " because the user " + user.getNamespace() + ':' + user.getName()
                            + " does not own or have academic permission to it.");
                    return resp;
                }

                this.logger.debug("Academic " + user.getNamespace() + ':' + user.getName()
                        + " has permission to " + "generate report from user class" + uClass.getName() + '.');
            }

            /* ----------------------------------------------------------------
             * -- 3a. Get Sessions that match the user class                --
             * ---------------------------------------------------------------- */

            //Select sessions where the resource permission associated is for this user class    
            cri.createCriteria("resourcePermission").add(Restrictions.eq("userClass", uClass));

            // Select time period
            if (qSRReq.getStartTime() != null) {
                cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime()));
            }
            if (qSRReq.getEndTime() != null) {
                cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime()));
            }

            //Query Filter to be used for multiple selections in later versions of reporting. 
            //QueryFilterType queryFilters[] = qSAReq.getQueryConstraints();

            final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>(
                    new UserComparator());

            final List<Session> list = cri.list();
            for (final Session o : list) {
                /* ----------------------------------------------------------------
                 * -- 3b. Iterate through sessions and create user records       --
                 * ---------------------------------------------------------------- */

                /* Create check for user_id not being null - deleted user */
                if (o.getUser() != null) {
                    final User u = o.getUser();

                    if (recordMap.containsKey(u)) {
                        recordMap.get(u).addRecord(o);
                    } else {
                        final SessionStatistics userRec = new SessionStatistics();
                        userRec.addRecord(o);
                        recordMap.put(u, userRec);
                    }
                }
            }

            /* ----------------------------------------------------------------
             * -- 3c. Get pagination requirements so correct records are     -- 
             * --     returned.                                              --
             * ---------------------------------------------------------------- */

            int pageNumber = 1;
            int pageLength = recordMap.size();
            int recordCount = 0;
            int totalSessionCount = 0;
            int totalSessionDuration = 0;
            int totalQueueDuration = 0;

            if (qSRReq.getPagination() != null) {
                final PaginationType pages = qSRReq.getPagination();
                pageNumber = pages.getPageNumber();
                pageLength = pages.getPageLength();

            }

            /* ----------------------------------------------------------------
             * -- 3d. Iterate through user records and calculate report data --
             * ---------------------------------------------------------------- */

            for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) {
                recordCount++;
                totalSessionCount += e.getValue().getSessionCount();
                totalQueueDuration += e.getValue().getTotalQueueDuration();
                totalSessionDuration += e.getValue().getTotalSessionDuration();
                if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) {
                    final SessionReportType reportType = new SessionReportType();

                    //Get user from session object
                    final RequestorType user0 = new RequestorType();
                    final UserNSNameSequence nsSequence = new UserNSNameSequence();
                    nsSequence.setUserName(e.getKey().getName());
                    nsSequence.setUserNamespace(e.getKey().getNamespace());
                    user0.setRequestorNSName(nsSequence);
                    reportType.setUser(user0);

                    reportType.setUserClass(uClass.getName());

                    reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration());
                    reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration());
                    reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration());
                    reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration());
                    reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration());

                    reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration());
                    reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration());
                    reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration());
                    reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration());
                    reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration());

                    reportType.setSessionCount(e.getValue().getSessionCount());

                    respType.addSessionReport(reportType);
                }
            }

            respType.setSessionCount(totalSessionCount);
            respType.setTotalQueueDuration(totalQueueDuration);
            respType.setTotalSessionDuration(totalSessionDuration);

            resp.setQuerySessionReportResponse(respType);

        }

        else if (query0.getTypeForQuery() == TypeForQuery.USER) {
            /* ----------------------------------------------------------------
             * -- 4. User Information only available to ADMIN and            -- 
             * --    ACADEMIC users with permissions to generate reports     --
             * --    for this classes to which this user belongs.            --
             * -- NOTE: User nam expected as: namespace:username             --
             * ---------------------------------------------------------------- */

            final UserDao userDAO = new UserDao(ses);
            final String idParts[] = query0.getQueryLike().split(Reports.QNAME_DELIM, 2);
            final String ns = idParts[0];
            final String name = (idParts.length > 1) ? idParts[1] : idParts[0];
            final User user0 = userDAO.findByName(ns, name);

            if (user0 == null) {
                this.logger.warn("No valid user found - " + query0.getTypeForQuery().toString());
                return resp;
            }

            /* ----------------------------------------------------------------
             * Check that the requestor has permissions to request the report.
             * If persona = USER, no reports (USERs will not get here)
             * If persona = ADMIN, any report 
             * If persona = ACADEMIC, only for users belonging to 
             *    classes they can generate reports for
             * ---------------------------------------------------------------- */
            if (User.ACADEMIC.equals(persona)) {
                /* An academic may generate reports for their own classes only. */
                boolean hasPerm = false;

                final Iterator<AcademicPermission> apIt = user.getAcademicPermissions().iterator();
                while (apIt.hasNext()) {
                    final AcademicPermission ap = apIt.next();
                    final Iterator<UserAssociation> uaIt = user0.getUserAssociations().iterator();
                    while (uaIt.hasNext()) {
                        final UserAssociation ua = uaIt.next();
                        if (ap.getUserClass().getId().equals(ua.getUserClass().getId())
                                && ap.isCanGenerateReports()) {
                            hasPerm = true;
                            break;
                        }
                    }
                    if (hasPerm) {
                        break;
                    }
                }

                if (!hasPerm) {
                    this.logger.info("Unable to generate report for user class " + user0.getName()
                            + " because the user " + user.getNamespace() + ':' + user.getName()
                            + " does not own or have academic permission to it.");
                    return resp;
                }

                this.logger.debug("Academic " + user.getNamespace() + ':' + user.getName()
                        + " has permission to " + "generate report from user class" + user0.getName() + '.');
            }

            /* ----------------------------------------------------------------
             * -- 4a. Get Sessions that match the user                       --
             * ---------------------------------------------------------------- */

            //Select sessions where the resource permission associated is for this user class    
            cri.add(Restrictions.eq("user", user0));

            // Select time period
            if (qSRReq.getStartTime() != null) {
                cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime()));
            }
            if (qSRReq.getEndTime() != null) {
                cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime()));
            }

            //Query Filter to be used for multiple selections in later versions of reporting. 
            //QueryFilterType queryFilters[] = qSAReq.getQueryConstraints();

            final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>(
                    new UserComparator());

            final List<Session> list = cri.list();
            for (final Session o : list) {
                /* ----------------------------------------------------------------
                 * -- 4b. Iterate through sessions and create user records       --
                 * ---------------------------------------------------------------- */

                final User u = o.getUser();

                if (recordMap.containsKey(u)) {
                    recordMap.get(u).addRecord(o);
                } else {
                    final SessionStatistics userRec = new SessionStatistics();
                    userRec.addRecord(o);
                    recordMap.put(u, userRec);
                }
            }

            /* ----------------------------------------------------------------
             * -- 4c. Get pagination requirements so correct records are     -- 
             * --     returned.                                              --
             * ---------------------------------------------------------------- */

            int pageNumber = 1;
            int pageLength = recordMap.size();
            int recordCount = 0;
            int totalSessionCount = 0;
            int totalSessionDuration = 0;
            int totalQueueDuration = 0;

            if (qSRReq.getPagination() != null) {
                final PaginationType pages = qSRReq.getPagination();
                pageNumber = pages.getPageNumber();
                pageLength = pages.getPageLength();

            }

            /* ----------------------------------------------------------------
             * -- 4d. Iterate through user records and calculate report data --
             * ---------------------------------------------------------------- */

            for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) {
                recordCount++;
                totalSessionCount += e.getValue().getSessionCount();
                totalQueueDuration += e.getValue().getTotalQueueDuration();
                totalSessionDuration += e.getValue().getTotalSessionDuration();
                if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) {
                    final SessionReportType reportType = new SessionReportType();

                    //Get user from session object
                    final RequestorType user1 = new RequestorType();
                    final UserNSNameSequence nsSequence = new UserNSNameSequence();
                    nsSequence.setUserName(e.getKey().getName());
                    nsSequence.setUserNamespace(e.getKey().getNamespace());
                    user1.setRequestorNSName(nsSequence);
                    reportType.setUser(user1);

                    reportType.setUser(user1);

                    reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration());
                    reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration());
                    reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration());
                    reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration());
                    reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration());

                    reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration());
                    reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration());
                    reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration());
                    reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration());
                    reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration());

                    reportType.setSessionCount(e.getValue().getSessionCount());

                    respType.addSessionReport(reportType);
                }
            }

            respType.setSessionCount(totalSessionCount);
            respType.setTotalQueueDuration(totalQueueDuration);
            respType.setTotalSessionDuration(totalSessionDuration);

            resp.setQuerySessionReportResponse(respType);

        }

    }

    finally {
        ses.close();
    }

    return resp;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.rigmanagement.impl.RigMaintenanceNotifier.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//w  w  w .  j a v  a 2s .  c o  m
public void run() {
    org.hibernate.Session db = DataAccessActivator.getNewSession();
    if (db == null) {
        this.logger
                .error("Unable to run rig maintenance notification service because unable to obtain a database "
                        + "session.");
        return;
    }

    Date ps = new Date();
    Date pe = new Date(System.currentTimeMillis() + RUN_PERIOD * 1000);

    try {
        /* ----------------------------------------------------------------
         * -- For maintenance periods that are starting, terminate the   --
         * -- rig's session and set the rig to maintenance mode.         --
         * ---------------------------------------------------------------- */
        Criteria qu = db.createCriteria(RigOfflineSchedule.class).add(Restrictions.eq("active", Boolean.TRUE))
                .add(Restrictions.ge("startTime", ps)).add(Restrictions.lt("startTime", pe))
                .createCriteria("rig").add(Restrictions.eq("active", Boolean.TRUE))
                .add(Restrictions.eq("online", Boolean.TRUE));

        for (RigOfflineSchedule sched : (List<RigOfflineSchedule>) qu.list()) {
            Rig rig = sched.getRig();
            this.logger.info("Going to notify rig " + rig.getName() + " to go into maintenance state at time "
                    + ps + '.');

            /* Check the rig isn't in session, if it is terminate the session. */
            if (sched.getRig().isInSession()) {

                Session ses = rig.getSession();
                this.logger.info("Need to kick off user " + ses.getUser().qName() + " from rig " + rig.getName()
                        + " because rig is going into maintenance.");
                ses.setActive(false);
                ses.setRemovalTime(pe);
                ses.setRemovalReason("Rig going into maintenance.");

                if (this.notTest)
                    new RigReleaser().release(ses, db);
            }

            rig.setOnline(false);
            rig.setOfflineReason("Rig going into maintenance.");
            new RigLogDao(db).addOfflineLog(rig, "Maintenance period starting.");

            db.beginTransaction();
            db.flush();
            db.getTransaction().commit();

            if (this.notTest)
                new RigMaintenance().putMaintenance(rig, true, db);
        }

        /* ----------------------------------------------------------------
         * -- For maintenance periods that are ending, notify the rig to --
         * -- end maintenance mode.                                      --
         * ---------------------------------------------------------------- */
        qu = db.createCriteria(RigOfflineSchedule.class).add(Restrictions.eq("active", Boolean.TRUE))
                .add(Restrictions.ge("endTime", ps)).add(Restrictions.lt("endTime", pe));

        List<RigOfflineSchedule> endOffline = qu.list();
        for (RigOfflineSchedule sched : endOffline) {
            sched.setActive(false);

            Rig rig = sched.getRig();
            if (rig.isActive()) {
                this.logger.info("Going to notify rig " + rig.getName() + " to clear maintenance state at time "
                        + ps + '.');
                if (this.notTest)
                    new RigMaintenance().clearMaintenance(rig, db);
            } else {
                this.logger.warn("Mainteance period for rig " + rig.getName() + " is ending but it is not "
                        + "registered.");
            }

            /* Notify the booking engine. */
            BookingEngineService service = RigManagementActivator.getBookingService();
            if (service != null)
                service.clearRigOffline(sched, db);
        }

        if (endOffline.size() > 0) {
            db.beginTransaction();
            db.flush();
            db.getTransaction().commit();
        }
    } catch (HibernateException ex) {
        this.logger
                .error("Caught database exception in rig maintenance notification service. Exception reason: "
                        + ex.getMessage() + '.');

        if (db.isDirty()) {
            db.getTransaction().rollback();
        }
    } finally {
        db.close();
    }
}