Example usage for org.hibernate.criterion Restrictions ge

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

Introduction

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

Prototype

public static SimpleExpression ge(String propertyName, Object value) 

Source Link

Document

Apply a "greater 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 ww w .ja  v  a 2 s  .  c  om*/
@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 List<Double> createMarginalDistribution(double lower, double upper, int days,
        MarketValueAnalyser.Analyse period, boolean good_rep, PrintWriter writer) {

    HibernateSupport.beginTransaction();
    Criteria c2 = HibernateSupport.getCurrentSession().createCriteria(News.class);
    c2.createAlias("news_details", "detail");
    c2.add(Restrictions.ge("detail.total_polarity", lower));
    c2.add(Restrictions.lt("detail.total_polarity", upper));

    if (good_rep) {
        c2.createAlias("companies", "company");
        c2.add(News.getNewsOfCompaniesWithGoodReputation());
    }//  ww w .  j  av a  2  s  .c  om

    List<News> news_list = c2.list();
    HibernateSupport.commitTransaction();

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

    PolynomialSplineFunction psf;
    Date publish_date;
    Calendar from = Calendar.getInstance();
    Calendar to = Calendar.getInstance();
    double[] share_price_dev;
    int counter = 0;
    News single_news;
    List<Company> companies;
    List<Double> price_devs_period = new ArrayList<Double>();
    Pair<Calendar, Calendar> from_to;

    while (news_list.size() > 0) {
        single_news = news_list.get(0);
        news_list.remove(0);

        companies = single_news.getCompaniesNew();

        publish_date = single_news.getDate();
        //from.setTime(publish_date);
        //to.setTime(publish_date);

        from_to = MyDateUtils.getFromToCalendars(period, publish_date, days);
        from = from_to.getValue0();
        to = from_to.getValue1();

        to.set(Calendar.DAY_OF_YEAR, to.get(Calendar.DAY_OF_YEAR) + days);
        for (Company company : single_news.getCompaniesNew()) {
            //System.out.println("publish_date = " + publish_date);
            //System.out.println("ISIN = " + company.getIsin());
            if ((psf = this.getMarketValueSplineFromTo(company, from, to)) != null) {
                share_price_dev = this.getSharePriceDevelopement(psf, from, to);
                //System.out.println(++counter);
                //System.out.println(share_price_dev[days - 1]);
                price_devs_period.add(share_price_dev[days - 1]); //day - 1
                writer.println(single_news.getNewsDetails().get(0).getTotalPolarity() + ", "
                        + share_price_dev[days - 1]);
            }
        }
    }

    /*Collections.sort(price_devs_period);
    List<Double> data_set = this.createDataSet(price_devs_period, -10.0f, 10.0f, 42);
    System.out.println(data_set);
    return data_set;*/
    return null;

}

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 www .jav a 2 s .  c  o 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 ww . j a  va  2s .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.reports.intf.Reports.java

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            respType.addAccessReportData(report);
        }

    } finally {
        db.close();
    }

    return response;
}

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

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                respType.setPagination(page);

            }

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

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

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

                    reportType.setRigName(query0.getQueryLike());

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

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

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

                    respType.addSessionReport(reportType);
                }

            }

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

            resp.setQuerySessionReportResponse(respType);
        }

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

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

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

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

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

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

            Long idCount = new Long(-1);

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

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

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

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

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

            }

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

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

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

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

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

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

                    reportType.setRigType(rType.getName());

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

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

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

                    respType.addSessionReport(reportType);
                }
            }

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

            resp.setQuerySessionReportResponse(respType);

        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            }

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

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

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

                    reportType.setUserClass(uClass.getName());

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

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

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

                    respType.addSessionReport(reportType);
                }
            }

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

            resp.setQuerySessionReportResponse(respType);

        }

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

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

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

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

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

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

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

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

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

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

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

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

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

                final User u = o.getUser();

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

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

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

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

            }

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

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

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

                    reportType.setUser(user1);

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

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

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

                    respType.addSessionReport(reportType);
                }
            }

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

            resp.setQuerySessionReportResponse(respType);

        }

    }

    finally {
        ses.close();
    }

    return resp;
}

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

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:au.edu.uts.eng.remotelabs.schedserver.session.impl.SessionExpiryChecker.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  www .  ja  va  2  s . c om
public void run() {
    org.hibernate.Session db = null;

    try {
        if ((db = DataAccessActivator.getNewSession()) == null) {
            this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the "
                    + "SchedulingServer-DataAccess bundle is installed and active.");
            return;
        }

        boolean kicked = false;

        Criteria query = db.createCriteria(Session.class);
        query.add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.isNotNull("assignmentTime"));

        Date now = new Date();

        List<Session> sessions = query.list();
        for (Session ses : sessions) {
            ResourcePermission perm = ses.getResourcePermission();
            int remaining = ses.getDuration() + // The session time
                    (perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
                    Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time

            int extension = perm.getSessionDuration() - ses.getDuration() >= TIME_EXT ? TIME_EXT
                    : perm.getExtensionDuration();

            /******************************************************************
             * For sessions that have been marked for termination, terminate  * 
             * those that have no more remaining time.                        *
             ******************************************************************/
            if (ses.isInGrace()) {
                if (remaining <= 0) {
                    ses.setActive(false);
                    ses.setRemovalTime(now);
                    db.beginTransaction();
                    db.flush();
                    db.getTransaction().commit();

                    this.logger.info("Terminating session for " + ses.getUserNamespace() + ':'
                            + ses.getUserName() + " on " + ses.getAssignedRigName()
                            + " because it is expired and the grace period has elapsed.");
                    if (this.notTest)
                        new RigReleaser().release(ses, db);
                }
            }
            /******************************************************************
             * For sessions with remaining time less than the grace duration: *
             *    1) If the session has no remaining extensions, mark it for  *
             *       termination.                                             *
             *    2) Else, if the session rig is queued, mark it for          *
             *       termination.                                             *
             *    3) Else, extend the sessions time.                          *
             ******************************************************************/
            else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration()) {
                BookingEngineService service;

                /* Need to make a decision whether to extend time or set for termination. */
                if (ses.getExtensions() <= 0 && ses.getDuration() >= perm.getSessionDuration()) {
                    this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on "
                            + "rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking "
                            + "session for expiry and giving a grace period.");
                    ses.setInGrace(true);
                    ses.setRemovalReason("No more session time extensions.");
                    db.beginTransaction();
                    db.flush();
                    db.getTransaction().commit();

                    /* Notification warning. */
                    if (this.notTest)
                        new RigNotifier().notify("Your session will expire in " + remaining + " seconds. "
                                + "Please finish and exit.", ses, db);
                } else if ((Integer) db.createCriteria(Bookings.class)
                        .add(Restrictions.eq("active", Boolean.TRUE))
                        .add(Restrictions.eq("user", ses.getUser())).add(Restrictions.ge("startTime", now))
                        .add(Restrictions.lt("startTime",
                                new Date(System.currentTimeMillis() + extension * 1000)))
                        .setProjection(Projections.rowCount()).uniqueResult() > 0) {
                    this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on "
                            + "rig" + ses.getAssignedRigName() + " is being terminated because the user has a "
                            + "starting booking. Marking session for expiry and giving a grace period.");
                    ses.setInGrace(true);
                    ses.setRemovalReason("User has starting booking.");
                    db.beginTransaction();
                    db.flush();
                    db.getTransaction().commit();

                    /* Notification warning. */
                    if (this.notTest)
                        new RigNotifier().notify("Your session will expire in " + remaining + " seconds. "
                                + "Please finish and exit. Please note, you have a reservation that starts after this"
                                + " session so do not leave.", ses, db);
                } else if (QueueInfo.isQueued(ses.getRig(), db)
                        || ((service = SessionActivator.getBookingService()) != null
                                && !service.extendQueuedSession(ses.getRig(), ses, extension, db))) {
                    this.logger.info(
                            "Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig "
                                    + ses.getAssignedRigName() + " is expired and the rig is queued or booked. "
                                    + "Marking session for expiry and giving a grace period.");
                    ses.setInGrace(true);
                    ses.setRemovalReason("Rig is queued or booked.");
                    db.beginTransaction();
                    db.flush();
                    db.getTransaction().commit();

                    /* Notification warning. */
                    if (this.notTest)
                        new RigNotifier().notify("Your session will end in " + remaining + " seconds. "
                                + "After this you be removed, so please logoff.", ses, db);
                } else {
                    this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on "
                            + "rig " + ses.getAssignedRigName() + " is expired and is having its session time "
                            + "extended by " + extension + " seconds.");
                    if (perm.getSessionDuration() - ses.getDuration() >= TIME_EXT) {
                        ses.setDuration(ses.getDuration() + extension);
                    } else {
                        ses.setExtensions((short) (ses.getExtensions() - 1));
                    }
                    db.beginTransaction();
                    db.flush();
                    db.getTransaction().commit();
                }
            }
            /******************************************************************
             * For sessions created with a user class that can be kicked off, * 
             * if the rig is queued, the user is kicked off immediately.      *
             ******************************************************************/
            /* DODGY The 'kicked' flag is to only allow a single kick per 
             * pass. This is allow time for the rig to be released and take the
             * queued session. This is a hack at best, but should be addressed 
             * by a released - cleaning up meta state. */
            else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable()) {
                kicked = true;

                /* No grace is being given. */
                this.logger
                        .info("A kickable user is using a rig that is queued for, so they are being removed.");
                ses.setActive(false);
                ses.setRemovalTime(now);
                ses.setRemovalReason("Resource was queued and user was kickable.");
                db.beginTransaction();
                db.flush();
                db.getTransaction().commit();

                if (this.notTest)
                    new RigReleaser().release(ses, db);
            }
            /******************************************************************
             * Finally, for sessions with time still remaining, check         *
             * session activity timeout - if it is not ignored and is ready   *
             * for use.                                                       * 
             ******************************************************************/
            else if (ses.isReady() && ses.getResourcePermission().isActivityDetected()
                    && (System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm
                            .getSessionActivityTimeout()) {
                /* Check activity. */
                if (this.notTest)
                    new SessionIdleKicker().kickIfIdle(ses, db);
            }
        }
    } catch (HibernateException hex) {
        this.logger.error("Failed to query database to expired sessions (Exception: " + hex.getClass().getName()
                + ", Message:" + hex.getMessage() + ").");

        if (db != null && db.getTransaction() != null) {
            try {
                db.getTransaction().rollback();
            } catch (HibernateException ex) {
                this.logger.error("Exception rolling back session expiry transaction (Exception: "
                        + ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
            }
        }
    } catch (Throwable thr) {
        this.logger.error("Caught unchecked exception in session expirty checker. Exception: " + thr.getClass()
                + ", message: " + thr.getMessage() + '.');
    } finally {
        try {
            if (db != null)
                db.close();
        } catch (HibernateException ex) {
            this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName()
                    + "," + " Message: " + ex.getMessage() + ").");
        }
    }
}

From source file:au.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   w w w.  j a v a 2s .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;
    }
}