Example usage for org.hibernate ScrollableResults next

List of usage examples for org.hibernate ScrollableResults next

Introduction

In this page you can find the example usage for org.hibernate ScrollableResults next.

Prototype

boolean next();

Source Link

Document

Advance to the next result.

Usage

From source file:com.duroty.application.mail.manager.PreferencesManager.java

License:Open Source License

/**
 * DOCUMENT ME!// w w  w.ja  v  a 2 s  .  co m
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param idint DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void setIdentityDefault(Session hsession, String repositoryName, int idint) throws MailException {
    try {
        Users user = getUser(hsession, repositoryName);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.not(Restrictions.eq("ideIdint", new Integer(idint))));
        crit.add(Restrictions.eq("users", user));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Identity identity = (Identity) scroll.get(0);
            identity.setIdeDefault(false);
            hsession.update(identity);
        }

        crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("ideIdint", new Integer(idint)));
        crit.add(Restrictions.eq("users", user));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            identity.setIdeDefault(true);
            hsession.update(identity);
            hsession.flush();
        } else {
            throw new MailException("Error in default identity");
        }
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.SearchManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*from   w ww.  ja  va2  s.c om*/
 *
 * @param username DOCUMENT ME!
 * @param password DOCUMENT ME!
 * @param label DOCUMENT ME!
 * @param box DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws DMailException DOCUMENT ME!
 */
private ChainedFilter getChainedFilter(Session hsession, String username, int label, String box)
        throws Exception {
    ChainedFilter filter = null;

    try {
        Users user = getUser(hsession, username);

        org.hibernate.Query query1 = null;
        org.hibernate.Query query2 = null;

        String[] boxes = null;

        if ((box != null) && box.equals("ALL")) {
            boxes = new String[] { this.folderInbox, this.folderSent, this.folderDraft, this.folderHidden,
                    this.folderBlog, this.folderFiles };
        } else if (box != null) {
            boxes = new String[] { box };
        } else {
            boxes = new String[] { this.folderInbox, this.folderSent, this.folderDraft, this.folderHidden,
                    this.folderBlog, this.folderFiles };
        }

        if ((boxes == null) && (label == 0)) {
            return null;
        } else if ((boxes != null) && (label == 0)) {
            query1 = hsession.getNamedQuery("count-messages-by-folder");
            query1.setParameterList("folder", boxes);
            query1.setInteger("user", user.getUseIdint());

            query2 = hsession.getNamedQuery("messages-by-folder");
            query2.setParameterList("folder", boxes);
            query2.setInteger("user", user.getUseIdint());
        } else if ((boxes == null) && (label > 0)) {
            query1 = hsession.getNamedQuery("count-messages-by-label");
            query1.setInteger("label", label);
            query1.setInteger("user", user.getUseIdint());
            query1.setString("folderTrash", this.folderTrash);
            query1.setString("folderSpam", this.folderSpam);
            query1.setString("folderDelete", FOLDER_DELETE);

            query2 = hsession.getNamedQuery("messages-by-label");
            query2.setInteger("label", label);
            query2.setInteger("user", user.getUseIdint());
            query2.setString("folderTrash", this.folderTrash);
            query2.setString("folderSpam", this.folderSpam);
            query2.setString("folderDelete", FOLDER_DELETE);
        } else {
            query1 = hsession.getNamedQuery("count-messages-by-folder-label");
            query1.setInteger("label", label);
            query1.setParameterList("folder", boxes);
            query1.setInteger("user", user.getUseIdint());
            query1.setString("folderTrash", this.folderTrash);
            query1.setString("folderSpam", this.folderSpam);
            query1.setString("folderDelete", FOLDER_DELETE);

            query2 = hsession.getNamedQuery("messages-by-folder-label");
            query2.setInteger("label", label);
            query2.setParameterList("folder", boxes);
            query2.setInteger("user", user.getUseIdint());
            query2.setString("folderTrash", this.folderTrash);
            query2.setString("folderSpam", this.folderSpam);
            query2.setString("folderDelete", FOLDER_DELETE);
        }

        Integer count = (Integer) query1.uniqueResult();

        if (count.intValue() > 0) {
            QueryFilter[] qFilters = new QueryFilter[count.intValue()];

            ScrollableResults scroll = query2.scroll();

            int i = 0;

            while (scroll.next()) {
                Message message = (Message) scroll.get(0);
                qFilters[i] = new QueryFilter(
                        new TermQuery(new Term(LuceneMessageConstants.Field_idint, message.getMesName())));
                i++;
            }

            filter = new ChainedFilter(qFilters);
        } else {
            QueryFilter[] qFilters = new QueryFilter[0];
            filter = new ChainedFilter(qFilters);
        }

        return filter;
    } finally {
    }
}

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

