Example usage for org.hibernate Criteria list

List of usage examples for org.hibernate Criteria list

Introduction

In this page you can find the example usage for org.hibernate Criteria list.

Prototype

public List list() throws HibernateException;

Source Link

Document

Get the results.

Usage

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w w  w .j a  v  a2  s .c o  m*/
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.gov.naa.digipres.spyd.dao.hibernate.HibernateItemRecordDAO.java

License:Open Source License

@Override
public ItemRecord getItemRecord(String id) {
    Session session = HibernateUtil.getSession();
    Criteria crit = session.createCriteria(ItemRecord.class);
    crit.add(Restrictions.eq("id", id));
    List results = crit.list();
    if ((results == null) || results.size() == 0) {
        return null;
    }/*  ww  w .  ja  v  a 2  s  . co  m*/
    ItemRecord item = (ItemRecord) results.get(0);
    session.flush();
    session.clear();

    return item;
}

From source file:au.gov.naa.digipres.spyd.dao.hibernate.HibernateItemRecordDAO.java

License:Open Source License

@Override
public List<ItemRecord> getAllItemRecords() {
    Session session = HibernateUtil.getSession();
    Criteria crit = session.createCriteria(ItemRecord.class);
    List<ItemRecord> itemRecords = crit.list();
    session.flush();/*from  w w w .  j  a va2s . co m*/
    session.clear();

    return itemRecords;
}

From source file:au.gov.naa.digipres.spyd.dao.hibernate.HibernateItemRecordDAO.java

License:Open Source License

@Override
public List<ItemRecord> getItemRecordsBySubDir(String subdir) {
    Session session = HibernateUtil.getSession();
    Criteria crit = session.createCriteria(ItemRecord.class);

    //TODO add a restriction to the criteria so it actually gets filtered. 
    List<ItemRecord> itemRecords = crit.list();
    session.flush();/* ww w.j  a va2  s.  c  om*/
    session.clear();

    return itemRecords;
}

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

License:Open Source License

public List<ArkRole> getArkRoleList() {
    Criteria criteria = getSession().createCriteria(ArkRole.class);
    return criteria.list();
}

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

License:Open Source License

public List<ArkModule> getArkModuleList() {
    Criteria criteria = getSession().createCriteria(ArkModule.class);
    return criteria.list();
}

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

License:Open Source License

public List<ArkFunction> getArkFunctionList() {
    Criteria criteria = getSession().createCriteria(ArkFunction.class);
    return criteria.list();
}

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

License:Open Source License

public List<ArkRolePolicyTemplate> getArkRolePolicyTemplateList() {
    Criteria criteria = getSession().createCriteria(ArkRolePolicyTemplate.class);
    return criteria.list();
}

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

License:Open Source License

public List<ArkRolePolicyTemplate> searchArkRolePolicyTemplate(ArkRolePolicyTemplate arkRolePolicyTemplate) {
    Criteria criteria = getSession().createCriteria(ArkRolePolicyTemplate.class);

    if (arkRolePolicyTemplate.getId() != null) {
        criteria.add(Restrictions.eq("id", arkRolePolicyTemplate.getId()));
    }//from  w  w w  .  j  a  v  a  2s  . c o m

    if (arkRolePolicyTemplate.getArkRole() != null) {
        criteria.add(Restrictions.eq("arkRole", arkRolePolicyTemplate.getArkRole()));
    }

    if (arkRolePolicyTemplate.getArkModule() != null) {
        criteria.add(Restrictions.eq("arkModule", arkRolePolicyTemplate.getArkModule()));
    }

    if (arkRolePolicyTemplate.getArkFunction() != null) {
        criteria.add(Restrictions.eq("arkFunction", arkRolePolicyTemplate.getArkFunction()));
    }

    return criteria.list();
}

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

License:Open Source License

public List<ArkFunctionType> getArkFunctionTypeList() {
    Criteria criteria = getSession().createCriteria(ArkFunctionType.class);
    return criteria.list();
}