Example usage for org.hibernate.criterion Restrictions le

List of usage examples for org.hibernate.criterion Restrictions le

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions le.

Prototype

public static SimpleExpression le(String propertyName, Object value) 

Source Link

Document

Apply a "less than or equal" constraint to the named property

Usage

From source file:TestClientWithTimestamps.java

License:BSD License

/**
 * This example demonstrates the use of Hibernate detached criteria objects
 * to formulate and perform more sophisticated searches. for more
 * information, please consult the Hibernate documentation at
 * http://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/DetachedCriteria.html
 *///from w  w w.j a v a  2  s  . c  o  m
@SuppressWarnings("unused")
private static void searchSNPAnnoation() {
    DetachedCriteria criteria = DetachedCriteria.forClass(SNPAnnotation.class);
    criteria.add(Restrictions.ge("chromosomeLocation", new Integer(4000000)));
    criteria.add(Restrictions.le("chromosomeLocation", new Integer(4200000)));
    criteria.add(Restrictions.eq("chromosomeName", "1"));
    try {
        System.out.println("______________________________________________________________________");
        System.out.println("Retrieving all SNPAnnotations for Chr 1,4000000 - 4200000");
        ApplicationService appService = ApplicationServiceProvider.getApplicationService();

        List resultList = appService.query(criteria, SNPAnnotation.class.getName());
        if (resultList != null) {
            System.out.println("Number of results returned: " + resultList.size());
            System.out.println("DbsnpId" + "\t" + "ChromosomeName" + "\t" + "ChromosomeLocation" + "\t"
                    + "GenomeBuild" + "\t" + "ReferenceSequence" + "\t" + "ReferenceStrand" + "\t"
                    + "GeneBiomarker(s)" + "\n");
            for (Iterator resultsIterator = resultList.iterator(); resultsIterator.hasNext();) {
                SNPAnnotation returnedObj = (SNPAnnotation) resultsIterator.next();
                System.out.println(returnedObj.getDbsnpId() + "\t" + returnedObj.getChromosomeName() + "\t"
                        + returnedObj.getChromosomeLocation() + "\t" + returnedObj.getGenomeBuild() + "\t"
                        + returnedObj.getReferenceSequence() + "\t" + returnedObj.getReferenceStrand() + "\t"
                        + pipeGeneBiomarkers(returnedObj.getGeneBiomarkerCollection()) + "\n");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:analysers.MarketValueAnalyser.java

License:Open Source License

public static void main(String[] args) throws ParseException {

    HibernateSupport.beginTransaction();
    Criteria cr = HibernateSupport.getCurrentSession().createCriteria(News.class);
    cr.createAlias("news_details", "details");
    cr.add(Restrictions.ge("details.total_objectivity", 0.5));
    cr.add(Restrictions.le("details.total_objectivity", 1.0));
    cr.setProjection(Projections.rowCount());
    long size = (long) cr.uniqueResult();
    HibernateSupport.commitTransaction();

    System.out.println("size = " + size);

    MarketValueAnalyser mva = new MarketValueAnalyser();
    //mva.createDistributionTable(40, 1, MarketValueAnalyser.Analyse.AFTER, false);
    mva.createDistributionTable(40, 3, MarketValueAnalyser.Analyse.AFTER, false);
    mva.createDistributionTable(40, 5, MarketValueAnalyser.Analyse.AFTER, false);
    mva.createDistributionTable(40, 7, MarketValueAnalyser.Analyse.AFTER, false);

    mva.createDistributionTable(40, 1, MarketValueAnalyser.Analyse.BEFORE, false);
    mva.createDistributionTable(40, 3, MarketValueAnalyser.Analyse.BEFORE, false);
    mva.createDistributionTable(40, 5, MarketValueAnalyser.Analyse.BEFORE, false);
    mva.createDistributionTable(40, 7, MarketValueAnalyser.Analyse.BEFORE, false);

}

From source file:ar.com.zauber.commons.repository.query.visitor.CriteriaFilterVisitor.java

License:Apache License

/** calculate a criterion */
private Criterion createCriterion(final BinaryPropertyFilter binaryPropertyFilter, final Object value) {
    final String fieldName = getFieldName(binaryPropertyFilter.getProperty());
    final Criterion ret;

    if (binaryPropertyFilter instanceof EqualsPropertyFilter) {
        ret = Restrictions.eq(fieldName, value);
    } else if (binaryPropertyFilter instanceof LessThanPropertyFilter) {
        ret = Restrictions.lt(fieldName, value);
    } else if (binaryPropertyFilter instanceof LessThanEqualsPropertyFilter) {
        ret = Restrictions.le(fieldName, value);
    } else if (binaryPropertyFilter instanceof GreaterThanPropertyFilter) {
        ret = Restrictions.gt(fieldName, value);
    } else if (binaryPropertyFilter instanceof GreaterThanEqualsPropertyFilter) {
        ret = Restrictions.ge(fieldName, value);
    } else if (binaryPropertyFilter instanceof LikePropertyFilter) {
        if (((LikePropertyFilter) binaryPropertyFilter).getCaseSensitive()) {
            ret = Restrictions.like(fieldName, value);
        } else {/*from w  w w  . j  a v  a 2s  . co m*/
            ret = Restrictions.ilike(fieldName, value);
        }
    } else {
        throw new IllegalStateException("Unable to process filter" + binaryPropertyFilter);
    }

    return ret;
}

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

License:Open Source License

/**
 * Adds a day range constraint to a bookings query so that bookings within
 * this day are returned.//from w w  w . ja v a2 s  .c  o m
 * 
 * @return restriction
 */
private Criterion addDayRange() {
    return Restrictions.disjunction().add(Restrictions.and( // Booking within day
            Restrictions.ge("startTime", this.dayBegin), Restrictions.le("endTime", this.dayEnd)))
            .add(Restrictions.and( // Booking starts before day and ends on this day
                    Restrictions.lt("startTime", this.dayBegin), Restrictions.gt("endTime", this.dayBegin)))
            .add(Restrictions.and( // Booking starts on day and ends after day
                    Restrictions.lt("startTime", this.dayEnd), Restrictions.gt("endTime", this.dayEnd)))
            .add(Restrictions.and(Restrictions.le("startTime", this.dayBegin),
                    Restrictions.gt("endTime", this.dayEnd)));
}

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

License:Open Source License

@Override
public CreateBookingResponse createBooking(CreateBooking createBooking) {
    /* --------------------------------------------------------------------
     * -- Read request parameters.                                       --
     * -------------------------------------------------------------------- */
    CreateBookingType request = createBooking.getCreateBooking();
    String debug = "Received " + this.getClass().getSimpleName() + "#createBooking with params: ";

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

    BookingType booking = request.getBooking();
    int pid = booking.getPermissionID().getPermissionID();
    debug += ", permission=" + pid;

    Calendar start = booking.getStartTime();
    Calendar end = booking.getEndTime();
    this.dstHack(start);
    this.dstHack(end);

    debug += ", start=" + start.getTime() + ", end=" + end.getTime();

    debug += ", send notification=" + request.getSendNotification() + ", notification time zone="
            + request.getNotificationTimezone() + '.';
    this.logger.debug(debug);

    /* --------------------------------------------------------------------
     * -- Generate default response parameters.                          --
     * -------------------------------------------------------------------- */
    CreateBookingResponse response = new CreateBookingResponse();
    BookingResponseType status = new BookingResponseType();
    status.setSuccess(false);/*from  w  w w .ja  v  a 2 s  .c  o  m*/
    response.setCreateBookingResponse(status);

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

        /* ----------------------------------------------------------------
         * -- Load the permission.                                       --
         * ---------------------------------------------------------------- */
        ResourcePermission perm = new ResourcePermissionDao(ses).get(Long.valueOf(pid));
        if (perm == null) {
            this.logger.info("Unable to create a booking because the permission has not been found. Supplied "
                    + "permission ID=" + pid + '.');
            status.setFailureReason("Permission not found.");
            return response;
        }

        if (!this.checkPermission(user, perm)) {
            this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                    + user.getName() + " does not have permission " + pid + '.');
            status.setFailureReason("Does not have permission.");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Check permission constraints.                              --
         * ---------------------------------------------------------------- */
        Date startDate = start.getTime();
        Date endDate = end.getTime();

        if (!perm.getUserClass().isBookable()) {
            this.logger.info("Unable to create a booking because the permission " + pid + " is not bookable.");
            status.setFailureReason("Permission not bookable.");
            return response;
        }

        if (startDate.before(perm.getStartTime()) || endDate.after(perm.getExpiryTime())) {
            this.logger
                    .info("Unable to create a booking because the booking time is outside the permission time. "
                            + "Permission start: " + perm.getStartTime() + ", expiry: " + perm.getExpiryTime()
                            + ", booking start: " + startDate + ", booking end: " + endDate + '.');
            status.setFailureReason("Booking time out of permission range.");
            return response;
        }

        /* Time horizon is a moving offset when bookings can be made. */
        Calendar horizon = Calendar.getInstance();
        horizon.add(Calendar.SECOND, perm.getUserClass().getTimeHorizon());
        if (horizon.after(start)) {
            this.logger.info("Unable to create a booking because the booking start time (" + startDate
                    + ") is before the time horizon (" + horizon.getTime() + ").");
            status.setFailureReason("Before time horizon.");
            return response;
        }

        /* Maximum concurrent bookings. */
        int numBookings = (Integer) ses.createCriteria(Bookings.class)
                .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                .add(Restrictions.eq("resourcePermission", perm)).setProjection(Projections.rowCount())
                .uniqueResult();
        if (numBookings >= perm.getMaximumBookings()) {
            this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                    + user.getName() + " already has the maxiumum numnber of bookings (" + numBookings + ").");
            status.setFailureReason("User has maximum number of bookings.");
            return response;
        }

        /* User bookings at the same time. */
        numBookings = (Integer) ses.createCriteria(Bookings.class).setProjection(Projections.rowCount())
                .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                .add(Restrictions.disjunction()
                        .add(Restrictions.and(Restrictions.gt("startTime", startDate),
                                Restrictions.lt("startTime", endDate)))
                        .add(Restrictions.and(Restrictions.gt("endTime", startDate),
                                Restrictions.le("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.le("startTime", startDate),
                                Restrictions.gt("endTime", endDate))))
                .uniqueResult();
        if (numBookings > 0) {
            this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                    + user.getName() + " has concurrent bookings.");
            status.setFailureReason("User has concurrent bookings.");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Create booking.                                            --
         * ---------------------------------------------------------------- */
        BookingCreation bc = this.engine.createBooking(user, perm, new TimePeriod(start, end), ses);
        if (bc.wasCreated()) {
            status.setSuccess(true);
            BookingIDType bid = new BookingIDType();
            bid.setBookingID(bc.getBooking().getId().intValue());
            status.setBookingID(bid);

            new BookingNotification(bc.getBooking()).notifyCreation();
        } else {
            status.setSuccess(false);
            status.setFailureReason("Resource not free.");

            BookingListType bestFits = new BookingListType();
            status.setBestFits(bestFits);
            for (TimePeriod tp : bc.getBestFits()) {
                numBookings = (Integer) ses.createCriteria(Bookings.class).setProjection(Projections.rowCount())
                        .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                        .add(Restrictions.disjunction()
                                .add(Restrictions.and(Restrictions.gt("startTime", tp.getStartTime().getTime()),
                                        Restrictions.lt("startTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.gt("endTime", tp.getStartTime().getTime()),
                                        Restrictions.le("endTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.le("startTime", tp.getStartTime().getTime()),
                                        Restrictions.gt("endTime", tp.getEndTime().getTime()))))
                        .uniqueResult();
                if (numBookings > 0) {
                    this.logger.debug("Excluding best fit option for user " + user.qName() + " because it is "
                            + "concurrent with an existing.");
                    continue;
                }
                BookingType fit = new BookingType();
                fit.setPermissionID(booking.getPermissionID());
                fit.setStartTime(tp.getStartTime());
                fit.setEndTime(tp.getEndTime());
                bestFits.addBookings(fit);
            }
        }
    } finally {
        ses.close();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.pojo.impl.BookingsServiceImpl.java

License:Open Source License

@Override
public BookingOperation createBooking(Calendar start, Calendar end, User user, ResourcePermission perm,
        Session db) {/*from  w w  w . j av a  2s . c  o  m*/
    BookingOperation response = new BookingOperation();
    response.setSuccess(false);

    /* ----------------------------------------------------------------
     * -- Check permission constraints.                              --
     * ---------------------------------------------------------------- */
    Date startDate = start.getTime();
    Date endDate = end.getTime();

    if (!perm.getUserClass().isBookable()) {
        this.logger.info(
                "Unable to create a booking because the permission " + perm.getId() + " is not bookable.");
        response.setFailureReason("Permission not bookable.");
        return response;
    }

    if (startDate.before(perm.getStartTime()) || endDate.after(perm.getExpiryTime())) {
        this.logger.info("Unable to create a booking because the booking time is outside the permission time. "
                + "Permission start: " + perm.getStartTime() + ", expiry: " + perm.getExpiryTime()
                + ", booking start: " + startDate + ", booking end: " + endDate + '.');
        response.setFailureReason("Booking time out of permission range.");
        return response;
    }

    /* Time horizon is a moving offset when bookings can be made. */
    Calendar horizon = Calendar.getInstance();
    horizon.add(Calendar.SECOND, perm.getUserClass().getTimeHorizon());
    if (horizon.after(start)) {
        this.logger.info("Unable to create a booking because the booking start time (" + startDate
                + ") is before the time horizon (" + horizon.getTime() + ").");
        response.setFailureReason("Before time horizon.");
        return response;
    }

    /* Maximum concurrent bookings. */
    int numBookings = (Integer) db.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE))
            .add(Restrictions.eq("user", user)).add(Restrictions.eq("resourcePermission", perm))
            .setProjection(Projections.rowCount()).uniqueResult();
    if (numBookings >= perm.getMaximumBookings()) {
        this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                + user.getName() + " already has the maxiumum numnber of bookings (" + numBookings + ").");
        response.setFailureReason("User has maximum number of bookings.");
        return response;
    }

    /* User bookings at the same time. */
    numBookings = (Integer) db.createCriteria(Bookings.class).setProjection(Projections.rowCount())
            .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
            .add(Restrictions.disjunction()
                    .add(Restrictions.and(Restrictions.gt("startTime", startDate),
                            Restrictions.lt("startTime", endDate)))
                    .add(Restrictions.and(Restrictions.gt("endTime", startDate),
                            Restrictions.le("endTime", endDate)))
                    .add(Restrictions.and(Restrictions.le("startTime", startDate),
                            Restrictions.gt("endTime", endDate))))
            .uniqueResult();

    if (numBookings > 0) {
        this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                + user.getName() + " has concurrent bookings.");
        response.setFailureReason("User has concurrent bookings.");
        return response;
    }

    /* ----------------------------------------------------------------
     * -- Create booking.                                            --
     * ---------------------------------------------------------------- */
    if (ResourcePermission.CONSUMER_PERMISSION.equals(perm.getType())) {
        CreateBookingRequest request = new CreateBookingRequest();
        if (request.createBooking(user, perm.getRemotePermission(), start, end, db)) {
            response.setSuccess(request.wasSuccessful());
            response.setFailureReason(request.getReason());
            if (request.wasSuccessful()) {
                /* Provider created booking so we now need to create it 
                 * locally. */
                this.logger.debug("Successfullly created booking at provider with identifier "
                        + request.getBookingID() + '.');
                Bookings bk = new Bookings();
                bk.setActive(true);
                bk.setStartTime(startDate);
                bk.setEndTime(endDate);
                bk.setDuration((int) (end.getTimeInMillis() - start.getTimeInMillis()) / 1000);
                bk.setResourcePermission(perm);
                bk.setResourceType(ResourcePermission.CONSUMER_PERMISSION);
                bk.setProviderId(request.getBookingID());
                bk.setUser(user);
                bk.setUserNamespace(user.getNamespace());
                bk.setUserName(user.getName());
                response.setBooking(new BookingsDao(db).persist(bk));

                /* Notification emails are only sent to home users. */
                new BookingNotification(bk).notifyCreation();
            } else {
                this.logger.info("Provider failed to create booking with reason " + request.getReason());

                /* Provider returned that it couldn't create booking. */
                for (BookingTime bt : request.getBestFits()) {
                    response.addBestFit(bt.getStart(), bt.getEnd());
                }
            }
        } else {
            /* Provider call failed. */
            this.logger
                    .info("Provider call to create booking failed with reason " + request.getFailureReason());
            response.setSuccess(false);
            response.setFailureReason("Provider request failed (" + request.getFailureReason() + ")");
        }
    } else {
        BookingCreation bc = this.engine.createBooking(user, perm, new TimePeriod(start, end), db);
        if (bc.wasCreated()) {
            response.setSuccess(true);
            response.setBooking(bc.getBooking());

            /* Notification emails are only sent to home users. */
            if (perm.getRemotePermission() == null)
                new BookingNotification(bc.getBooking()).notifyCreation();
        } else {
            response.setSuccess(false);
            response.setFailureReason("Resource not free.");

            for (TimePeriod tp : bc.getBestFits()) {
                numBookings = (Integer) db.createCriteria(Bookings.class).setProjection(Projections.rowCount())
                        .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                        .add(Restrictions.disjunction()
                                .add(Restrictions.and(Restrictions.gt("startTime", tp.getStartTime().getTime()),
                                        Restrictions.lt("startTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.gt("endTime", tp.getStartTime().getTime()),
                                        Restrictions.le("endTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.le("startTime", tp.getStartTime().getTime()),
                                        Restrictions.gt("endTime", tp.getEndTime().getTime()))))
                        .uniqueResult();
                if (numBookings > 0) {
                    this.logger.debug("Excluding best fit option for user " + user.qName() + " because it is "
                            + "concurrent with an existing.");
                    continue;
                }

                response.addBestFit(tp.getStartTime(), tp.getEndTime());
            }
        }
    }

    return response;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  www . j  a v a  2 s .  co  m*/
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//w ww .j  a  va  2 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.org.theark.core.dao.StudyDao.java

License:Open Source License

private List<Long> applyConsentStatusFilters(DataExtractionVO allTheData, Search search,
        List<Long> idsToInclude) {

    //for(Long l : idsToInclude) {
    //   log.info("including: " + l);
    //}//from   www.j a v  a2s. c  om
    boolean hasConsentFilters = false;
    if (search.getQueryFilters().isEmpty()) {
        return idsToInclude;
    } else {
        for (QueryFilter filter : search.getQueryFilters()) {
            if (filter.getConsentStatusField() != null) {
                hasConsentFilters = true;
            }
        }
    }
    Criteria filter = getSession().createCriteria(Consent.class, "c");
    filter.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
    filter.createAlias("c.linkSubjectStudy", "lss");
    if (!idsToInclude.isEmpty()) {
        filter.add(Restrictions.in("lss.id", idsToInclude));
    }
    filter.createAlias("c.studyComponentStatus", "cscs");
    filter.createAlias("c.studyComp", "csc");

    if (!hasConsentFilters) {

        for (QueryFilter qf : search.getQueryFilters()) {
            if (qf.getConsentStatusField() != null) {
                switch (qf.getOperator()) {
                case EQUAL:
                    filter.add(Restrictions.eq(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case BETWEEN:
                    filter.add(Restrictions.between(getConsentFilterFieldName(qf), qf.getValue(),
                            qf.getSecondValue()));
                    break;
                case GREATER_THAN:
                    filter.add(Restrictions.gt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case GREATER_THAN_OR_EQUAL:
                    filter.add(Restrictions.ge(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case IS_EMPTY:
                    filter.add(Restrictions.isEmpty(getConsentFilterFieldName(qf)));
                    break;
                case IS_NOT_EMPTY:
                    filter.add(Restrictions.isNotEmpty(getConsentFilterFieldName(qf)));
                    break;
                case LESS_THAN:
                    filter.add(Restrictions.lt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LESS_THAN_OR_EQUAL:
                    filter.add(Restrictions.le(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LIKE:
                    filter.add(Restrictions.like(getConsentFilterFieldName(qf), qf.getValue(),
                            MatchMode.ANYWHERE));
                    break;
                case NOT_EQUAL:
                    filter.add(Restrictions.ne(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                default:
                    break;
                }
            }
        }
    }
    filter.setProjection(
            Projections.distinct(Projections.projectionList().add(Projections.property("lss.id"))));

    List<Long> consentStatusIDs = filter.list();

    Collection<Consent> csData = Collections.EMPTY_LIST;

    if (!consentStatusIDs.isEmpty()) {
        Criteria consentData = getSession().createCriteria(Consent.class, "c");
        consentData.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
        consentData.createAlias("c.linkSubjectStudy", "lss");
        consentData.add(Restrictions.in("lss.id", consentStatusIDs));
        csData = consentData.list();
    }

    HashMap<String, ExtractionVO> hashOfConsentStatusData = allTheData.getConsentStatusData();

    ExtractionVO valuesForThisLss = new ExtractionVO();
    HashMap<String, String> map = null;
    LinkSubjectStudy previousLss = null;
    int count = 0;
    //will try to order our results and can therefore just compare to last LSS and either add to or create new Extraction VO
    for (Consent data : csData) {
        if (previousLss == null) {
            map = new HashMap<String, String>();
            previousLss = data.getLinkSubjectStudy();
            count = 0;
        } else if (data.getLinkSubjectStudy().getId().equals(previousLss.getId())) {
            //then just put the data in
            count++;
        } else { //if its a new LSS finalize previous map, etc
            valuesForThisLss.setKeyValues(map);
            valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
            hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
            previousLss = data.getLinkSubjectStudy();
            map = new HashMap<String, String>();//reset
            valuesForThisLss = new ExtractionVO();
            count = 0;
        }
        if (data.getStudyComp().getName() != null) {
            map.put(count + "_Study Component Name", data.getStudyComp().getName());
        }
        if (data.getStudyComponentStatus() != null) {
            map.put(count + "_Study Component Status", data.getStudyComponentStatus().getName());
        }
        if (data.getConsentDate() != null) {
            map.put(count + "_Consent Date", data.getConsentDate().toString());
        }
        if (data.getConsentedBy() != null) {
            map.put(count + "_Consented By", data.getConsentedBy());
        }
    }

    //finalize the last entered key value sets/extraction VOs
    if (map != null && previousLss != null) {
        valuesForThisLss.setKeyValues(map);
        valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
        hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
    }

    //can probably now go ahead and add these to the dataVO...even though inevitable further filters may further axe this list or parts of it.
    allTheData.setConsentStatusData(hashOfConsentStatusData);
    if (hasConsentFilters) {
        return consentStatusIDs;
    } else {
        return idsToInclude;
    }
}

From source file:au.org.theark.report.model.dao.ReportDao.java

License:Open Source License

public List<ResearcherCostDataRow> getResearcherBillableItemTypeCostData(
        final ResearcherCostResportVO researcherCostResportVO) {
    List<ResearcherCostDataRow> results = new ArrayList<ResearcherCostDataRow>();
    Criteria criteria = getSession().createCriteria(BillableItem.class, "bi");
    criteria.createAlias("workRequest", "wr", JoinType.LEFT_OUTER_JOIN);
    criteria.createAlias("billableItemType", "bit", JoinType.LEFT_OUTER_JOIN);
    criteria.createAlias("bit.billableItemTypeStatus", "bitst", JoinType.LEFT_OUTER_JOIN);
    criteria.createAlias("wr.researcher", "re", JoinType.LEFT_OUTER_JOIN);

    criteria.add(Restrictions.eq("re.id", researcherCostResportVO.getResearcherId()));
    criteria.add(Restrictions.eq("bi.studyId", researcherCostResportVO.getStudyId()));
    criteria.add(Restrictions.eq("bi.invoice", researcherCostResportVO.getInvoice()));
    criteria.add(Restrictions.le("bi.commenceDate", researcherCostResportVO.getToDate()));
    criteria.add(Restrictions.ge("bi.commenceDate", researcherCostResportVO.getFromDate()));
    criteria.add(Restrictions.eq("bitst.name", "ACTIVE"));

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("bit.id"));
    projectionList.add(Projections.property("bit.itemName"), "costType");
    projectionList.add(Projections.sum("bi.totalCost"), "totalCost");
    projectionList.add(Projections.sum("bi.totalGST"), "totalGST");

    criteria.setProjection(projectionList); // only return fields required for report
    criteria.setResultTransformer(Transformers.aliasToBean(ResearcherCostDataRow.class));

    criteria.addOrder(Order.asc("bit.itemName"));
    results = criteria.list();/*  ww  w  .jav  a 2  s .  c om*/
    return results;
}