Example usage for org.hibernate ScrollableResults scroll

List of usage examples for org.hibernate ScrollableResults scroll

Introduction

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

Prototype

boolean scroll(int positions);

Source Link

Document

Scroll the specified number of positions from the current position.

Usage

From source file:com.farmafene.commons.hibernate.HBPaginaFactory.java

License:Open Source License

/**
 * Metodo factora/*from w  w  w .j a  va 2 s  . c om*/
 * 
 * @param begin
 *            primer registro
 * @param size
 *            tamao pgina
 * @param result
 *            dnde buscar
 * @return pgina generada
 * @since 1.0.0
 */
public HBPagina<T> getPagina(int begin, int size, ScrollableResults result) {
    HBPaginaImp lista = new HBPaginaImp();
    if (lista.getFirst() < 1) {
        lista.setFirst(1);
    }
    if (lista.getPageSize() < 0) {
        lista.setPageSize(0);
    }
    result.beforeFirst();
    result.scroll(lista.getFirst() - 1);
    for (int i = 0; result.next() && (lista.getPageSize() == 0 || i < lista.getPageSize()); i++) {
        T obj = handler.makeObject(result.get());
        if (obj != null) {
            lista.getLista().add(obj);
        }
    }
    if (result.last()) {
        lista.setTotalSize(result.getRowNumber() + 1);
    } else {
        lista.setTotalSize(0);
        lista.setFirst(0);
    }
    return lista;
}

From source file:com.ibm.asset.trails.dao.jpa.VSoftwareLparDAOJpa.java

