Example usage for org.hibernate ScrollableResults close

List of usage examples for org.hibernate ScrollableResults close

Introduction

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

Prototype

void close();

Source Link

Document

Release resources immediately.

Usage

From source file:com.ibm.asset.trails.service.impl.ReportServiceImpl.java

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getSoftwareVarianceReport(Account pAccount, String remoteUser, String lsName,
        PrintWriter pPrintWriter) throws HibernateException, Exception {
    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT S.Software_Name, COUNT(IS.Software_Id), CAST(NULL AS VARCHAR(256)) FROM EAADMIN.Software S, EAADMIN.Installed_Software IS, EAADMIN.Software_Lpar SL WHERE S.Software_Id = IS.Software_Id AND S.Status = 'ACTIVE' AND S.Level = 'LICENSABLE' AND IS.Discrepancy_Type_Id IN (1, 2, 4) AND IS.Status = 'ACTIVE' AND IS.Software_Lpar_Id = SL.Id AND NOT EXISTS (SELECT SF.Software_Id FROM EAADMIN.Schedule_F SF, EAADMIN.Status S2 WHERE SF.Customer_Id = :customerId AND SF.Software_Name = S.Software_Name AND S2.Id = SF.Status_Id AND S2.Description = 'ACTIVE') AND SL.Customer_Id = :customerId GROUP BY S.Software_Name UNION SELECT SF.Software_Name, CAST(0 AS INTEGER), SF.Software_Title FROM EAADMIN.Schedule_F SF, EAADMIN.Status S2 WHERE SF.Customer_Id = :customerId AND S2.Id = SF.Status_Id AND S2.Description = 'ACTIVE' AND NOT EXISTS (SELECT S3.Software_Id FROM EAADMIN.Software S3, EAADMIN.Installed_Software IS, EAADMIN.Software_Lpar SL WHERE S3.Software_Name = SF.Software_Name AND S3.Software_Id = IS.Software_Id AND S3.Status = 'ACTIVE' AND S3.Level = 'LICENSABLE' AND IS.Discrepancy_Type_Id IN (1, 2, 4) AND IS.Status = 'ACTIVE' AND IS.Software_Lpar_Id = SL.Id AND SL.Customer_Id = :customerId) ORDER BY Software_Name")
            .setLong("customerId", pAccount.getId()).scroll(ScrollMode.FORWARD_ONLY);

    printHeader(SOFTWARE_VARIANCE_REPORT_NAME, null, SOFTWARE_VARIANCE_REPORT_COLUMN_HEADERS, pPrintWriter);
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }//w  ww  .j a v  a  2 s . co m
    lsrReport.close();
}

From source file:com.ibm.asset.trails.service.impl.ReportServiceImpl.java

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getWorkstationAccountsReport(String remoteUser, String lsName, PrintWriter pPrintWriter)
        throws HibernateException, Exception {
    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT C.Account_Number, C.Customer_Name, CT.Customer_Type_Name, G.Name AS G_Name, R.Name AS R_Name, CC.Name AS CC_Name, S.Sector_Name, COUNT(H.Id), H.Hardware_Status FROM EAADMIN.Customer C, EAADMIN.Customer_Type CT, EAADMIN.Country_Code CC, EAADMIN.Region R, EAADMIN.Geography G, EAADMIN.Sector S, EAADMIN.Hardware H, EAADMIN.Machine_Type MT WHERE C.Status = 'ACTIVE' AND C.Customer_Type_Id = CT.Customer_Type_Id AND CT.Customer_Type_Name LIKE '%WORKSTATION%' AND G.Id = R.Geography_Id AND R.Id = CC.Region_Id AND CC.Id = C.Country_Code_Id AND S.Sector_Id = C.Sector_Id AND H.Customer_Id = C.Customer_Id AND H.Status = 'ACTIVE' AND MT.Id = H.Machine_Type_Id AND MT.Type != 'WORKSTATION' GROUP BY C.Account_Number, C.Customer_Name, CT.Customer_Type_Name, G.Name, R.Name, CC.Name, S.Sector_Name, H.Hardware_Status ORDER BY C.Account_Number, H.Hardware_Status")
            .scroll(ScrollMode.FORWARD_ONLY);

    printHeader(WORKSTATION_ACCOUNTS_REPORT_NAME, null, WORKSTATION_ACCOUNTS_REPORT_COLUMN_HEADERS,
            pPrintWriter);/*from   w  w w  .j  a va  2s .  c o  m*/
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }
    lsrReport.close();
}

