Example usage for org.hibernate Query scroll

List of usage examples for org.hibernate Query scroll

Introduction

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

Prototype

ScrollableResults scroll();

Source Link

Document

Return the query results as ScrollableResults.

Usage

From source file:com.duroty.service.analyzer.LuceneFiltersAnalysis.java

License:Open Source License

/**
 * DOCUMENT ME!/*  w w w  . j  a  va2 s .  c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param username DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
private Vector getFilters(Session hsession, String username) {
    try {
        Vector filters = new Vector();

        Criteria crit = hsession.createCriteria(Users.class);
        crit.add(Restrictions.eq("useUsername", username));
        crit.add(Restrictions.eq("useActive", new Boolean(true)));

        Users user = (Users) crit.uniqueResult();

        Query query = hsession.getNamedQuery("filter-by-user");
        query.setInteger("user", user.getUseIdint());

        ScrollableResults scroll = query.scroll();

        while (scroll.next()) {
            filters.addElement(scroll.get(0));
        }

        return filters;
    } catch (Exception ex) {
        DLog.log(DLog.ERROR, this.getClass(), ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }

    return null;
}

From source file:com.duroty.task.IMAPServiceTask.java

License:Open Source License

/**
 * DOCUMENT ME!//w  w w  . ja  va  2s  .co m
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;
    Store store = null;
    Folder rootFolder = null;
    Folder folder = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(durotyMailFactory);
        store = msession.getStore("imap");

        String imapHost = msession.getProperty("mail.imap.host");

        Query query = hsession.getNamedQuery("users-mail");
        query.setBoolean("active", true);
        query.setString("role", "mail");

        ScrollableResults scroll = query.scroll();

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

            String repositoryName = user.getUseUsername();

            store.connect(imapHost, repositoryName, user.getUsePassword());

            rootFolder = store.getDefaultFolder();

            if ((rootFolder.getType() & Folder.HOLDS_FOLDERS) != 0) {
                folder = store.getFolder(this.imapInbox);

                Message[] messages = getMimeMessages(folder, new Flags(Flags.Flag.SEEN), false);
                MailUtilities.setFolderOpenAndReady(folder, Folder.READ_WRITE);

                if ((messages != null) && (messages.length > 0)) {
                    for (int i = 0; i < messages.length; i++) {
                        if (pool.size() >= poolSize) {
                            DLog.log(DLog.WARN, this.getClass(), "PoolSize " + pool.size());

                            break;
                        }

                        MimeMessage mime = null;

                        if (messages[i] instanceof MimeMessage) {
                            mime = new MimeMessage((MimeMessage) messages[i]);

                            String messageName = null;

                            if (folder instanceof IMAPFolder) {
                                messageName = String.valueOf(((IMAPFolder) folder).getUID(messages[i]));
                            } else {
                                messageName = String.valueOf(messages[i].getMessageNumber());
                            }

                            messageName += this.imapInbox;

                            boolean existMessage = existMessageName(hfactory.openSession(), user, messageName);

                            if (existMessage) {
                                messages[i].setFlag(Flags.Flag.SEEN, true);
                            } else {
                                String key = messageName + "--" + repositoryName;

                                if (!poolContains(key)) {
                                    addPool(key);

                                    if (!isSpam(user, mime)) {
                                        Mailet mailet = new Mailet(this, messageName, repositoryName, mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();

                                        //cal controlar si el borrem
                                        messages[i].setFlag(Flags.Flag.SEEN, true);
                                    } else {
                                        messages[i].setFlag(Flags.Flag.SEEN, true);
                                        messages[i].setFlag(Flags.Flag.DELETED, true);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                }

                MailUtilities.setFolderClose(folder, true);
                folder = null;
                messages = null;

                folder = store.getFolder(this.imapSent);
                messages = getMimeMessages(folder, new Flags(Flags.Flag.SEEN), false);
                MailUtilities.setFolderOpenAndReady(folder, Folder.READ_WRITE);

                if (!folder.exists()) {
                    folder.create(Folder.HOLDS_MESSAGES);
                }

                if (!folder.isSubscribed()) {
                    folder.setSubscribed(true);
                }

                if ((messages != null) && (messages.length > 0)) {
                    for (int i = 0; i < messages.length; i++) {
                        if (pool.size() >= poolSize) {
                            DLog.log(DLog.WARN, this.getClass(), "PoolSize " + pool.size());

                            break;
                        }

                        MimeMessage mime = null;

                        if (messages[i] instanceof MimeMessage) {
                            mime = new MimeMessage((MimeMessage) messages[i]);

                            mime.addHeader("X-DBox", "SENT");

                            String messageName = null;

                            if (folder instanceof IMAPFolder) {
                                messageName = String.valueOf(((IMAPFolder) folder).getUID(messages[i]));
                            } else {
                                messageName = String.valueOf(messages[i].getMessageNumber());
                            }

                            messageName += this.imapSent;

                            boolean existMessage = existMessageName(hfactory.openSession(), user, messageName);

                            if (existMessage) {
                                messages[i].setFlag(Flags.Flag.SEEN, true);
                            } else {
                                String key = messageName + "--" + repositoryName;

                                if (!poolContains(key)) {
                                    addPool(key);

                                    if (!isSpam(user, mime)) {
                                        Mailet mailet = new Mailet(this, messageName, repositoryName, mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();

                                        //cal controlar si el borrem
                                        messages[i].setFlag(Flags.Flag.SEEN, true);
                                    } else {
                                        messages[i].setFlag(Flags.Flag.SEEN, true);
                                        messages[i].setFlag(Flags.Flag.DELETED, true);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                }

                MailUtilities.setFolderClose(folder, true);
                folder = null;
                messages = null;

                folder = store.getFolder(this.imapDraft);
                messages = getMimeMessages(folder, new Flags(Flags.Flag.SEEN), false);
                MailUtilities.setFolderOpenAndReady(folder, Folder.READ_WRITE);

                if (!folder.exists()) {
                    folder.create(Folder.HOLDS_MESSAGES);
                }

                if (!folder.isSubscribed()) {
                    folder.setSubscribed(true);
                }

                if ((messages != null) && (messages.length > 0)) {
                    for (int i = 0; i < messages.length; i++) {
                        if (pool.size() >= poolSize) {
                            DLog.log(DLog.WARN, this.getClass(), "PoolSize " + pool.size());

                            break;
                        }

                        MimeMessage mime = null;

                        if (messages[i] instanceof MimeMessage) {
                            mime = new MimeMessage((MimeMessage) messages[i]);

                            mime.addHeader("X-DBox", "DRAFT");

                            String messageName = null;

                            if (folder instanceof IMAPFolder) {
                                messageName = String.valueOf(((IMAPFolder) folder).getUID(messages[i]));
                            } else {
                                messageName = String.valueOf(messages[i].getMessageNumber());
                            }

                            messageName += this.imapDraft;

                            boolean existMessage = existMessageName(hfactory.openSession(), user, messageName);

                            if (existMessage) {
                                messages[i].setFlag(Flags.Flag.SEEN, true);
                            } else {
                                String key = messageName + "--" + repositoryName;

                                if (!poolContains(key)) {
                                    addPool(key);

                                    if (!isSpam(user, mime)) {
                                        Mailet mailet = new Mailet(this, messageName, repositoryName, mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();

                                        //cal controlar si el borrem
                                        messages[i].setFlag(Flags.Flag.SEEN, true);
                                    } else {
                                        messages[i].setFlag(Flags.Flag.SEEN, true);
                                        messages[i].setFlag(Flags.Flag.DELETED, true);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                }

                MailUtilities.setFolderClose(folder, true);
                folder = null;
            }

            MailUtilities.setFolderClose(rootFolder, true);
            MailUtilities.setStoreClose(store);
        }
    } catch (Exception e) {
        System.gc();
        pool.clear();

        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        DLog.log(DLog.ERROR, this.getClass(), writer.toString());
    } catch (OutOfMemoryError e) {
        System.gc();
        pool.clear();

        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        DLog.log(DLog.ERROR, this.getClass(), writer.toString());
    } catch (Throwable e) {
        System.gc();
        pool.clear();

        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        DLog.log(DLog.ERROR, this.getClass(), writer.toString());
    } finally {
        System.gc();

        GeneralOperations.closeMailFolder(folder, false);
        GeneralOperations.closeMailFolder(rootFolder, false);
        GeneralOperations.closeMailStore(store);
        GeneralOperations.closeHibernateSession(hsession);

        setInit(false);
    }
}

From source file:com.duroty.task.POP3ServiceTask.java

License:Open Source License

/**
 * DOCUMENT ME!/* w  ww. ja va  2s  .c  o m*/
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(durotyMailFactory);

        String pop3Host = msession.getProperty("mail.pop3.host");

        int port = 0;

        try {
            port = Integer.parseInt(msession.getProperty("mail.pop3.port"));
        } catch (Exception ex) {
            port = 0;
        }

        Query query = hsession.getNamedQuery("users-mail");
        query.setBoolean("active", true);
        query.setString("role", "mail");

        ScrollableResults scroll = query.scroll();

        while (scroll.next()) {
            POP3Client client = new POP3Client();

            try {
                if (port > 0) {
                    client.connect(pop3Host, port);
                } else {
                    client.connect(pop3Host);
                }

                client.setState(POP3Client.AUTHORIZATION_STATE);

                //client.setDefaultTimeout()
                Users user = (Users) scroll.get(0);

                String repositoryName = user.getUseUsername();

                if (client.login(repositoryName, user.getUsePassword())) {
                    POP3MessageInfo[] info = client.listUniqueIdentifiers();

                    if ((info != null) && (info.length > 0)) {
                        for (int i = 0; i < info.length; i++) {
                            if (pool.size() >= poolSize) {
                                break;
                            }

                            Reader reader = client.retrieveMessage(info[i].number);

                            boolean existMessage = existMessageName(hfactory.openSession(), user,
                                    info[i].identifier);

                            String key = info[i].identifier + "--" + repositoryName;

                            if (existMessage) {
                                client.deleteMessage(info[i].number);
                            } else {
                                if (!poolContains(key)) {
                                    addPool(key);

                                    MimeMessage mime = buildMimeMessage(info[i].identifier, reader, user);

                                    if (!isSpam(user, mime)) {
                                        client.deleteMessage(info[i].number);

                                        Mailet mailet = new Mailet(this, info[i].identifier, repositoryName,
                                                mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();
                                    } else {
                                        client.deleteMessage(info[i].number);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                } else {
                }
            } catch (Exception e) {
            } finally {
                System.gc();

                try {
                    client.logout();
                    client.disconnect();
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (OutOfMemoryError e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (Throwable e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } finally {
        System.gc();

        GeneralOperations.closeHibernateSession(hsession);

        setInit(false);
    }
}

From source file:com.liferay.jbpm.util.QueryUtil.java

License:Open Source License

public static List<?> list(Query query, Dialect dialect, int begin, int end) {

    if ((begin == ALL_POS) && (end == ALL_POS)) {
        return query.list();
    } else {//from w w  w .  ja va  2s .co m
        if (dialect.supportsLimit()) {
            query.setMaxResults(end - begin);
            query.setFirstResult(begin);

            return query.list();
        } else {
            List<Object> list = new ArrayList<Object>();

            ScrollableResults sr = query.scroll();

            if (sr.first() && sr.scroll(begin)) {
                for (int i = begin; i < end; i++) {
                    Object obj = sr.get(0);

                    list.add(obj);

                    if (!sr.next()) {
                        break;
                    }
                }
            }

            return list;
        }
    }
}

From source file:com.liferay.jbpm.util.QueryUtil.java

License:Open Source License

public static List<?> randomList(Query query, Dialect dialect, int total, int num) {

    if ((total == 0) || (num == 0)) {
        return new ArrayList<Object>();
    }//from  w  w  w .  ja va  2s  . co m

    if (num >= total) {
        return list(query, dialect, ALL_POS, ALL_POS);
    }

    int[] scrollIds = Randomizer.getInstance().nextInt(total, num);

    List<Object> list = new ArrayList<Object>();

    ScrollableResults sr = query.scroll();

    for (int i = 0; i < scrollIds.length; i++) {
        if (sr.scroll(scrollIds[i])) {
            Object obj = sr.get(0);

            list.add(obj);

            sr.first();
        }
    }

    return list;
}

From source file:com.liferay.jbpm.util.QueryUtil.java

License:Open Source License

public static Comparable<?>[] getPrevAndNext(Query query, int count, OrderByComparator obc,
        Comparable<?> comparable) {

    int pos = count;
    int boundary = 0;

    Comparable<?>[] array = new Comparable[3];

    ScrollableResults sr = query.scroll();

    if (sr.first()) {
        while (true) {
            Object obj = sr.get(0);

            if (obj == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn("Object is null");
                }//w  w  w  .  j av a 2s .c  o m

                break;
            }

            Comparable<?> curComparable = (Comparable<?>) obj;

            int value = obc.compare(comparable, curComparable);

            if (_log.isDebugEnabled()) {
                _log.debug("Comparison result is " + value);
            }

            if (value == 0) {
                if (!comparable.equals(curComparable)) {
                    break;
                }

                array[1] = curComparable;

                if (sr.previous()) {
                    array[0] = (Comparable<?>) sr.get(0);
                }

                sr.next();

                if (sr.next()) {
                    array[2] = (Comparable<?>) sr.get(0);
                }

                break;
            }

            if (pos == 1) {
                break;
            }

            pos = (int) Math.ceil(pos / 2.0);

            int scrollPos = pos;

            if (value < 0) {
                scrollPos = scrollPos * -1;
            }

            boundary += scrollPos;

            if (boundary < 0) {
                scrollPos = scrollPos + (boundary * -1) + 1;

                boundary = 0;
            }

            if (boundary > count) {
                scrollPos = scrollPos - (boundary - count);

                boundary = scrollPos;
            }

            if (_log.isDebugEnabled()) {
                _log.debug("Scroll " + scrollPos);
            }

            if (!sr.scroll(scrollPos)) {
                if (value < 0) {
                    if (!sr.next()) {
                        break;
                    }
                } else {
                    if (!sr.previous()) {
                        break;
                    }
                }
            }
        }
    }

    return array;
}

From source file:com.lp.server.anfrage.fastlanereader.AnfrageartHandler.java

License:Open Source License

/**
 * sorts the data of the current query using the specified criterias and
 * returns the page of data where the row of selectedId is contained.
 * //from w  w  w  . j a va  2  s.  c o  m
 * @param sortierKriterien
 *            nach diesen Kriterien wird das Ergebnis sortiert
 * @param selectedId
 *            auf diesem Datensatz soll der Cursor stehen
 * @return QueryResult das Ergebnis der Abfrage
 * @throws EJBExceptionLP
 *             Ausnahme
 * @see UseCaseHandler#sort(SortierKriterium[], Object)
 */
public QueryResult sort(SortierKriterium[] sortierKriterien, Object selectedId) throws EJBExceptionLP {
    this.getQuery().setSortKrit(sortierKriterien);

    QueryResult result = null;
    int rowNumber = 0;

    if (selectedId != null) {
        SessionFactory factory = FLRSessionFactory.getFactory();
        Session session = null;

        try {
            session = factory.openSession();
            session = setFilter(session);
            String queryString = getFromClause() + buildWhereClause() + buildOrderByClause();

            Query query = session.createQuery(queryString);
            ScrollableResults scrollableResult = query.scroll();
            if (scrollableResult != null) {
                scrollableResult.beforeFirst();
                while (scrollableResult.next()) {
                    FLRAnfrageart anfrageart = (FLRAnfrageart) scrollableResult.get(0);
                    String c_nr = anfrageart.getC_nr();
                    if (selectedId.equals(c_nr)) {
                        rowNumber = scrollableResult.getRowNumber();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
        } finally {
            try {
                session.close();
            } catch (HibernateException he) {
                throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
            }
        }
    }

    if (rowNumber < 0 || rowNumber >= this.getRowCount()) {
        rowNumber = 0;
    }

    result = this.getPageAt(new Integer(rowNumber));
    result.setIndexOfSelectedRow(rowNumber);

    return result;
}

From source file:com.lp.server.anfrage.fastlanereader.AnfrageHandler.java

License:Open Source License

/**
 * sorts the data described by the current query using the specified sort
 * criterias. The current query is also updated with the new sort criterias.
 * /*  ww  w . j a  v  a2  s.  com*/
 * @param sortierKriterien
 *            nach diesen Kriterien wird das Ergebnis sortiert
 * @param selectedId
 *            auf diesem Datensatz soll der Cursor stehen
 * @return QueryResult das Ergebnis der Abfrage
 * @throws EJBExceptionLP
 *             Ausnahme
 * @see UseCaseHandler#sort(SortierKriterium[], Object)
 */
public QueryResult sort(SortierKriterium[] sortierKriterien, Object selectedId) throws EJBExceptionLP {
    QueryResult result = null;

    try {
        int rowNumber = 0;

        getQuery().setSortKrit(sortierKriterien);

        if (selectedId != null && ((Integer) selectedId).intValue() >= 0) {
            SessionFactory factory = FLRSessionFactory.getFactory();
            Session session = null;

            try {
                session = factory.openSession();
                String queryString = "select " + FLR_ANFRAGE + "i_id" + FLR_ANFRAGE_FROM_CLAUSE
                        + this.buildWhereClause() + this.buildOrderByClause();
                Query query = session.createQuery(queryString);
                ScrollableResults scrollableResult = query.scroll();
                if (scrollableResult != null) {
                    scrollableResult.beforeFirst();
                    while (scrollableResult.next()) {
                        Integer id = (Integer) scrollableResult.getInteger(0);
                        if (selectedId.equals(id)) {
                            rowNumber = scrollableResult.getRowNumber();
                            break;
                        }
                    }
                }
            } finally {
                try {
                    session.close();
                } catch (HibernateException he) {
                    throw new EJBExceptionLP(EJBExceptionLP.FEHLER_HIBERNATE, he);
                }
            }
        }

        if (rowNumber < 0 || rowNumber >= this.getRowCount()) {
            rowNumber = 0;
        }

        result = this.getPageAt(new Integer(rowNumber));
        result.setIndexOfSelectedRow(rowNumber);
    } catch (Throwable t) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER, new Exception(t));
    }

    return result;
}

From source file:com.lp.server.anfrage.fastlanereader.AnfragepositionartHandler.java

License:Open Source License

/**
 * sorts the data of the current query using the specified criterias and
 * returns the page of data where the row of selectedId is contained.
 * /*from ww  w  . ja  va  2s.  c o m*/
 * @param sortierKriterien
 *            nach diesen Kriterien wird das Ergebnis sortiert
 * @param selectedId
 *            auf diesem Datensatz soll der Cursor stehen
 * @return QueryResult das Ergebnis der Abfrage
 * @throws EJBExceptionLP
 *             Ausnahme
 * @see UseCaseHandler#sort(SortierKriterium[], Object)
 */
public QueryResult sort(SortierKriterium[] sortierKriterien, Object selectedId) throws EJBExceptionLP {
    this.getQuery().setSortKrit(sortierKriterien);

    QueryResult result = null;
    int rowNumber = 0;

    if (selectedId != null) {
        SessionFactory factory = FLRSessionFactory.getFactory();
        Session session = null;

        try {
            session = factory.openSession();
            String queryString = "select " + FLR_ANFRAGEPOSITIONART
                    + AnfrageServiceFac.FLR_ANFRAGEPOSITIONART_POSITIONSART_C_NR
                    + FLR_ANFRAGEPOSITIONART_FROM_CLAUSE + this.buildWhereClause() + this.buildOrderByClause();
            Query query = session.createQuery(queryString);
            ScrollableResults scrollableResult = query.scroll();
            if (scrollableResult != null) {
                scrollableResult.beforeFirst();
                while (scrollableResult.next()) {
                    String c_nr = (String) scrollableResult.getString(0);
                    if (selectedId.equals(c_nr)) {
                        rowNumber = scrollableResult.getRowNumber();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
        } finally {
            try {
                session.close();
            } catch (HibernateException he) {
                throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
            }
        }
    }

    if (rowNumber < 0 || rowNumber >= this.getRowCount()) {
        rowNumber = 0;
    }

    result = this.getPageAt(new Integer(rowNumber));
    result.setIndexOfSelectedRow(rowNumber);

    return result;
}

From source file:com.lp.server.anfrage.fastlanereader.AnfragepositionHandler.java

License:Open Source License

public QueryResult sort(SortierKriterium[] sortierKriterien, Object selectedId) throws EJBExceptionLP {
    this.getQuery().setSortKrit(sortierKriterien);

    QueryResult result = null;/*from   w w  w. ja v a 2s  .  co  m*/
    int rowNumber = 0;

    if (selectedId != null && ((Integer) selectedId).intValue() >= 0) {
        SessionFactory factory = FLRSessionFactory.getFactory();
        Session session = null;

        try {
            session = factory.openSession();
            String queryString = "select " + FLR_ANFRAGEPOSITION + "i_id" + FLR_ANFRAGEPOSITION_FROM_CLAUSE
                    + this.buildWhereClause() + this.buildOrderByClause();
            Query query = session.createQuery(queryString);
            ScrollableResults scrollableResult = query.scroll();
            if (scrollableResult != null) {
                scrollableResult.beforeFirst();
                while (scrollableResult.next()) {
                    Integer id = (Integer) scrollableResult.getInteger(0);
                    if (selectedId.equals(id)) {
                        rowNumber = scrollableResult.getRowNumber();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
        } finally {
            try {
                session.close();
            } catch (HibernateException he) {
                throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
            }
        }
    }

    if (rowNumber < 0 || rowNumber >= this.getRowCount()) {
        rowNumber = 0;
    }

    result = this.getPageAt(new Integer(rowNumber));
    result.setIndexOfSelectedRow(rowNumber);

    return result;
}