Example usage for org.hibernate Criteria scroll

List of usage examples for org.hibernate Criteria scroll

Introduction

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

Prototype

public ScrollableResults scroll() throws HibernateException;

Source Link

Document

Get the results as an instance of ScrollableResults .

Usage

From source file:com.amalto.core.storage.hibernate.InstanceScrollOptimization.java

License:Open Source License

@Override
public StorageResults visit(Select select) {
    ComplexTypeMetadata mainType = select.getTypes().get(0);
    Paging paging = select.getPaging();//from  w w w  .j  av a 2s .c  o  m
    int start = paging.getStart();
    if (start != 0) {
        throw new IllegalStateException(
                "This optimization is only use for iterating over all instances (start is not supported).");
    }
    if (paging.getLimit() != Integer.MAX_VALUE) {
        // Optimization *could* work when page size is set... however it also means the analysis of the query is
        // redirecting to the wrong optimization, and this is an issue.
        throw new UnsupportedOperationException();
    }
    // Perform same query as input *but* adds an order by clause 'by id' that allows efficient filtering (iterator
    // should
    // only return unique results).
    Select copy = select.copy();
    Collection<FieldMetadata> keyFields = mainType.getKeyFields();
    for (FieldMetadata keyField : keyFields) {
        copy.addOrderBy(new OrderBy(new Field(keyField), OrderBy.Direction.ASC));
    }
    Criteria criteria = createCriteria(copy); // Perform the query with order by id.
    // Create the filtered result iterator
    CloseableIterator<DataRecord> nonFilteredIterator = new ScrollableIterator(mappings, storageClassLoader,
            criteria.scroll(), callbacks);
    Predicate isUniqueFilter = new UniquePredicate(); // Unique filter returns only different instances
    Iterator filteredIterator = IteratorUtils.filteredIterator(nonFilteredIterator, isUniqueFilter);
    FilteredIteratorWrapper uniqueIterator = new FilteredIteratorWrapper(nonFilteredIterator, filteredIterator,
            select);
    return new HibernateStorageResults(storage, select, uniqueIterator);
}

From source file:com.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*from  w w w . j  a va  2 s. c  om*/
 *
 * @param hsession DOCUMENT ME!
 * @param userObj DOCUMENT ME!
 *
 * @throws AdminException DOCUMENT ME!
 */
