Example usage for org.hibernate ScrollMode FORWARD_ONLY

List of usage examples for org.hibernate ScrollMode FORWARD_ONLY

Introduction

In this page you can find the example usage for org.hibernate ScrollMode FORWARD_ONLY.

Prototype

ScrollMode FORWARD_ONLY

To view the source code for org.hibernate ScrollMode FORWARD_ONLY.

Click Source Link

Document

Requests a scrollable result that is only scrollable forwards.

Usage

From source file:edu.scripps.fl.pubchem.app.AssayDownloader.java

License:Apache License

public void process() throws Exception {
    if (notInDb) {
        SQLQuery query = PubChemDB.getSession().createSQLQuery("select assay_aid from pcassay");
        ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
        Iterator<Long> iterator = new ScrollableResultsIterator<Long>(Long.class, scroll);
        Set<Long> aids = PubChemFactory.getInstance().getAIDs();
        while (iterator.hasNext())
            aids.remove(iterator.next());
        process(aids);//from w  ww .  j a  v  a 2  s.c  o m
    } else if (this.mlpcn) {
        Set<Long> aids = PubChemFactory.getInstance()
                .getAIDs("\"NIH Molecular Libraries Program\"[SourceCategory] OR \"hasonhold\"[Filter]");
        //         for(long id = 1; id < 1788; id++)
        //            aids.remove(id);
        process(aids);
    } else if (this.days != null)
        process(PubChemFactory.getInstance().getAIDs(this.days));
    else
        process(PubChemFactory.getInstance().getAIDs());
}

From source file:edu.scripps.fl.pubchem.app.CIDDownloader.java

License:Apache License

public static void main(String[] args) throws Exception {
    CIDDownloader fetcher = new CIDDownloader();

    CommandLineHandler clh = new CommandLineHandler() {
        public void configureOptions(Options options) {
            options.addOption(OptionBuilder.withLongOpt("input_file").withType("").withValueSeparator('=')
                    .hasArg().create());
            options.addOption(OptionBuilder.withLongOpt("output_file").withType("").withValueSeparator('=')
                    .hasArg().isRequired().create());
        }/*from  w  w  w  .  j a v a  2s  .  c  o  m*/
    };
    args = clh.handle(args);
    String inputFile = clh.getCommandLine().getOptionValue("input_file");
    String outputFile = clh.getCommandLine().getOptionValue("output_file");

    fetcher.setOutputFile(outputFile);
    Iterator<?> iterator;
    if (null == inputFile) {
        if (args.length == 0) {
            log.info("Running query to find CIDs in PCAssayResult but not in PCCompound");
            SQLQuery query = PubChemDB.getSession().createSQLQuery(
                    "select distinct r.cid from pcassay_result r left join pccompound c on r.cid = c.cid where (r.cid is not null and r.cid > 0 ) and c.cid is null order by r.cid");
            ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
            iterator = new ScrollableResultsIterator<Integer>(Integer.class, scroll);
        } else {
            iterator = Arrays.asList(args).iterator();
        }
    } else if ("-".equals(inputFile)) {
        log.info("Reading CIDs (one per line) from STDIN");
        iterator = new LineIterator(new InputStreamReader(System.in));
    } else {
        log.info("Reading CIDs (one per line) from " + inputFile);
        iterator = new LineIterator(new FileReader(inputFile));
    }
    fetcher.process(iterator);
    System.exit(0);
}

From source file:edu.scripps.fl.pubchem.app.ResultDownloader.java

License:Apache License

protected void process() throws Exception {
    Query query = PubChemDB.getSession().createSQLQuery(
            "select assay_aid from PCAssay where assay_version_changed = 'T' and assay_total_sid_count > 0 order by assay_aid");
    Iterator<Integer> iter = new ScrollableResultsIterator(Integer.class,
            query.scroll(ScrollMode.FORWARD_ONLY));
    process(iter);/*from  w  w  w.j a v a2  s  . c om*/
}