From source file:com.ibm.asset.trails.service.impl.ReportServiceImpl.java

License:Open Source License

@Override
@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getPriorityISVSWReport(PrintWriter pPrintWriter) {
    printHeader(PRIORITY_ISV_SW_REPORT_NAME, null, PRIORITY_ISV_SW_REPORT_COLUMN_HEADERS, pPrintWriter);
    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT mf.NAME, isv.LEVEL, case when isv.LEVEL = 'GLOBAL' then 'ALL' else cus.CUSTOMER_NAME end as CUSTOMER_NAME, cus.ACCOUNT_NUMBER, isv.EVIDENCE_LOCATION, st.DESCRIPTION, isv.BUSINESS_JUSTIFICATION,isv.REMOTE_USER, isv.RECORD_TIME from EAADMIN.PRIORITY_ISV_SW isv inner join EAADMIN.MANUFACTURER mf on isv.MANUFACTURER_ID = mf.ID inner join EAADMIN.STATUS st on isv.STATUS_ID = st.ID left outer join EAADMIN.CUSTOMER cus on isv.CUSTOMER_ID = cus.CUSTOMER_ID")
            .scroll(ScrollMode.FORWARD_ONLY);
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }//  w  w  w  . j av a2s.  com

    lsrReport.close();
}

From source file:com.ibm.asset.trails.service.impl.ReportServiceImpl.java

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getScheduleFReport(Account account, PrintWriter pPrintWriter) {
    StringBuffer sql = new StringBuffer();
    sql.append(/*from ww w .ja  va2  s  . c o m*/
            "select sf.Level,sf.hw_Owner,sf.hostname,sf.serial,sf.Machine_Type, c.account_number,sf.software_title,sf.software_name,sf.manufacturer,sc.description as Scope,sf.sw_financial_resp,so.description as Source,sf.source_location,st.description as Status,sf.business_justification")
            .append(" from eaadmin.schedule_f sf,eaadmin.scope sc, eaadmin.status st,eaadmin.source so,eaadmin.customer c ")
            .append(" where sc.id=sf.scope_id and st.id=sf.status_id and so.id=sf.source_id and c.customer_id=sf.customer_id and")
            .append(" c.customer_id=").append(account.getId());

    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(sql.toString())
            .scroll(ScrollMode.FORWARD_ONLY);

    pPrintWriter.println(outputData(SCHEDULE_F_REPORT_COLUMN_HEADERS));
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }

    lsrReport.close();
}

From source file:com.ibm.asset.trails.service.impl.ReportServiceImpl.java

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getNonInstanceBasedSWReport(PrintWriter pPrintWriter) {
    // TODO Auto-generated method stub
    printHeader(NON_INSTANCE_REPORT_NAME, null, NON_INSTANCE_REPORT_COLUMN_HEADERS, pPrintWriter);
    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT sw.SOFTWARE_NAME, mf.NAME, non.RESTRICTION, ct.DESCRIPTION as ctDesc, CASE non.BASE_ONLY WHEN 1 THEN 'Y' ELSE 'N' END, st.DESCRIPTION as stDesc, non.REMOTE_USER, non.RECORD_TIME FROM EAADMIN.NON_INSTANCE non, EAADMIN.SOFTWARE sw, EAADMIN.MANUFACTURER mf, EAADMIN.CAPACITY_TYPE ct, EAADMIN.STATUS st WHERE non.SOFTWARE_ID = sw.SOFTWARE_ID AND non.MANUFACTURER_ID = mf.ID AND non.CAPACITY_TYPE_CODE = ct.CODE AND non.STATUS_ID = st.ID")
            .scroll(ScrollMode.FORWARD_ONLY);
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }// ww w .ja  v  a 2s.  c o m

    lsrReport.close();
}