License:Open Source License

/**
 * Loads the token frequencies from the database.
 * @param conn The connection for accessing the database
 * @throws Exception//from w ww. j a va2 s.com
 */
public void loadHamNSpam(String username) throws Exception {
    SessionFactory hfactory = null;
    Session hsession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(BayesianHam.class);
        crit.add(Restrictions.eq("users", user));

        ScrollableResults scroll = crit.scroll();

        Map ham = getHamTokenCounts();

        while (scroll.next()) {
            BayesianHam bham = (BayesianHam) scroll.get(0);

            String token = bham.getHamToken();
            int count = bham.getHamOcurrences();

            // to reduce memory, use the token only if the count is > 1
            if (count > 1) {
                ham.put(token, new Integer(count));
            }
        }

        crit = hsession.createCriteria(BayesianSpam.class);
        crit.add(Restrictions.eq("users", user));

        scroll = crit.scroll();

        Map spam = getSpamTokenCounts();

        while (scroll.next()) {
            BayesianSpam bspam = (BayesianSpam) scroll.get(0);
            String token = bspam.getSpamToken();
            int count = bspam.getSpamOcurrences();

            // to reduce memory, use the token only if the count is > 1
            if (count > 1) {
                spam.put(token, new Integer(count));
            }
        }

        //Get the ham/spam message counts.
        crit = hsession.createCriteria(BayesianMessagecounts.class);
        crit.add(Restrictions.eq("users", user));

        BayesianMessagecounts bmc = (BayesianMessagecounts) crit.uniqueResult();

        if (bmc != null) {
            setHamMessageCount(bmc.getHamCount());
            setSpamMessageCount(bmc.getSpamCount());
        }
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

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

License:Open Source License

/**
 * DOCUMENT ME!//from   ww  w. ja  v a2s  .  c om
 *
 * @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.BookmarkServiceTask.java

License:Open Source License

/**
 * DOCUMENT ME!/*from   w  w  w  .j av a2  s. com*/
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();

        Criteria crit = hsession.createCriteria(Bookmark.class);

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            if (pool.size() >= poolSize) {
                break;
            }

            Bookmark bookmark = (Bookmark) scroll.get(0);

            Users user = bookmark.getUsers();

            String idint = NumberUtils.pad(Long.parseLong(String.valueOf(bookmark.getBooIdint())));

            String key = idint + "--" + user.getUseUsername();

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

                BookmarkObj bookmarkObj = new BookmarkObj();
                bookmarkObj.setIdint(idint);
                bookmarkObj.setUrl(bookmark.getBooUrl());

                Bookmarklet bookmarklet = new Bookmarklet(this, idint, user.getUseUsername(), bookmarkObj);
                Thread thread = new Thread(bookmarklet, key);
                thread.start();

                hsession.delete(bookmark);
                hsession.flush();
            }

            Thread.sleep(100);
        }
    } catch (Exception e) {
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
        System.gc();
    } catch (OutOfMemoryError e) {
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
        System.gc();
    } catch (Throwable e) {
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } finally {
        GeneralOperations.closeHibernateSession(hsession);

        setInit(false);
    }
}

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

License:Open Source License