From source file:eu.interedition.text.util.SQL.java

License:Apache License

public static <T> Iterable<T> iterate(final Criteria c, Class<T> type) {
    return new Iterable<T>() {
        @Override/*w ww. j ava 2s.  com*/
        public Iterator<T> iterator() {
            return new AbstractIterator<T>() {

                final ScrollableResults results = c.scroll(ScrollMode.FORWARD_ONLY);

                @Override
                @SuppressWarnings("unchecked")
                protected T computeNext() {
                    return (results.next() ? (T) results.get()[0] : endOfData());
                }
            };
        }
    };
}

From source file:fr.gael.dhus.database.dao.KeyStoreEntryDao.java

License:Open Source License

/**
 * Retrieves entries of a keyStore, oldest first.
 * @param keyStoreName the name of the keyStore
 * @return a ScrollableResult of entries
 *///from  w w w.j a  va 2  s .  c  o m
public ScrollableResults readOldestEntries(final String keyStoreName) {
    return getHibernateTemplate().execute(new HibernateCallback<ScrollableResults>() {
        @Override
        public ScrollableResults doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(entityClass);
            criteria.add(Restrictions.eq("key.keyStore", keyStoreName));
            criteria.addOrder(Order.asc("insertionDate"));
            return criteria.scroll(ScrollMode.FORWARD_ONLY);
        }
    });
}

From source file:fr.mael.microrss.dao.impl.UserArticleDaoImpl.java

License:Open Source License

private void manageResults(Class clazz, FullTextSession searchSession) {
    ScrollableResults results = searchSession.createCriteria(clazz).setFetchMode("article", FetchMode.JOIN)
            .setFetchSize(100).scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
        index++;/*from w  w  w .j  a v  a2  s  .co m*/
        searchSession.index(results.get(0));
        if (index % 100 == 0) {
            searchSession.flushToIndexes();
            searchSession.clear();
        }
    }
    searchSession.flushToIndexes();
    searchSession.clear();

}

From source file:gov.nih.nci.indexgen.Indexer.java

License:BSD License

/**
 * Generates lucene documents//from  w  ww.  j  a  v a  2s.  c  o m
 */
public void run() {

    System.out.println("Started " + entity.getEntityName());

    long start = System.currentTimeMillis();

    try {
        fullTextSession.setFlushMode(FlushMode.MANUAL);
        fullTextSession.setCacheMode(CacheMode.IGNORE);
        Transaction transaction = fullTextSession.beginTransaction();

        // Scrollable results will avoid loading too many objects in memory
        ScrollableResults results = fullTextSession.createQuery("from " + entity.getEntityName())
                .scroll(ScrollMode.FORWARD_ONLY);

        int i = 0;
        while (results.next()) {
            fullTextSession.index(results.get(0));
            if (++i % batchSize == 0)
                fullTextSession.clear();
        }

        transaction.commit();
    }

    finally {
        fullTextSession.close();
    }

    long end = System.currentTimeMillis();
    System.out.println("Completed " + entity.getEntityName() + " in " + (end - start) + " ms");
}

From source file:gr.abiss.calipso.service.impl.UserServiceImpl.java

License:Open Source License

@Override
@Transactional(readOnly = false)// w w w.ja v  a2  s.c  om
public void expireResetPasswordTokens() {
    // get a hibernate session suitable for read-only access to large datasets
    StatelessSession session = ((Session) this.repository.getEntityManager().getDelegate()).getSessionFactory()
            .openStatelessSession();
    Date yesterday = DateUtils.addDays(new Date(), -1);

    // send email notifications for account confirmation tokens that expired
    org.hibernate.Query query = session.createQuery(
            "SELECT new gr.abiss.calipso.model.UserDTO(u.id, u.firstName, u.lastName,u.username, u.email, u.emailHash) FROM User u "
                    + "WHERE u.password IS NULL and u.resetPasswordTokenCreated IS NOT NULL and u.resetPasswordTokenCreated  < :yesterday");
    query.setParameter("yesterday", yesterday);
    query.setFetchSize(Integer.valueOf(1000));
    query.setReadOnly(true);
    query.setLockMode("a", LockMode.NONE);
    ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
    while (results.next()) {
        UserDTO dto = (UserDTO) results.get(0);
        // TODO: send expiration email
        this.emailService.sendAccountConfirmationExpired(new User(dto));
    }
    results.close();
    session.close();

    // expire tokens, including password reset requests
    this.repository.expireResetPasswordTokens(yesterday);
}