From source file:com.ikon.module.db.stuff.IndexHelper.java

License:Open Source License

protected int doRebuildIndex() throws Exception {
    FullTextSession fullTextSession = (FullTextSession) entityManager.getDelegate();
    fullTextSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
    fullTextSession.setCacheMode(org.hibernate.CacheMode.IGNORE);
    fullTextSession.purgeAll(NodeDocumentVersion.class);
    fullTextSession.getSearchFactory().optimize(NodeDocumentVersion.class);

    String query = "select ndv from NodeDocumentVersion ndv";
    ScrollableResults cursor = fullTextSession.createQuery(query).scroll();
    cursor.last();//from   w  w w.j  a v a 2  s  .co  m
    int count = cursor.getRowNumber() + 1;
    log.warn("Re-building Wine index for " + count + " objects.");

    if (count > 0) {
        int batchSize = 300;
        cursor.first(); // Reset to first result row
        int i = 0;

        while (true) {
            fullTextSession.index(cursor.get(0));

            if (++i % batchSize == 0) {
                fullTextSession.flushToIndexes();
                fullTextSession.clear(); // Clear persistence context for each batch
                log.info("Flushed index update " + i + " from Thread " + Thread.currentThread().getName());
            }

            if (cursor.isLast()) {
                break;
            }

            cursor.next();
        }
    }

    cursor.close();
    fullTextSession.flushToIndexes();
    fullTextSession.clear(); // Clear persistence context for each batch
    fullTextSession.getSearchFactory().optimize(NodeDocumentVersion.class);

    return count;
}

From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelExecutorTask.java

License:Apache License

private double[] eval(final Model model, final Timestamp topOfPeriod, final Timestamp endOfPeriod,
        final MaxentModel maxentModel) {

    final ScrollableResults scrollableResults = this.documentDao.scrollableSearch(model.getUserId(), null,
            model.getTopic().getSearchExpression(), SortOrder.DATE_ASC, topOfPeriod, endOfPeriod);

    // initialize with an estimated size to prevent a lot of resizing
    final Map<String, Integer> contextMap = new LinkedHashMap<String, Integer>(64 * 1024);

    try {//from  w w  w. j  av  a 2 s  .co m
        while (scrollableResults.next()) {
            final Object[] row = scrollableResults.get();
            final Document document = (Document) row[0];

            if (document == null) {
                // caused by stale index
                continue;
            } else {
                OpenNLPMaxentContextBuilder.append(contextMap, document);
            }
        }
    } finally {
        scrollableResults.close();
    }

    final String[] context = new String[contextMap.size()];
    final float[] values = new float[contextMap.size()];

    // copy map to arrays
    OpenNLPMaxentContextBuilder.buildContextArrays(contextMap, context, values);

    // eval
    return maxentModel.eval(context, values);
}

From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelTrainerTask.java

License:Apache License