public void paginatedList(DisplayTagList data, Account account, ReconSetting reconSetting, int startIndex,
        int objectsPerPage, String sort, String dir) {
    Criteria criteria = getHibernateSessionCriteria();

    criteria.createAlias("hardwareLpar", "hl")
            .createAlias("hl.hardwareLparEff", "hle", CriteriaSpecification.LEFT_JOIN)
            .createAlias("hl.hardware", "h").createAlias("h.machineType", "mt")
            .createAlias("installedSoftwares", "is")
            .createAlias("is.scheduleF", "sf", CriteriaSpecification.LEFT_JOIN)
            .createAlias("sf.scope", "scope", CriteriaSpecification.LEFT_JOIN)
            .createAlias("is.softwareLpar", "sl").createAlias("is.alert", "aus")
            .createAlias("aus.reconcile", "r", CriteriaSpecification.LEFT_JOIN)
            .createAlias("r.usedLicenses", "ul", CriteriaSpecification.LEFT_JOIN)
            .createAlias("ul.license", "license", CriteriaSpecification.LEFT_JOIN)
            .createAlias("r.reconcileType", "rt", CriteriaSpecification.LEFT_JOIN)
            .createAlias("is.software", "sw")
            .createAlias("sw.manufacturer", "mf", CriteriaSpecification.LEFT_JOIN)
            .add(Restrictions.eq("account", account));

    if (reconSetting.getReconcileType() != null) {
        criteria.add(Restrictions.eq("rt.id", reconSetting.getReconcileType()));
    }//from w w  w  .java2  s.  com

    if (StringUtils.isNotBlank(reconSetting.getAlertStatus())) {
        boolean open = false;
        if (reconSetting.getAlertStatus().equals("OPEN")) {
            open = true;
            criteria.add(Restrictions.eq("aus.open", open));
        } else {
            criteria.add(Restrictions.and(Restrictions.eq("aus.open", false),
                    Restrictions.eqProperty("is.id", "r.installedSoftware.id")));
        }

    } else {
        criteria.add(Restrictions.or(Restrictions.eq("aus.open", true),
                Restrictions.and(Restrictions.eq("aus.open", false),
                        Restrictions.eqProperty("is.id", "r.installedSoftware.id"))));
    }

    if (null != reconSetting.getAlertFrom() && reconSetting.getAlertFrom().intValue() >= 0) {
        criteria.add(Restrictions.ge("aus.alertAge", reconSetting.getAlertFrom()));
    }
    if (null != reconSetting.getAlertTo() && reconSetting.getAlertTo().intValue() >= 0) {
        criteria.add(Restrictions.le("aus.alertAge", reconSetting.getAlertTo()));
    }

    if (StringUtils.isNotBlank(reconSetting.getAssigned())) {
        if (reconSetting.getAssigned().equals("Assigned")) {
            criteria.add(Restrictions.ne("aus.remoteUser", "STAGING"));
        }
        if (reconSetting.getAssigned().equals("Unassigned")) {
            criteria.add(Restrictions.eq("aus.remoteUser", "STAGING"));
        }
    }

    if (StringUtils.isNotBlank(reconSetting.getAssignee())) {
        criteria.add(Restrictions.eq("aus.remoteUser", reconSetting.getAssignee()).ignoreCase());
    }

    if (StringUtils.isNotBlank(reconSetting.getOwner())) {
        if (reconSetting.getOwner().equalsIgnoreCase("IBM")) {
            criteria.add(Restrictions.eq("h.owner", reconSetting.getOwner()).ignoreCase());
        } else if (reconSetting.getOwner().equalsIgnoreCase("Customer")) {
            ArrayList<String> lalOwner = new ArrayList<String>();

            lalOwner.add("CUST");
            lalOwner.add("CUSTO");
            criteria.add(Restrictions.in("h.owner", lalOwner));
        }
    }

    // I'm not sure why the heck we aren't just getting a list of strings?
    if (reconSetting.getCountries().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getCountries().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getCountries()[i])) {
                list.add(reconSetting.getCountries()[i].toUpperCase());
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("h.country", list));
        }
    }

    if (reconSetting.getNames().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getNames().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getNames()[i])) {
                list.add(reconSetting.getNames()[i].toUpperCase());
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("hl.name", list));
        }
    }

    if (reconSetting.getSwcmIDs().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getSwcmIDs().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getSwcmIDs()[i])) {
                list.add(reconSetting.getSwcmIDs()[i].toUpperCase());
            }
        }
        if (list.size() > 0) {
            criteria.add(Restrictions.in("license.extSrcId", list));
        }
    }

    if (reconSetting.getSerialNumbers().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getSerialNumbers().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getSerialNumbers()[i])) {
                list.add(reconSetting.getSerialNumbers()[i].toUpperCase());
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("h.serial", list));
        }
    }

    if (reconSetting.getProductInfoNames().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getProductInfoNames().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getProductInfoNames()[i])) {
                list.add(reconSetting.getProductInfoNames()[i]);
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("sw.softwareName", list));
        }
    }

    if (StringUtils.isNotBlank(reconSetting.getScope())) {
        if ("Not specified".equalsIgnoreCase(reconSetting.getScope())) {
            criteria.add(Restrictions.isNull("scope.description"));
        } else {
            criteria.add(Restrictions.eq("scope.description", reconSetting.getScope()));
        }
    }

    if (StringUtils.isNotBlank(reconSetting.getFinanResp())) {
        if ("Not Specified".trim().equalsIgnoreCase(reconSetting.getFinanResp())) {
            criteria.add(Restrictions.isNull("sf.SWFinanceResp"));
        } else {
            criteria.add(Restrictions.eq("sf.SWFinanceResp", reconSetting.getFinanResp()));
        }
    }

    criteria.setProjection(Projections.projectionList().add(Projections.property("aus.id").as("alertId"))
            .add(Projections.property("r.id").as("reconcileId"))
            .add(Projections.property("aus.alertAge").as("alertAgeI"))
            .add(Projections.property("is.id").as("installedSoftwareId"))
            .add(Projections.property("hl.name").as("hostname"))
            .add(Projections.property("sl.name").as("sl_hostname"))
            .add(Projections.property("hl.spla").as("spla"))
            .add(Projections.property("hl.sysplex").as("sysplex"))
            .add(Projections.property("hl.internetIccFlag").as("internetIccFlag"))
            .add(Projections.property("h.serial").as("serial"))
            .add(Projections.property("h.country").as("country"))
            .add(Projections.property("h.owner").as("owner"))
            .add(Projections.property("h.mastProcessorType").as("mastProcessorType"))
            .add(Projections.property("h.processorManufacturer").as("processorManufacturer"))
            .add(Projections.property("h.mastProcessorModel").as("mastProcessorModel"))
            .add(Projections.property("h.nbrCoresPerChip").as("nbrCoresPerChip"))
            .add(Projections.property("h.nbrOfChipsMax").as("nbrOfChipsMax"))
            .add(Projections.property("h.cpuLsprMips").as("cpuLsprMips"))
            .add(Projections.property("h.cpuIfl").as("cpuIFL"))
            .add(Projections.property("hl.partLsprMips").as("partLsprMips"))
            .add(Projections.property("h.cpuGartnerMips").as("cpuGartnerMips"))
            .add(Projections.property("hl.partGartnerMips").as("partGartnerMips"))
            .add(Projections.property("hl.effectiveThreads").as("effectiveThreads"))
            .add(Projections.property("hl.vcpu").as("vcpu")).add(Projections.property("h.cpuMsu").as("cpuMsu"))
            .add(Projections.property("hl.partMsu").as("partMsu"))
            .add(Projections.property("hl.serverType").as("lparServerType"))
            .add(Projections.property("h.shared").as("shared"))
            .add(Projections.property("h.multi_tenant").as("multi_tenant"))
            .add(Projections.property("mt.type").as("assetType"))
            .add(Projections.property("mt.name").as("assetName"))
            .add(Projections.property("h.hardwareStatus").as("hardwareStatus"))
            .add(Projections.property("hl.lparStatus").as("lparStatus"))
            .add(Projections.property("processorCount").as("processorCount"))
            .add(Projections.property("sw.softwareName").as("productInfoName"))
            .add(Projections.property("sw.softwareId").as("productInfoId"))
            .add(Projections.property("sw.pid").as("pid"))
            .add(Projections.property("mf.manufacturerName").as("manufacturerName"))
            .add(Projections.property("rt.name").as("reconcileTypeName"))
            .add(Projections.property("rt.id").as("reconcileTypeId"))
            .add(Projections.property("aus.remoteUser").as("assignee"))
            .add(Projections.property("h.processorCount").as("hardwareProcessorCount"))
            .add(Projections.property("hle.processorCount").as("hwLparEffProcessorCount"))
            .add(Projections.property("hl.osType").as("osType"))
            .add(Projections.property("hle.status").as("hwLparEffProcessorStatus"))
            .add(Projections.property("h.chips").as("chips")));
    criteria.setResultTransformer(new AliasToBeanResultTransformer(ReconWorkspace.class));

    criteria.addOrder(Order.desc("aus.open"));

    if (dir.equalsIgnoreCase("ASC")) {
        criteria.addOrder(Order.asc(sort));
    } else {
        criteria.addOrder(Order.desc(sort));
    }

    ArrayList<ReconWorkspace> list = new ArrayList<ReconWorkspace>();

    ScrollableResults itemCursor = criteria.scroll();
    itemCursor.beforeFirst();
    if (itemCursor.next()) {
        itemCursor.scroll(startIndex);
        int i = 0;

        while (objectsPerPage > i++) {
            ReconWorkspace rw = (ReconWorkspace) itemCursor.get(0);
            if (null != rw.getHwLparEffProcessorStatus()
                    && rw.getHwLparEffProcessorStatus().equalsIgnoreCase("INACTIVE")) {
                rw.setHwLparEffProcessorCount(0);
            }
            list.add(rw);
            if (!itemCursor.next())
                break;
        }

        data.setList(list);
        itemCursor.last();
        data.setFullListSize(itemCursor.getRowNumber() + 1);
        itemCursor.close();

        addSchedulef2List(account, data.getList());
    } else {
        data.setList(null);
        data.setFullListSize(0);
        itemCursor.close();
    }

}

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 ww w.  j a  v  a 2s  .  c  o  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  ww.j av a2s. c  om*/

    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");
                }/*from   w w w .  ja v  a 2 s  .  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:net.chrisrichardson.foodToGo.domain.hibernate.HibernateOrderRepositoryImpl.java

License:Apache License

private List getOrdersFromScrollableResults(ScrollableResults results1) {
    List orders = new ArrayList();
    int pageSize = 10;
    if (results1.first() && results1.scroll(0)) {
        for (int i = 0; i < pageSize; i++) {
            orders.add(results1.get(0));
            if (!results1.next())
                break;
        }/*from   w w w. j av  a  2 s.co  m*/
    }

    List results = orders;
    return results;
}

