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:br.com.gvt.eng.vod.dao.AssetDAO.java

public Map<String, Integer> retrieveSearchTerms(String where) {
    // Efetuando a consulta na base
    ScrollableResults scrollableResults = getSession()
            .createSQLQuery("SELECT title, original_title, description, director, actors from IPVOD_ASSET a "
                    + "left join IPVOD_VISUAL_MENU_ASSET_INDEX ma on (ma.ASSET_ID = A.ASSET_ID) " + where)
            .setFetchSize(2000).setCacheable(false).setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);

    List<String> list = new ArrayList<String>();
    Map<String, Integer> map = new HashMap<String, Integer>();

    // Lendo o resultSet
    while (scrollableResults.next()) {
        for (int i = 0; i < 3; i++) {
            if (scrollableResults.get(i) != null && !"".equals(scrollableResults.get(i).toString())
                    && !"null".equals(scrollableResults.get(i).toString())) {
                list.add(scrollableResults.get(i).toString());
                map.put(scrollableResults.get(i).toString(), 0);
            }//from ww w . j  a v  a  2 s.c o m
        }
    }
    Map<String, Integer> mp = null;
    mp = uniqueTermsCounter(list);

    ValueComparator bvc = new ValueComparator(mp);
    TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(bvc);
    sorted_map.putAll(mp);
    return sorted_map;
}

From source file:ca.ualberta.physics.cssdp.catalogue.dao.UrlDataProductDao.java

License:Apache License

public void process(UrlDataProductUpdateMap urlDataProductUpdateMap) {

    if (urlDataProductUpdateMap.getUrls().size() == 0) {
        return;//from   w ww.  j a  v  a 2 s. c om
    }

    /*
     * The size of scannedUrlDataProducts should be <= jdbc batch size
     * configured.
     */

    // we have to resort to hibernate directly because JPA does not have
    // scrolling capability
    Session session = emp.get().unwrap(Session.class).getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();

    // "in" clause limit is 2^16 on Postgresql, it might be different on
    // other dbs
    String hqlString = "from UrlDataProduct urldp where urldp.url in (:urls)";

    // the fastest way to scroll through the existing data
    Query q = session.createQuery(hqlString);
    q.setParameterList("urls", urlDataProductUpdateMap.getUrls());
    q.setCacheMode(CacheMode.IGNORE);
    ScrollableResults existingData = q.scroll(ScrollMode.FORWARD_ONLY);

    while (existingData.next()) {

        UrlDataProduct existing = (UrlDataProduct) existingData.get(0);
        UrlDataProduct updated = urlDataProductUpdateMap.get(existing.getUrl());

        if (updated != null) {

            /*
             * Only bother to update the record if it's actually changed.
             * Note that the scan timestamp is ignored in the check because
             * that isn't something the provider changed. A change can also
             * mean the url was deleted, and now it's back.
             */
            if (existing.hasChanged(updated)) {
                // existing.setDataProduct(updated.getDataProduct());
                existing.setUrl(updated.getUrl());
                existing.setStartTimestamp(updated.getStartTimestamp());
                existing.setEndTimestamp(updated.getEndTimestamp());
                existing.setScanTimestamp(updated.getScanTimestamp());
                existing.setDeleted(false);
                urlDataProductUpdateMap.remove(updated.getUrl());
                session.update(existing);
            } else {
                // remove it so it's not duplicated
                urlDataProductUpdateMap.remove(existing.getUrl());
            }

        } else {

            // if we get here it means the existing url has been removed
            // from the server, set "delete" it from the catalogue
            existing.setDeleted(true);
            existing.setScanTimestamp(new LocalDateTime());

        }

    }

    // persist the new url mappings
    for (String newUrl : urlDataProductUpdateMap.getUrls()) {
        UrlDataProduct newUrlDataProduct = urlDataProductUpdateMap.get(newUrl);
        session.save(newUrlDataProduct);
        logger.debug("saved a mapping: " + newUrlDataProduct.getUrl());
    }

    session.flush();
    session.clear();

    tx.commit();
    session.close();

}

From source file:ch.qos.logback.audit.persistent.AuditEventDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
static public List<Object[]> findMaxSubject() throws HibernateException {
    Session s = null;/*from w  w  w  .jav  a  2s  .co  m*/
    try {
        s = openSession();

        //      Query q = s.createQuery("select grp.sc, grp.sub from ( " +
        //
        //      " select count(subject) as sub, subject from "
        //          + AuditEvent.class.getName() + " GROUP BY subject) AS grp");

        Query q = s.createQuery("select count(ae.subject), ae.subject FROM " + AE_CLASS + " AS ae "
                + "GROUP BY ae.subject ORDER BY count(ae.subject) desc");
        ScrollableResults sr = q.scroll();
        List<Object[]> l = new ArrayList<Object[]>();
        int i = 0;
        while (sr.next()) {
            System.out.println(i++);
            Object[] oa = sr.get();
            l.add(oa);
        }

        return l;
    } finally {
        close(s);
    }
}

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

License:Open Source License

public ProjectionIterator(MappingRepository mappingMetadataRepository, final ScrollableResults results,
        List<TypedExpression> selectedFields, final Set<ResultsCallback> callbacks) {
    this(mappingMetadataRepository, new CloseableIterator<Object>() {

        private boolean hasNext;

        private boolean isClosed = false;

        private boolean consumedResult = true;

        @Override/*w w w .j a  va  2  s  .com*/
        public boolean hasNext() {
            if (!consumedResult) {
                return hasNext;
            }
            try {
                hasNext = results.next();
                consumedResult = false;
                return hasNext;
            } catch (Exception e) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Unable to check for next result.", e); //$NON-NLS-1$
                }
                return false;
            }
        }

        @Override
        public Object next() {
            consumedResult = true;
            return results.get();
        }

        @Override
        public void remove() {
        }

        @Override
        public void close() throws IOException {
            if (!isClosed) {
                try {
                    results.close();
                } finally {
                    isClosed = true;
                }
            }
        }
    }, selectedFields, callbacks);
}

From source file:com.appeligo.alerts.PendingAlert.java

License:Apache License

@SuppressWarnings("unchecked")
public static PendingAlert getNextAlert() {
    Permissions.checkUser(Permissions.SUPERUSER);
    Session session = getSession();/* w  w w  . ja  v  a2s. c om*/
    Query query = session.getNamedQuery("PendingAlert.getNextAlerts");
    ScrollableResults results = query.scroll();
    results.beforeFirst();
    PendingAlert pendingAlert = null;
    if (results.next()) {
        pendingAlert = (PendingAlert) results.get(0);
    }
    results.close();
    return pendingAlert;
}

From source file:com.aw.core.dao.DAOHbm.java

License:Open Source License

public List listAbortable(SQLQuery sqlQuery) {
    ScrollableResults ss = sqlQuery.scroll(ScrollMode.FORWARD_ONLY);
    AWQueryAbortable queryAbortable = AWQueryAbortable.instance();
    List results = new ArrayList(AWQueryAbortable.DEF_LIST_SIZE);
    queryAbortable.resetRowCount();/*from  w  ww. j a va2 s  .  c  o  m*/
    while (ss.next()) {
        if (queryAbortable.isAborted())
            break;
        results.add(ss.get());
        queryAbortable.incRowCount();
    }
    return results;
}

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

License:Open Source License

/**
 * DOCUMENT ME!//w  ww .  j  a v  a2  s  .c  o m
 *
 * @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!//w  w  w.ja va 2  s .com
 *
 * @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 w  w  w.ja va  2s .  com*/
 *
 * @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.co  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);
    }
}