public void addUser(Session hsession, UserObj userObj) throws AdminException {
    try {
        Users users = new Users();
        users.setUseActive(userObj.isActive());
        users.setUseEmail(userObj.getEmail());
        users.setUseLanguage(userObj.getLanguage());
        users.setUseName(userObj.getName());
        users.setUsePassword(userObj.getPassword());
        users.setUseRegisterDate(userObj.getRegisterDate());
        users.setUseUsername(userObj.getUsername());

        if ((userObj.getRoles() != null) && (userObj.getRoles().length > 0)) {
            Criteria crit = hsession.createCriteria(Roles.class);
            crit.add(Restrictions.in("rolIdint", userObj.getRoles()));

            ScrollableResults scroll = crit.scroll();

            while (scroll.next()) {
                UserRole userRole = new UserRole(new UserRoleId(users, (Roles) scroll.get(0)));
                users.addUserRole(userRole);
            }
        }

        hsession.save(users);
        hsession.flush();

        MailPreferences mailPreferences = new MailPreferences();
        mailPreferences.setUsers(users);
        mailPreferences.setMaprHtmlMessage(userObj.isHtmlMessages());
        mailPreferences.setMaprMessagesByPage(userObj.getMessagesByPage());
        mailPreferences.setMaprQuotaSize(userObj.getQuotaSize());

        if (userObj.getSignature() != null) {
            mailPreferences.setMaprSignature("\n" + userObj.getSignature().replaceAll("'", "\\\\'"));
        }

        if (userObj.isSpamTolerance()) {
            mailPreferences.setMaprSpamTolerance(100);
        } else {
            mailPreferences.setMaprSpamTolerance(-1);
        }

        mailPreferences.setMaprVacationActive(userObj.isVactionActive());
        mailPreferences.setMaprVacationBody(userObj.getVacationBody());
        mailPreferences.setMaprVacationSubject(userObj.getVacationSubject());

        hsession.save(mailPreferences);
        hsession.flush();

        Identity identity = new Identity();
        identity.setIdeActive(true);
        identity.setIdeCode(RandomStringUtils.randomAlphanumeric(25));
        identity.setIdeDefault(true);
        identity.setIdeEmail(userObj.getEmailIdentity());
        identity.setIdeName(userObj.getName());
        identity.setIdeReplyTo(userObj.getEmailIdentity());
        identity.setUsers(users);

        hsession.save(identity);
        hsession.flush();
    } catch (Exception ex) {
        throw new AdminException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*from  ww  w .  ja  va2  s .co m*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param token DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public SearchUsersObj allUsers(Session hsession, int page, int byPage) throws Exception {
    SearchUsersObj searchUsersObj = new SearchUsersObj();
    Vector users = new Vector();

    try {
        Criteria crit = hsession.createCriteria(Users.class);
        searchUsersObj.setHits(crit.list().size());

        crit = hsession.createCriteria(Users.class);
        crit.setFirstResult(page * byPage);
        crit.setMaxResults(byPage);
        crit.addOrder(Order.asc("useName"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Users user = (Users) scroll.get(0);

            UserObj obj = new UserObj();

            obj.setActive(user.isUseActive());
            obj.setEmail(user.getUseEmail());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            obj.setHtmlMessages(mailPreferences.isMaprHtmlMessage());
            obj.setIdint(user.getUseIdint());
            obj.setLanguage(user.getUseLanguage());
            obj.setMessagesByPage(mailPreferences.getMaprMessagesByPage());
            obj.setName(user.getUseName());
            obj.setPassword(user.getUsePassword());
            obj.setQuotaSize(mailPreferences.getMaprQuotaSize());
            obj.setRegisterDate(user.getUseRegisterDate());

            Integer[] roles = new Integer[user.getUserRoles().size()];

            if (roles.length > 0) {
                it = user.getUserRoles().iterator();

                int i = 0;

                while (it.hasNext()) {
                    UserRole userRole = (UserRole) it.next();
                    roles[i] = new Integer(userRole.getId().getRoles().getRolIdint());
                    i++;
                }
            }

            obj.setRoles(roles);

            obj.setSignature(mailPreferences.getMaprSignature());

            if (mailPreferences.getMaprSpamTolerance() == 100) {
                obj.setSpamTolerance(true);
            } else {
                obj.setSpamTolerance(false);
            }

            obj.setUsername(user.getUseUsername());
            obj.setVacationBody(mailPreferences.getMaprVacationBody());
            obj.setVacationSubject(mailPreferences.getMaprVacationSubject());
            obj.setVactionActive(mailPreferences.isMaprVacationActive());

            int usedQuotaSize = getUsedQuotaSize(hsession, user);
            usedQuotaSize /= 1024;

            if (usedQuotaSize > 1024) {
                usedQuotaSize /= 1024;
                obj.setUsedQuota(usedQuotaSize + " MB");
            } else {
                obj.setUsedQuota(((usedQuotaSize > 0) ? (usedQuotaSize + "") : "<1") + " kB");
            }

            users.addElement(obj);
        }

        searchUsersObj.setUsers(users);

        return searchUsersObj;
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*from ww  w .j  av  a  2s.  c om*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param token DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public SearchUsersObj suggestUsers(Session hsession, String token, int page, int byPage) throws Exception {
    SearchUsersObj searchUsersObj = new SearchUsersObj();
    Vector users = new Vector();

    try {
        Criteria crit = hsession.createCriteria(Users.class);
        crit.add(Restrictions.or(Restrictions.ilike("useName", token, MatchMode.ANYWHERE),
                Restrictions.ilike("useEmail", token, MatchMode.ANYWHERE)));
        searchUsersObj.setHits(crit.list().size());

        crit = hsession.createCriteria(Users.class);
        crit.add(Restrictions.or(Restrictions.ilike("useName", token, MatchMode.ANYWHERE),
                Restrictions.ilike("useEmail", token, MatchMode.ANYWHERE)));
        crit.setFirstResult(page * byPage);
        crit.setMaxResults(byPage);
        crit.addOrder(Order.asc("useName"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Users user = (Users) scroll.get(0);

            UserObj obj = new UserObj();

            obj.setActive(user.isUseActive());
            obj.setEmail(user.getUseEmail());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            obj.setHtmlMessages(mailPreferences.isMaprHtmlMessage());
            obj.setIdint(user.getUseIdint());
            obj.setLanguage(user.getUseLanguage());
            obj.setMessagesByPage(mailPreferences.getMaprMessagesByPage());
            obj.setName(user.getUseName());
            obj.setPassword(user.getUsePassword());
            obj.setQuotaSize(mailPreferences.getMaprQuotaSize());
            obj.setRegisterDate(user.getUseRegisterDate());

            Integer[] roles = new Integer[user.getUserRoles().size()];

            if (roles.length > 0) {
                it = user.getUserRoles().iterator();

                int i = 0;

                while (it.hasNext()) {
                    UserRole userRole = (UserRole) it.next();
                    roles[i] = new Integer(userRole.getId().getRoles().getRolIdint());
                    i++;
                }
            }

            obj.setRoles(roles);

            obj.setSignature(mailPreferences.getMaprSignature());

            if (mailPreferences.getMaprSpamTolerance() == 100) {
                obj.setSpamTolerance(true);
            } else {
                obj.setSpamTolerance(false);
            }

            obj.setUsername(user.getUseUsername());
            obj.setVacationBody(mailPreferences.getMaprVacationBody());
            obj.setVacationSubject(mailPreferences.getMaprVacationSubject());
            obj.setVactionActive(mailPreferences.isMaprVacationActive());

            int usedQuotaSize = getUsedQuotaSize(hsession, user);
            usedQuotaSize /= 1024;

            if (usedQuotaSize > 1024) {
                usedQuotaSize /= 1024;
                obj.setUsedQuota(usedQuotaSize + " MB");
            } else {
                obj.setUsedQuota(((usedQuotaSize > 0) ? (usedQuotaSize + "") : "<1") + " kB");
            }

            users.addElement(obj);
        }

        searchUsersObj.setUsers(users);

        return searchUsersObj;
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*w  w w.  j  a v  a 2  s . c  o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param userObj DOCUMENT ME!
 *
 * @throws AdminException DOCUMENT ME!
 */
public void updateUser(Session hsession, UserObj userObj) throws AdminException {
    try {
        Criteria crit1 = hsession.createCriteria(Users.class);
        crit1.add(Restrictions.eq("useIdint", new Integer(userObj.getIdint())));

        Users users = (Users) crit1.uniqueResult();

        if (users == null) {
            throw new AdminException("The user don't exist");
        }

        Set roles = users.getUserRoles();
        Iterator it = roles.iterator();

        while (it.hasNext()) {
            UserRole ur = (UserRole) it.next();

            //roles.remove(ur);
            hsession.delete(ur);
        }

        users.setUserRoles(new HashSet(0));
        hsession.update(users);
        hsession.flush();

        users.setUseActive(userObj.isActive());
        users.setUseEmail(userObj.getEmail());
        users.setUseLanguage(userObj.getLanguage());
        users.setUseName(userObj.getName());

        if (!StringUtils.isBlank(userObj.getPassword())) {
            users.setUsePassword(userObj.getPassword());
        }

        if ((userObj.getRoles() != null) && (userObj.getRoles().length > 0)) {
            Criteria crit2 = hsession.createCriteria(Roles.class);
            crit2.add(Restrictions.in("rolIdint", userObj.getRoles()));

            Set set = new HashSet();
            ScrollableResults scroll = crit2.scroll();

            while (scroll.next()) {
                UserRole userRole = new UserRole(new UserRoleId(users, (Roles) scroll.get(0)));
                set.add(userRole);
            }

            users.setUserRoles(set);

            hsession.update(users);
            hsession.flush();
        }

        it = users.getMailPreferenceses().iterator();

        MailPreferences mailPreferences = (MailPreferences) it.next();
        mailPreferences.setUsers(users);
        mailPreferences.setMaprHtmlMessage(userObj.isHtmlMessages());
        mailPreferences.setMaprMessagesByPage(userObj.getMessagesByPage());
        mailPreferences.setMaprQuotaSize(userObj.getQuotaSize());

        if (userObj.getSignature() != null) {
            mailPreferences.setMaprSignature("\n" + userObj.getSignature().replaceAll("'", "\\\\'"));
        }

        if (userObj.isSpamTolerance()) {
            mailPreferences.setMaprSpamTolerance(100);
        } else {
            mailPreferences.setMaprSpamTolerance(-1);
        }

        mailPreferences.setMaprVacationActive(userObj.isVactionActive());
        mailPreferences.setMaprVacationBody(userObj.getVacationBody());
        mailPreferences.setMaprVacationSubject(userObj.getVacationSubject());

        hsession.update(mailPreferences);
        hsession.flush();
    } catch (Exception ex) {
        throw new AdminException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!//from w w  w .j av  a  2s. co  m
 *
 * @param hsession DOCUMENT ME!
 * @param idint DOCUMENT ME!
 *
 * @throws AdminException DOCUMENT ME!
 */
public void deleteUsers(Session hsession, Integer[] idints) throws AdminException {
    try {
        Criteria crit = hsession.createCriteria(Users.class);
        crit.add(Restrictions.in("useIdint", idints));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Users users = (Users) scroll.get(0);

            if (users != null) {
                hsession.delete(users);
                hsession.flush();
            }
        }
    } catch (Exception ex) {
        throw new AdminException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!//  ww  w .j a  v  a2  s.  co m
 *
 * @param hsession DOCUMENT ME!
 * @param idint DOCUMENT ME!
 *
 * @throws AdminException DOCUMENT ME!
 */
public Vector roles(Session hsession) throws AdminException {
    Vector roles = new Vector();

    try {
        Criteria crit = hsession.createCriteria(Roles.class);
        crit.addOrder(Order.asc("rolName"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Roles role = (Roles) scroll.get(0);
            roles.addElement(new RoleObj(role.getRolIdint(), role.getRolName()));
        }

        return roles;
    } catch (Exception ex) {
        throw new AdminException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.chat.manager.ChatManager.java

License:Open Source License

/**
 * DOCUMENT ME!//  w  w w  .  j a  v a  2  s  . co  m
 *
 * @param hsession DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param away DOCUMENT ME!
 *
 * @throws ChatException DOCUMENT ME!
 */
public String ping(Session hsession, String username, int away) throws ChatException {
    try {
        Vector buddiesOnline = new Vector();
        Vector buddiesOffline = new Vector();
        Vector buddies = new Vector();
        Vector messages = new Vector();
        JSONObject json = new JSONObject();

        Users user = getUser(hsession, username);

        if (user.getUseIsOnline() >= 3) {
            user.setUseLastPing(new Date());
            hsession.update(user);
            hsession.flush();
        } else if (user.getUseLastState() > 0) {
            user.setUseIsOnline(user.getUseLastState());
            user.setUseLastPing(new Date());
            hsession.update(user);
            hsession.flush();
        } else {
            user.setUseIsOnline(0);
            user.setUseCustomMessage(null);
            user.setUseLastPing(new Date());
            hsession.update(user);
            hsession.flush();

            throw new NotLoggedInException();
        }

        json.put("state", user.getUseIsOnline());
        json.put("lastState", user.getUseLastState());
        json.put("awayMessage", user.getUseCustomMessage());

        Criteria crit2 = hsession.createCriteria(Conversations.class);
        crit2.add(Restrictions.eq("usersByConvRecipientIdint", user));

        ScrollableResults scroll2 = crit2.scroll();

        int numMessages = 0;

        while (scroll2.next()) {
            Conversations conversations = (Conversations) scroll2.get(0);
            messages.addElement(new ConversationsObj(conversations.getUsersByConvSenderIdint().getUseUsername(),
                    conversations.getConvMessage()));

            hsession.delete(conversations);

            numMessages++;
        }

        hsession.flush();

        json.put("numMessages", new Integer(numMessages));
        json.put("messages", messages);

        Criteria crit1 = hsession.createCriteria(BuddyList.class);
        crit1.add(Restrictions.eq("usersByBuliOwnerIdint", user));
        crit1.add(Restrictions.eq("buliActive", new Boolean(true)));
        crit1.addOrder(Order.desc("buliLastDate"));

        ScrollableResults scroll1 = crit1.scroll();

        while (scroll1.next()) {
            BuddyList buddyList = (BuddyList) scroll1.get(0);
            Users buddy = buddyList.getUsersByBuliBuddyIdint();

            if (buddy.isUseActive()) {
                String name = buddy.getUseName();

                if (StringUtils.isBlank(name)) {
                    name = buddy.getUseUsername();
                }

                if (buddy.getUseIsOnline() == 0) {
                    buddiesOffline
                            .addElement(new BuddyObj(name, buddy.getUseUsername(), buddy.getUseIsOnline()));
                } else {
                    buddiesOnline
                            .addElement(new BuddyObj(name, buddy.getUseUsername(), buddy.getUseIsOnline()));
                }
            }
        }

        if (!buddiesOnline.isEmpty()) {
            buddies.addAll(buddiesOnline);
        }

        if (!buddiesOffline.isEmpty()) {
            buddies.addAll(buddiesOffline);
        }

        json.put("buddy", buddies);

        return json.toString();
    } catch (Exception e) {
        throw new ChatException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.files.manager.FilesManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*  w  ww  .  j a v  a2 s .c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public Vector getLabels(Session hsession, String repositoryName) throws FilesException {
    Vector labels = new Vector();

    try {
        Criteria criteria = hsession.createCriteria(Label.class);
        criteria.add(Restrictions.eq("users", getUser(hsession, repositoryName)));
        criteria.addOrder(Order.asc("labName"));

        ScrollableResults scroll = criteria.scroll();

        while (scroll.next()) {
            Label label = (Label) scroll.get(0);

            LabelObj obj = new LabelObj(label.getLabIdint(), label.getLabName());

            labels.addElement(obj);
        }

        return labels;
    } catch (Exception e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.files.manager.FilesManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*from  ww w . ja  v  a2 s  .  c om*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param mids DOCUMENT ME!
 * @param folder DOCUMENT ME!
 *
 * @throws FilesException DOCUMENT ME!
 */
public void moveFiles(Session hsession, String repositoryName, String[] mids, String folder)
        throws FilesException {
    if ((mids == null) || (mids.length == 0)) {
        throw new FilesException("ErrorMessages.messages.selection.null");
    }

    try {
        folder = parseFolder(folder);

        if (folder.equals(this.folderAll)) {
            folder = this.folderHidden;
        }

        Criteria crit = hsession.createCriteria(Message.class);
        crit.add(Restrictions.in("mesName", mids));
        crit.add(Restrictions.eq("users", getUser(hsession, repositoryName)));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Message message = (Message) scroll.get(0);

            message.setMesBox(folder);

            hsession.update(message);
            hsession.flush();
        }
    } catch (Exception ex) {
        throw new FilesException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}