From source file:net.mlw.vlh.adapter.hibernate3.HibernateAdapter.java

License:Open Source License

/**
 * @see net.mlw.vlh.ValueListAdapter#getValueList(java.lang.String,
 *      net.mlw.vlh.ValueListInfo)//from   w  w w .  ja v  a  2s  .  c  om
 */
public ValueList getValueList(String name, ValueListInfo info) {

    LOGGER.debug("getValueList(String, ValueListInfo) - start");

    if (info.getSortingColumn() == null) {
        info.setPrimarySortColumn(getDefaultSortColumn());
        info.setPrimarySortDirection(getDefaultSortDirectionInteger());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The default sort column '" + getDefaultSortColumn() + "' with direction '"
                    + getDefaultSortDirectionInteger() + "' was  set.");
        }
    }

    int numberPerPage = info.getPagingNumberPer();

    if (numberPerPage == Integer.MAX_VALUE) {
        numberPerPage = getDefaultNumberPerPage();
        info.setPagingNumberPer(numberPerPage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The paging number per page '" + numberPerPage + "' was  set.");
        }
    }

    Session session = SessionFactoryUtils.getSession(getSessionFactory(), allowCreate);
    try {
        Query query;

        boolean doFocus = ((getAdapterType() & DO_FOCUS) == 0) && info.isFocusEnabled() && info.isDoFocus()
                && (namedQuery == null);

        if (doFocus) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Start to focusing adapterName '" + name + "', ValueListInfo info = " + info + "'");
            }
            ScrollableResults results = getScrollableResults(getQueryForFocus(info, session), info);
            results.beforeFirst();
            doFocusFor(info, results);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Focusing finished for adapterName '" + name + "', ValueListInfo info '" + info + "'");
            }
        }

        query = getQuery(info, session);

        boolean doPaging = ((getAdapterType() & DO_PAGE) == 0);

        List list;

        if (doPaging) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("getValueList(String adapterName = " + name + ", ValueListInfo info = " + info
                        + ") - Start to paging result set");
            }

            list = new ArrayList(numberPerPage);
            ScrollableResults results = getScrollableResults(query, info);

            results.last();
            int lastRowNumber = results.getRowNumber();
            info.setTotalNumberOfEntries(lastRowNumber + 1);

            if (numberPerPage == 0) {
                numberPerPage = getDefaultNumberPerPage();
            }

            int pageNumber = info.getPagingPage();
            boolean isResult;
            if (pageNumber > 1) {
                if ((pageNumber - 1) * numberPerPage > lastRowNumber) {
                    pageNumber = (lastRowNumber / numberPerPage) + 1;
                    info.setPagingPage(pageNumber);
                }
            }
            // fixed by liujuan 2008.6.5
            isResult = results.first();

            if (pageNumber > 1) {
                // isResult = results.scroll((pageNumber - 1) * numberPerPage - lastRowNumber);
                isResult = results.scroll((pageNumber - 1) * numberPerPage);
            }
            /*else
            {
               isResult = results.first();
            }*/

            for (int i = 0; i < numberPerPage && isResult; i++) {
                list.add(results.get(0));
                isResult = results.next();
            }

            LOGGER.debug("Sorting finished.");

        } else {

            LOGGER.debug("Retrieving a list directly from the query.");

            list = query.list();
            info.setTotalNumberOfEntries(list.size());
        }

        ValueList returnValueList = getListBackedValueList(info, list);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Retrieved list was wrapped in valuelist, info=" + info);
        }
        return returnValueList;
    } catch (HibernateException e) {
        LOGGER.error("Error getting data in adapater '" + name + "' with info = '" + info + "'", e);
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    } catch (Exception e) {
        LOGGER.fatal("Fatal error getting data in adapater '" + name + "' with info = '" + info + "'", e);
        return null;
    } finally {
        SessionFactoryUtils.releaseSession(session, getSessionFactory());
    }
}

