Example usage for org.hibernate ScrollableResults get

List of usage examples for org.hibernate ScrollableResults get

Introduction

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

Prototype

Object get(int i);

Source Link

Document

Get the ith object in the current row of results, without initializing any other results in the row.

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   w w  w . j a  v a  2s  .c  om
        }
    }
    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   ww w  .j a va 2s.  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:com.appeligo.alerts.PendingAlert.java

License:Apache License

@SuppressWarnings("unchecked")
public static PendingAlert getNextAlert() {
    Permissions.checkUser(Permissions.SUPERUSER);
    Session session = getSession();//  w  ww.ja va  2s . c o  m
    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.duroty.application.admin.manager.AdminManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*ww w. jav a  2s  . 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!/*ww  w  .  j a v a 2  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!/*  ww  w.  j a v  a  2  s .  c  o  m*/
 *
 * @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!//from  ww w  . ja  va2 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!/*w  w w  . ja v a  2 s. c  o  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!//  www  . j av  a 2 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!/*from  ww  w .  ja  v  a  2s .com*/
 *
 * @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);
    }
}