Example usage for org.hibernate.criterion Restrictions lt

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

Introduction

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

Prototype

public static SimpleExpression lt(String propertyName, Object value) 

Source Link

Document

Apply a "less than" constraint to the named property

Usage

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

License:Open Source License

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

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

License:Open Source License

/**
 * Returns true if the rig is currently in a scheduled off-line period.
 * /*from  w w  w .  j a  va 2  s.  c o  m*/
 * @param rig rig to check
 * @return true if off-line
 */
public boolean isOffline(Rig rig) {
    Date now = new Date();
    return (Integer) this.session.createCriteria(this.clazz).add(Restrictions.eq("rig", rig))
            .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.lt("startTime", now))
            .add(Restrictions.gt("endTime", now)).setProjection(Projections.rowCount()).uniqueResult() > 0;
}

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

License:Open Source License

/**
 * Returns the list of keys for a user class. If the parameter 'historical'
 * is part of the request parameters and has a value of 'true', non-usable
 * keys are returned otherwise usable keys are returned. Usable keys are 
 * those that are 'active', have remaining uses and have not elapsed
 * their expiry time. /* www . jav  a 2s . c om*/
 * 
 * @param request request
 * @return list of permission keys
 * @throws JSONException 
 */
@SuppressWarnings("unchecked")
public JSONArray getList(HttpServletRequest request) throws JSONException {
    JSONArray arr = new JSONArray();

    String className = request.getParameter("name");
    if (className == null) {
        this.logger.warn("Unable to provide access key list because the user class name was not provided.");
        return arr;
    }

    Criteria qu = this.db.createCriteria(UserClassKey.class).add(Restrictions.eq("userTargeted", Boolean.FALSE))
            .addOrder(Order.asc("id"));

    if ("true".equals(request.getAttribute("historical"))) {
        qu.add(Restrictions.disjunction().add(Restrictions.eq("active", Boolean.FALSE))
                .add(Restrictions.eq("remaining", 0)))
                .add(Restrictions.or(Restrictions.isNull("expiry"), Restrictions.lt("expiry", new Date())));
    } else {
        qu.add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.gt("remaining", 0))
                .add(Restrictions.or(Restrictions.isNull("expiry"), Restrictions.gt("expiry", new Date())));
    }

    qu = qu.createCriteria("userClass").add(Restrictions.eq("name", className));

    for (UserClassKey key : (List<UserClassKey>) qu.list()) {
        JSONObject keyObj = new JSONObject();
        keyObj.put("key", key.getRedeemKey());
        keyObj.put("active", key.isActive());
        keyObj.put("remaining", key.getRemaining());
        arr.put(keyObj);
    }

    return arr;
}

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

License:Open Source License

/**
 * Gets the next user bookingService within a specified limit, from now to now
 * plus limit. If no bookingService exists within the limit, null is returned.
 * // ww w  .  j ava 2s.  co  m
 * @param user user who has bookingService
 * @param sec limit 
 * @param ses database session
 * @return bookingService or null if none exists 
 */
private Bookings getNextBooking(User user, int sec, org.hibernate.Session ses) {
    Calendar start = Calendar.getInstance();
    start.add(Calendar.SECOND, sec);

    return (Bookings) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE))
            .add(Restrictions.eq("user", user)).add(Restrictions.lt("startTime", start.getTime()))
            .setMaxResults(1).addOrder(Order.asc("startTime")).uniqueResult();
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w w w .j  a va  2  s . 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.rigmanagement.intf.RigManagement.java

License:Open Source License