From source file:org.gbif.portal.dao.occurrence.OccurrenceAssociationTraverser.java

License:Open Source License

/**
 * @see org.gbif.portal.dao.AssociationTraverser#batchPreprocess(int, org.hibernate.ScrollableResults, org.hibernate.Session)
 *///from  ww w. j av  a2s .  c  o  m
public void batchPreprocess(int batchSize, ScrollableResults scrollableResults, Session session) {

    if (!retrieveIdentifiers)
        return;

    if (logger.isDebugEnabled())
        logger.debug("Current row number:" + scrollableResults.getRowNumber());

    List<Long> occurrenceRecordIds = new ArrayList<Long>();

    boolean eor = false;
    int numberScrolled = 0;

    for (numberScrolled = 0; numberScrolled < batchSize - 1 && !eor; numberScrolled++) {
        //retrieve the id
        Long recordId = (Long) scrollableResults.get(0);
        occurrenceRecordIds.add(recordId);

        if (scrollableResults.isLast()) {
            eor = true;
            numberScrolled--;
        } else {
            scrollableResults.next();
        }
    }
    scrollableResults.scroll(-numberScrolled);

    if (logger.isDebugEnabled()) {
        logger.debug("Number scrolled through: " + numberScrolled);
        logger.debug("Scrolled back to: " + scrollableResults.getRowNumber());
    }

    //retrieve image records for this batch - and process into Map - 
    List<ORImage> orImageList = imageRecordDAO.getImageRecordsForOccurrenceRecords(occurrenceRecordIds);
    this.orImageUrlMap = new HashMap<Long, String>();
    for (ORImage orImage : orImageList) {
        //only storing the first image url we find         
        if (this.orImageUrlMap.get(orImage.getOccurrenceRecordId()) == null) {
            this.orImageUrlMap.put(orImage.getOccurrenceRecordId(), orImage.getUrl());
        }
        session.evict(orImage);
    }
    if (logger.isDebugEnabled())
        logger.debug("Number of images found for batch: " + this.orImageUrlMap.size());

    //retrieve type status for this batch      
    List<TypeStatus> typeStatusList = typificationRecordDAO
            .getTypeStatusForOccurrenceRecords(occurrenceRecordIds);
    this.typeStatusMap = new HashMap<Long, String>();
    for (TypeStatus typeStatus : typeStatusList) {
        //only storing the first type status we find
        if (this.typeStatusMap.get(typeStatus.getOccurrenceRecordId()) == null) {
            this.typeStatusMap.put(typeStatus.getOccurrenceRecordId(), typeStatus.getTypeStatus());
        }
        session.evict(typeStatus);
    }
    if (logger.isDebugEnabled())
        logger.debug("Number of type status found for batch: " + this.typeStatusMap.size());

    //retrieve identifiers for this batch      
    List<IdentifierRecord> identifierList = identifierRecordDAO
            .getIdentifierRecordsForOccurrenceRecords(occurrenceRecordIds);
    this.identifiersMap = new HashMap<Long, List<IdentifierRecord>>();
    for (IdentifierRecord ir : identifierList) {
        List<IdentifierRecord> irs = this.identifiersMap.get(ir.getOccurrenceRecordId());
        if (irs == null) {
            irs = new ArrayList<IdentifierRecord>();
            irs.add(ir);
            this.identifiersMap.put(ir.getOccurrenceRecordId(), irs);
        } else {
            irs.add(ir);
        }
        session.evict(ir);
    }
    if (logger.isDebugEnabled())
        logger.debug("Number of identifiers found for batch: " + this.identifiersMap.size());

}