From source file:it.jugpadova.blo.EventBo.java

License:Apache License

public void regenerateLuceneIndexes() {
    Session session = this.eventDao.getHibernateTemplate().getSessionFactory().getCurrentSession();
    FullTextSession fullTextSession = Search.createFullTextSession(session);
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    ScrollableResults results = fullTextSession.createCriteria(Event.class).scroll(ScrollMode.FORWARD_ONLY);

    int index = 0;
    while (results.next()) {
        index++;//from   ww  w . j a v a2s  . c om
        fullTextSession.index(results.get(0)); //index each element

        if (index % 50 == 0) {
            fullTextSession.clear(); //clear every batchSize since the queue is processed

        }
    }
}

From source file:jp.go.nict.langrid.dao.hibernate.HibernateOverUseStateDao.java

License:Open Source License

@Override
public OverUseStateSearchResult searchOverUseWithPeriod(int startIndex, int maxCount, String gridId,
        Calendar startDateTime, Calendar endDateTime, Order[] orders, Period period) throws DaoException {
    //## hibernate-postgresql????
    startDateTime = CalendarUtil.toDefaultTimeZone(startDateTime);
    endDateTime = CalendarUtil.toDefaultTimeZone(endDateTime);

    if (orders.length == 0) {
        orders = new Order[] { new Order("lastAccessDateTime", OrderDirection.DESCENDANT) };
    }//from   w w  w.j  a va  2 s  . co m
    for (Order o : orders) {
        if (o.getFieldName().equals("period")) {
            o.setFieldName("ol.period");
        }
    }

    Session session = getSession();
    getContext().beginTransaction();
    try {
        // AccessState
        Query qState = session.createQuery(countClouse + fromAndWhereClouseStateWithPeriod);
        qState.setString("gridId", gridId);
        qState.setCalendar("startDateTime", startDateTime);
        qState.setCalendar("endDateTime", endDateTime);
        qState.setInteger("period", period.ordinal());
        long countState = (Long) qState.uniqueResult();
        qState = session.createQuery(selectClouseState + fromAndWhereClouseStateWithPeriod
                + QueryUtil.buildOrderByQuery(Object.class, "ac", orders));
        qState.setString("gridId", gridId);
        qState.setCalendar("startDateTime", startDateTime);
        qState.setCalendar("endDateTime", endDateTime);
        qState.setInteger("period", period.ordinal());

        List<OverUseState> result = new ArrayList<OverUseState>();
        ScrollableResults iState = qState.scroll(ScrollMode.FORWARD_ONLY);
        for (int i = 0; i < (startIndex + maxCount); i++) {
            OverUseState currentState = getNextOverUseState(iState);
            if (currentState == null) {
                break;
            }
            if (startIndex <= i)
                result.add(currentState);
        }
        OverUseStateSearchResult r = new OverUseStateSearchResult(result.toArray(new OverUseState[] {}),
                (int) (countState), true);
        getContext().commitTransaction();
        return r;
    } catch (HibernateException e) {
        getContext().rollbackTransaction();
        logAdditionalInfo(e);
        throw new DaoException(e);
    } catch (RuntimeException e) {
        getContext().rollbackTransaction();
        throw new DaoException(e);
    } catch (Error e) {
        getContext().rollbackTransaction();
        throw new DaoException(e);
    }
}