@Override
public PutRigOfflineResponse putRigOffline(PutRigOffline putRigOffline) {
    PutRigOfflineType param = putRigOffline.getPutRigOffline();
    this.logger.debug("Received RigManagement#putRigOffline with params: requestor ID=" + param.getRequestorID()
            + "requestor namespace=" + param.getRequestorNameSpace() + ", requestor name"
            + param.getRequestorName() + ", rig name=" + param.getRig().getName() + ", offline start="
            + param.getStart().getTime() + ", offline end=" + param.getEnd().getTime() + ", reason="
            + param.getReason() + '.');

    PutRigOfflineResponse response = new PutRigOfflineResponse();
    OperationResponseType result = new OperationResponseType();
    response.setPutRigOfflineResponse(result);

    RigDao dao = new RigDao();
    try {//from w w  w . j av  a 2  s  .co  m
        if (!this.isAuthorised(param, dao.getSession())) {
            this.logger.warn("Unable to put a rig offline because the user is not authorised to perform this "
                    + "operation (not a ADMIN).");
            result.setFailureCode(1);
            result.setFailureReason("Not authorised.");
            return response;
        }

        Rig rig = dao.findByName(param.getRig().getName());
        if (rig == null) {
            this.logger.warn("Unable to put a rig offline because the rig with name " + param.getRig().getName()
                    + " was not found.");
            result.setFailureCode(2);
            result.setFailureReason("Rig not found.");
            return response;
        }

        if (param.getStart().after(param.getEnd())) {
            this.logger
                    .warn("Unable to put a rig offline because the offline start " + param.getStart().getTime()
                            + " is after the offline end " + param.getEnd().getTime() + ".");
            result.setFailureCode(3);
            result.setFailureReason("Start after end.");
            return response;
        }

        Date startDate = param.getStart().getTime();
        Date endDate = param.getEnd().getTime();

        if ((Integer) dao.getSession().createCriteria(RigOfflineSchedule.class)
                .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("rig", rig))
                .add(Restrictions.disjunction()
                        .add(Restrictions.and(Restrictions.gt("startTime", startDate),
                                Restrictions.lt("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.lt("startTime", startDate),
                                Restrictions.gt("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.lt("startTime", startDate),
                                Restrictions.gt("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.lt("startTime", startDate),
                                Restrictions.gt("endTime", endDate))))
                .setProjection(Projections.rowCount()).uniqueResult() > 0) {
            this.logger.warn("Unable to put a rig offline because there is a concurrent rig offline period.");
            result.setFailureCode(4);
            result.setFailureReason("Concurrent offline period.");
            return response;
        }

        result.setSuccessful(true);

        RigOfflineSchedule offline = new RigOfflineSchedule();
        offline.setActive(true);
        offline.setRig(rig);
        offline.setStartTime(startDate);
        offline.setEndTime(endDate);
        offline.setReason(param.getReason());
        new RigOfflineScheduleDao(dao.getSession()).persist(offline);

        /* Notify the booking engine. */
        BookingEngineService service = RigManagementActivator.getBookingService();
        if (service != null)
            service.putRigOffline(offline, dao.getSession());

        /* If the period is currently active, clear the rig maintenance state. */
        Date now = new Date();
        if (rig.isActive() && rig.isOnline() && offline.getStartTime().before(now)
                && offline.getEndTime().after(now)) {
            this.logger.info("Setting maintenance state on rig " + rig.getName() + '.');
            if (this.notTest)
                new RigMaintenance().putMaintenance(rig, true, dao.getSession());

            rig.setOnline(false);
            rig.setOfflineReason("In maintenance.");
            new RigLogDao(dao.getSession()).addOfflineLog(rig, "In maintenance.");
            dao.flush();
        }
    } finally {
        dao.closeSession();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.rigprovider.impl.StatusTimeoutChecker.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void run() {
    org.hibernate.Session db = null;/*from w  ww  .j  a  v  a2 s . c  om*/
    try {
        db = DataAccessActivator.getNewSession();
        if (db == null) {
            this.logger.error("Unable to obtain a database session for the rig status time out checker. "
                    + "Ensure the database is running and configured database details are correct.");
            return;
        }

        RigLogDao rigLogDao = new RigLogDao(db);

        /* Get all the rigs that have timed out. */
        List<Rig> timedOut = db.createCriteria(Rig.class).add(Restrictions.eq("managed", true)) // Unmanaged rigs need not provide a status update
                .add(Restrictions.eq("active", true)).add(Restrictions.lt("lastUpdateTimestamp",
                        new Date(System.currentTimeMillis() - this.timeout * 1000)))
                .list();

        for (Rig rig : timedOut) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(rig.getLastUpdateTimestamp());

            this.logger.warn("Rig " + rig.getName() + " has timed out with last status update received at "
                    + cal.get(Calendar.DATE) + '/' + (cal.get(Calendar.MONTH) + 1) + '/'
                    + cal.get(Calendar.YEAR) + " - " + cal.get(Calendar.HOUR_OF_DAY) + ':'
                    + cal.get(Calendar.MINUTE) + ':' + cal.get(Calendar.SECOND) + ". Making rig inactive.");

            if (rig.getSession() != null) {
                this.logger.warn("Timed out rig " + rig.getName() + " is in session so the session is being "
                        + "terminated.");
                Session ses = rig.getSession();

                ses.setActive(false);
                ses.setRemovalReason("Rig timed out");
                ses.setRemovalTime(new Date());

                rig.setInSession(false);
                rig.setSession(null);
            }

            rig.setActive(false);
            rig.setOnline(false);
            rig.setOfflineReason("Timed out.");

            rigLogDao.addUnRegisteredLog(rig, "Timed out.");

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

            /* Fire a notification the rig has gone offline. */
            for (RigEventListener list : RigProviderActivator.getRigEventListeners()) {
                list.eventOccurred(RigStateChangeEvent.OFFLINE, rig, db);
            }
        }
    } catch (HibernateException hex) {
        this.logger.error("Failed to query database to check rig status. Exception: " + hex.getClass().getName()
                + ", Message:" + hex.getMessage());

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

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w  w  w  . ja  v  a2  s  .  com*/
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  a2s . co  m
    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.phenotypic.model.dao.PhenotypicDao.java

License:Open Source License

public List<PhenoDataSetCollection> getSubjectMatchingPhenoCollections(LinkSubjectStudy subject,
        PhenoDataSetGroup phenoDataSetGroup, Date recordDate) {
    log.info("subject " + subject.getSubjectUID());
    log.info("phenoDataSetGroup " + phenoDataSetGroup.getName());
    log.info("date: " + recordDate);
    Criteria criteria = getSession().createCriteria(PhenoDataSetCollection.class);
    criteria.add(Restrictions.eq("linkSubjectStudy", subject));
    criteria.add(Restrictions.eq("questionnaire", phenoDataSetGroup));
    Calendar cal = Calendar.getInstance();
    cal.setTime(recordDate);// ww  w . ja va 2  s.  co m

    //Removing the "Time" section of the Dates as that's not important in this context
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    Date low = cal.getTime();
    cal.add(Calendar.DATE, 1);
    Date high = cal.getTime();
    criteria.add(Restrictions.lt("recordDate", high));
    criteria.add(Restrictions.ge("recordDate", low));

    return criteria.list();
}