/**
 * DOCUMENT ME!//from   w w  w  .  j  a  v a 2s .c om
 *
 * @param dirUsers DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public void flush() throws Exception {
    SessionFactory hfactory = null;
    Session hsession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();

        Calendar cal = new GregorianCalendar();

        //int hour = cal.get(Calendar.HOUR_OF_DAY);
        //int minute = cal.get(Calendar.MINUTE);
        //int second = cal.get(Calendar.SECOND);
        Calendar cal1 = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE) - 1,
                cal.get(Calendar.SECOND));
        Date date = new Date(cal1.getTimeInMillis());

        Criteria crit = hsession.createCriteria(Conversations.class);
        crit.add(Restrictions.le("convStamp", date));
        crit.addOrder(Order.asc("convStamp"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            hsession.delete(scroll.get(0));
            hsession.flush();
        }
    } catch (Exception e) {
        System.gc();

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

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

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

        setInit(false);

        System.gc();
    }
}

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

License:Open Source License

/**
 * DOCUMENT ME!/*from   w w  w. ja  va  2s  .  c om*/
 *
 * @param dirUsers DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public void flush() throws Exception {
    SessionFactory hfactory = null;
    Session hsession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();

        Calendar cal = new GregorianCalendar();

        //int hour = cal.get(Calendar.HOUR_OF_DAY);
        //int minute = cal.get(Calendar.MINUTE);
        //int second = cal.get(Calendar.SECOND);
        Calendar cal1 = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE) - 5,
                cal.get(Calendar.SECOND));
        Date date = new Date(cal1.getTimeInMillis());

        Criteria crit = hsession.createCriteria(Users.class);
        crit.add(Restrictions.le("useLastPing", date));
        crit.add(Restrictions.not(Restrictions.eq("useIsOnline", new Integer(0))));
        crit.add(Restrictions.isNotNull("useIsOnline"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Users user = (Users) scroll.get(0);
            user.setUseIsOnline(0);
            hsession.update(user);
            hsession.flush();
        }

        /*cal1 = new GregorianCalendar(cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
            cal.get(Calendar.HOUR_OF_DAY),
            cal.get(Calendar.MINUTE) - 1, cal.get(Calendar.SECOND));
        date = new Date(cal1.getTimeInMillis());
                
        crit = hsession.createCriteria(Conversations.class);
        crit.add(Restrictions.le("convStamp", date));
                
        scroll = crit.scroll();
                
        while (scroll.next()) {
            Conversations conv = (Conversations) scroll.get(0);
        hsession.update(conv);
        hsession.flush();
        }*/
    } catch (Exception e) {
        System.gc();

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

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

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

        setInit(false);

        System.gc();
    }
}

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

License:Open Source License

/**
 * DOCUMENT ME!/*from   www  .  ja  va 2  s.c  om*/
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();

        Criteria crit = hsession.createCriteria(Message.class);
        crit.add(Restrictions.eq("mesBox", folderDelete));

        ScrollableResults scroll = crit.scroll();

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

            Users user = message.getUsers();
            String mid = message.getMesName();

            hsession.delete(message);
            hsession.flush();

            this.messageable.deleteMimeMessage(mid, user);

            /*try {
                    
            } catch (HibernateException e) {
            } catch (OutOfMemoryError e) {
                System.gc();
            } catch (Exception e) {
            } catch (Throwable e) {
            }*/
            Thread.sleep(100);
        }
    } catch (Exception e) {
        System.gc();
        DLog.log(DLog.WARN, this.getClass(), e.getMessage());
    } catch (OutOfMemoryError e) {
        System.gc();
        DLog.log(DLog.WARN, this.getClass(), e.getMessage());
    } catch (Throwable e) {
        System.gc();
        DLog.log(DLog.WARN, this.getClass(), e.getMessage());
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        setInit(false);
    }
}

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

License:Open Source License

/**
 * DOCUMENT ME!//  w ww  . j a  v  a2 s .  c o 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!/*from w w  w .  j av  a 2 s.c  om*/
 */
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);
    }
}