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:au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.SessionDao.java

License:Open Source License

/**
 * Gets the users active session. If the user does not have an active 
 * session <code>null</code> is returned. If the user has multiple
 * active sessions, only the lastest (ordered by request time) is 
 * returned.//from w w w  . j  ava2s .c o  m
 * 
 * @param user user to find active session of
 * @return active session or null
 */
@SuppressWarnings("unchecked")
public Session findActiveSession(User user) {
    Criteria cri = this.session.createCriteria(Session.class);
    cri.add(Restrictions.eq("user", user));
    cri.add(Restrictions.eq("active", Boolean.TRUE));
    cri.addOrder(Order.desc("requestTime"));
    cri.setMaxResults(1);

    List<Session> sessions = cri.list();
    if (sessions.size() == 0) {
        return null;
    }
    return sessions.get(0);
}

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

License:Open Source License

/**
 * Returns info for an active session on the specified rig
 * /*from w  w w  . j ava2 s.  c om*/
 * @param user user to find active session of
 * @return active session or null
 */
@SuppressWarnings("unchecked")
public SlaveableRigs getInfo(Rig rig) {
    Criteria cri = this.session.createCriteria(SlaveableRigs.class);
    cri.add(Restrictions.eq("rig", rig));
    cri.addOrder(Order.desc("id"));
    cri.setMaxResults(1);

    List<SlaveableRigs> sessions = cri.list();
    if (sessions.size() == 0) {
        return null;
    }
    return sessions.get(0);
}

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

License:Open Source License

/**
 * Finishes the collaborative session/*from ww  w. jav a  2 s . c  om*/
 * 
 * @param user user to find active session of
 * @return active session or null
 */
@SuppressWarnings("unchecked")
public void finishCol(Rig rig) {
    Criteria cri = this.session.createCriteria(SlaveableRigs.class);
    cri.add(Restrictions.eq("rig", rig));
    cri.addOrder(Order.desc("id"));

    List<SlaveableRigs> sessions = cri.list();
    for (SlaveableRigs s : sessions) {
        this.delete(s);
    }
}

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. //from   w  ww  .ja  v  a  2 s . com
 * 
 * @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.reports.intf.Reports.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*ww w .j  a v a2 s  .  com*/
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/*  w ww.  java  2s  .  com*/
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.org.theark.admin.model.dao.AdminDao.java

License:Open Source License

private Criteria buildArkModuleFunctionCriteria(ArkModuleFunction arkModuleFunctionCriteria) {
    Criteria criteria = getSession().createCriteria(ArkModuleFunction.class);

    if (arkModuleFunctionCriteria.getArkModule() != null
            && arkModuleFunctionCriteria.getArkModule().getId() != null) {
        criteria.add(Restrictions.eq("arkModule", arkModuleFunctionCriteria.getArkModule()));
    }/*  w  ww. j  a  v  a2  s  .  c  o m*/

    criteria.createAlias("arkModule", "module");
    criteria.addOrder(Order.asc("module.name"));
    criteria.addOrder(Order.asc("functionSequence"));

    return criteria;
}

From source file:au.org.theark.admin.model.dao.AdminDao.java

License:Open Source License

public List<ArkFunction> getArkFunctionListByArkModule(ArkModule arkModule) {
    Criteria criteria = getSession().createCriteria(ArkModuleFunction.class);
    if (arkModule.getId() != null) {
        criteria.add(Restrictions.eq("arkModule", arkModule));
    }//  w  ww .  jav  a  2  s .c  o m
    criteria.createAlias("arkModule", "module");
    criteria.addOrder(Order.asc("module.name"));
    criteria.addOrder(Order.asc("functionSequence"));

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("arkFunction"), "arkFunction");
    criteria.setProjection(projectionList);
    return criteria.list();
}

From source file:au.org.theark.admin.model.dao.AdminDao.java

License:Open Source License

private Criteria buildArkRoleCriteria(ArkRole arkRoleCriteria) {
    Criteria criteria = getSession().createCriteria(ArkRole.class);

    if (arkRoleCriteria.getId() != null) {
        criteria.add(Restrictions.eq("id", arkRoleCriteria.getId()));
    }/*www.  ja va2 s .c o  m*/

    if (arkRoleCriteria.getName() != null) {
        criteria.add(Restrictions.eq("name", arkRoleCriteria.getName()));
    }

    if (arkRoleCriteria.getDescription() != null) {
        criteria.add(Restrictions.ilike("description", arkRoleCriteria.getName(), MatchMode.ANYWHERE));
    }

    criteria.addOrder(Order.asc("id"));
    return criteria;
}

From source file:au.org.theark.admin.model.dao.AdminDao.java

License:Open Source License

public List<ArkModule> getArkModuleListByArkRole(ArkRole arkRole) {
    Criteria criteria = getSession().createCriteria(ArkModuleRole.class);
    if (arkRole != null) {
        criteria.add(Restrictions.eq("arkRole", arkRole));
    }/* ww w. jav  a 2  s .  c  o  m*/
    criteria.createAlias("arkModule", "module");
    criteria.addOrder(Order.asc("module.name"));

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("arkModule"), "arkModule");
    criteria.setProjection(projectionList);
    return criteria.list();
}