@Override
public void train(Model model) {
    final int lookahead = model.getLookahead();
    final TimeUnits timeUnits = model.getTimeUnits();
    final long durationOfUnit = timeUnits.getDuration();

    final Date startDate = TimeUnits.floor(model.getStartDate(), timeUnits);
    final Date endDate = TimeUnits.ceil(model.getEndDate(), timeUnits);

    final Timestamp startDatePoints = new Timestamp(startDate.getTime() - durationOfUnit);
    final Timestamp endDatePoints = new Timestamp(endDate.getTime() + (lookahead * durationOfUnit));

    List<DataSetPoint> points = this.dataSetPointDao.findAndAggregatePointsGroupedByUnit(
            model.getTrainingDataSet(), startDatePoints, endDatePoints, timeUnits);
    Map<Date, DataSetPoint> pointMap = toMap(points);

    final Map<Date, Float> percentChangeMap = calculatePercentChange(points, pointMap);

    // should release these collections once percent change is calculated
    points = null;/*www . j a  va2  s  . c om*/
    pointMap = null;

    final HibernateEntityManager hem = this.em.unwrap(HibernateEntityManager.class);
    final Session session = hem.getSession();

    final Long userId = model.getUserId();
    final DocumentState state = null;
    final String queryString = model.getTopic().getSearchExpression();
    final ScrollableResults scrollableResults = this.documentDao.scrollableSearch(userId, state, queryString,
            SortOrder.DATE_ASC, startDatePoints, endDatePoints);

    try {
        final EventStream eventStream = new DocumentScoreEventStream(model, scrollableResults, session,
                percentChangeMap);
        final DataIndexer dataIndexer = new TwoPassDataIndexer(eventStream, this.cutoff);

        if (!logger.isDebugEnabled()) {
            GIS.PRINT_MESSAGES = false;
        }

        logger.debug("Invoking GIS.trainModel");
        final GISModel gisModel = GIS.trainModel(this.iterations, dataIndexer);
        logger.debug("GIS.trainModel complete");

        // because we've been clearing the entity manager's session
        model = this.modelDao.get(model.getId());
        writeModelToFile(model, gisModel);
        logger.info("Created model: " + gisModel);
        model.onTrainingComplete();

    } catch (final OutOfMemoryError e) {
        logError(model.getId(), e);
        throw e;
    } catch (final Exception e) {
        logError(model.getId(), e);
    } finally {
        scrollableResults.close();
    }
}

From source file:com.mothsoft.alexis.engine.textual.TopicDocumentMatcherImpl.java

License:Apache License

private void mapMatches(final Topic topic, final Map<Long, List<TopicScore>> documentTopicMap) {
    final String query = topic.getSearchExpression();

    final ScrollableResults scrollableResults = this.documentDao.scrollableSearch(topic.getUserId(),
            DocumentState.PENDING_TOPIC_MATCHING, query, SortOrder.DATE_ASC, null, null);

    try {//from  w w  w .j a  v a2  s . c o m
        while (scrollableResults.next()) {
            final Object[] array = scrollableResults.get();

            // allow for state document index
            if (array[0] == null) {
                continue;
            }

            final DocumentScore documentScore = new DocumentScore((Document) array[0], (Float) array[1]);
            mapMatches(topic, documentScore, documentTopicMap);
        }
    } finally {
        scrollableResults.close();
    }
}

From source file:com.multimedia.service.wallpaper.WallpaperServiceImpl.java

License:Apache License

@Override
public Map<String, Double> getTags(int maxTags) {
    ScrollableResults wallpaper_tags = dao.getScrollableResults("tags", "active", Boolean.TRUE, null, null);
    Map<String, Double> tags = new HashMap<String, Double>();
    if (wallpaper_tags.first()) {
        String tag;//w  ww . j  a v  a2 s.c  om
        Double score;
        String[] tags_parsed;
        String tag_parsed;
        do {
            tag = wallpaper_tags.getString(0);
            if (tag != null) {
                tags_parsed = tag.split(",");
                for (int i = 1; i < tags_parsed.length; i++) {
                    tag_parsed = tags_parsed[i].trim();
                    if (!black_word_list.contains(tag_parsed)) {
                        score = tags.get(tag_parsed);
                        if (score == null) {
                            tags.put(tag_parsed, new Double(1.0));
                        } else {
                            tags.put(tag_parsed, (score + 1));
                        }
                    }
                }
            }
        } while (wallpaper_tags.next());
    }
    wallpaper_tags.close();
    //keeping only maxTags quantity
    Set<Entry<String, Double>> i = tags.entrySet();
    List<Entry<String, Double>> l = new LinkedList<Entry<String, Double>>(i);
    java.util.Collections.sort(l, new WallpaperServiceImpl.EntryComparatorDesc());

    if (maxTags > 0) {
        for (int j = maxTags; j < l.size(); j++) {
            tags.remove(l.get(j).getKey());
        }
    }
    return tags;
}