From source file:uit.qabpss.util.dao.orm.hibernate.QueryUtil.java

License:Open Source License

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

    if ((total == 0) || (num == 0)) {
        return new ArrayList<Object>();
    }/*  w w w .  j a  va2 s .c  o  m*/

    if (num >= total) {
        return list(query, 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:vnpt.media.efinder.model.PaginationResult.java

public PaginationResult(Query query, int page, int maxResult, int maxNavigationPage) {
    final int pageIndex = page - 1 < 0 ? 0 : page - 1;
    int fromRecordIndex = pageIndex * maxResult;
    int maxRecordIndex = fromRecordIndex + maxResult;

    ScrollableResults resultScroll = query.scroll(ScrollMode.SCROLL_INSENSITIVE);

    //resultScroll.g
    List results = new ArrayList<>();
    boolean hasResult = resultScroll.first();
    if (hasResult) {
        // Cuon toi vi tri
        hasResult = resultScroll.scroll(fromRecordIndex);
        if (hasResult) {
            do {/* w  w  w  .  jav a 2 s. c o  m*/
                E record = (E) resultScroll.get(0);
                results.add(record);
            } while (resultScroll.next()//
                    && resultScroll.getRowNumber() >= fromRecordIndex
                    && resultScroll.getRowNumber() < maxRecordIndex);
        }

        // chuyen toi ban ghi cuoi
        resultScroll.last();
    }

    // Tong so ban ghi
    this.totalRecords = resultScroll.getRowNumber() + 1;
    this.currentPage = pageIndex + 1;
    this.list = results;
    this.maxResult = maxResult;
    this.totalPages = (this.totalRecords / this.maxResult);
    if (totalRecords % this.maxResult != 0) {
        this.totalPages = this.totalPages + 1;
    }
    this.maxNavigationPage = totalPages;

    if (maxNavigationPage < totalPages) {
        this.maxNavigationPage = maxNavigationPage;
    }

    this.calcNavigationPages();

}