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:com.eucalyptus.reporting.art.generator.AbstractArtGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
protected <ET> void foreach(final Class<ET> eventClass, final Criterion criterion, final boolean ascending,
        final Predicate<? super ET> callback) {
    final EntityTransaction transaction = Entities.get(eventClass);
    ScrollableResults results = null;//w  w  w .  j av a2  s.  c om
    try {
        results = Entities.createCriteria(eventClass).setReadOnly(true).setCacheable(false)
                .setCacheMode(CacheMode.IGNORE).setFetchSize(100).add(criterion)
                .addOrder(ascending ? Order.asc(TIMESTAMP_MS) : Order.desc(TIMESTAMP_MS))
                .scroll(ScrollMode.FORWARD_ONLY);

        while (results.next()) {
            final ET event = (ET) results.get(0);
            if (!callback.apply(event)) {
                break;
            }
            Entities.evict(event);
        }
    } finally {
        if (results != null)
            try {
                results.close();
            } catch (Exception e) {
            }
        transaction.rollback();
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java

License:Apache License

public <T extends ObjectType> void searchObjectsIterativeAttempt(Class<T> type, ObjectQuery query,
        ResultHandler<T> handler, Collection<SelectorOptions<GetOperationOptions>> options,
        OperationResult result) throws SchemaException {
    Session session = null;//from w w  w  . jav  a  2s.co m
    try {
        session = baseHelper.beginReadOnlyTransaction();
        RQuery rQuery;
        if (isUseNewQueryInterpreter(query)) {
            QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext);
            rQuery = engine.interpret(query, type, options, false, session);
        } else {
            QueryEngine engine = new QueryEngine(getConfiguration(), prismContext);
            rQuery = engine.interpret(query, type, options, false, session);
        }

        ScrollableResults results = rQuery.scroll(ScrollMode.FORWARD_ONLY);
        try {
            Iterator<GetObjectResult> iterator = new ScrollableResultsIterator(results);
            while (iterator.hasNext()) {
                GetObjectResult object = iterator.next();

                PrismObject<T> prismObject = updateLoadedObject(object, type, null, options, session, result);
                if (!handler.handle(prismObject, result)) {
                    break;
                }
            }
        } finally {
            if (results != null) {
                results.close();
            }
        }

        session.getTransaction().commit();
    } catch (SchemaException | QueryException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        baseHelper.cleanupSessionAndResult(session, result);
    }
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private <T extends ObjectType> void searchObjectsIterativeAttempt(Class<T> type, ObjectQuery query,
        ResultHandler<T> handler, Collection<SelectorOptions<GetOperationOptions>> options,
        OperationResult result) throws SchemaException {

    Session session = null;//from  ww w.j  a  v  a2s .  c  o  m
    try {
        session = beginReadOnlyTransaction();
        QueryEngine engine = new QueryEngine(getConfiguration(), getPrismContext());
        RQuery rQuery = engine.interpret(query, type, options, false, session);

        ScrollableResults results = rQuery.scroll(ScrollMode.FORWARD_ONLY);
        try {
            Iterator<GetObjectResult> iterator = new ScrollableResultsIterator(results);
            while (iterator.hasNext()) {
                GetObjectResult object = iterator.next();

                PrismObject<T> prismObject = updateLoadedObject(object, type, options, session);
                if (!handler.handle(prismObject, result)) {
                    break;
                }
            }
        } finally {
            if (results != null) {
                results.close();
            }
        }

        session.getTransaction().commit();
    } catch (SchemaException | QueryException | RuntimeException ex) {
        handleGeneralException(ex, session, result);
    } finally {
        cleanupSessionAndResult(session, result);
    }
}

From source file:com.hmsinc.epicenter.tools.reclassifier.Reclassifier.java

License:Open Source License

@Transactional
public void run() {

    setup();//from w  w w .  j  a va2  s.  c om

    final String destinationTable = (arguments.length > 4) ? arguments[4] : DEFAULT_TABLE_NAME;
    final String query = new StringBuilder("INSERT INTO ").append(destinationTable)
            .append(INSERT_CLASSIFICATION).toString();

    final BatchSqlUpdate updater = new BatchSqlUpdate(modelDataSource, query);
    updater.declareParameter(new SqlParameter(Types.BIGINT));
    updater.declareParameter(new SqlParameter(Types.BIGINT));
    updater.setBatchSize(BATCH_SIZE);
    updater.compile();

    final StatelessSession ss = ((Session) entityManager.getDelegate()).getSessionFactory()
            .openStatelessSession();

    final Criteria c = ss.createCriteria(target.getInteractionClass())
            .add(Restrictions.eq("patientClass", target.getPatientClass())).addOrder(Order.asc("id"))
            .setCacheable(false);

    if (arguments.length > 2) {
        c.add(Restrictions.gt("id", Long.valueOf(arguments[2])));
    }

    if (arguments.length > 3) {
        c.add(Restrictions.lt("id", Long.valueOf(arguments[3])));
    }

    final ScrollableResults sr = c.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    while (sr.next()) {

        final Interaction interaction = (Interaction) sr.get(0);
        final Set<Classification> classifications = classificationService.classify(interaction, target);

        save(interaction, classifications, updater);

        i++;
        if (i % BATCH_SIZE == 0) {
            logger.info("Processed {} interactions (current id: {})", i, interaction.getId());
        }

        ((Session) entityManager.getDelegate()).evict(interaction);
    }

    sr.close();

    updater.flush();
}

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

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getAlertExpiredMaintReport(Account pAccount, String remoteUser, String lsName,
        PrintWriter pPrintWriter) throws HibernateException, Exception {
    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT CASE WHEN VA.Alert_Age > 90 THEN 'Red' WHEN VA.Alert_Age > 45 THEN 'Yellow' ELSE 'Green' END, COALESCE(S.software_name, L.Full_Desc), L.Quantity, L.Expire_Date, L.Ext_Src_Id, VA.Creation_Time, VA.Alert_Age, VA.Remote_User, VA.Comments, VA.Record_Time FROM EAADMIN.V_Alerts VA, EAADMIN.License L LEFT OUTER JOIN EAADMIN.License_Sw_Map LSM ON LSM.License_Id = L.Id LEFT OUTER JOIN EAADMIN.software S ON S.software_id = LSM.Software_Id WHERE VA.Customer_Id = :customerId AND VA.Type = 'EXPIRED_MAINT' AND VA.Open = 1 AND L.Id = VA.Fk_Id ORDER BY COALESCE(S.software_name, L.Full_Desc) ASC")
            .setLong("customerId", pAccount.getId()).setString("type", "EXPIRED_MAINT")
            .scroll(ScrollMode.FORWARD_ONLY);

    printHeader(ALERT_EXPIRED_MAINT_REPORT_NAME, pAccount.getAccount(),
            ALERT_EXPIRED_MAINT_REPORT_COLUMN_HEADERS, pPrintWriter);
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }/*from w w  w.  j  a  va2s.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 getAlertExpiredScanReport(Account pAccount, String remoteUser, String lsName, HSSFWorkbook phwb,
        OutputStream pOutputStream) throws HibernateException, Exception {

    AlertType alertType = (AlertType) getEntityManager().createNamedQuery("getAlertTypeByCode")
            .setParameter("code", "EXP_SCAN").getSingleResult();

    StringBuffer dataQuery = new StringBuffer(
            "SELECT CASE WHEN VA.Alert_Age > 90 THEN 'Red' WHEN VA.Alert_Age > 45 THEN 'Yellow' ELSE 'Green' END, ");
    dataQuery.append(/*from   w ww .  j av a 2 s  .  co  m*/
            "SL.Name, SL.Bios_Serial, VA.Creation_Time, VA.Alert_Age, MT.Type, HL.OS_Type, VA.Remote_User, VA.Comments, ")
            .append("VA.Record_Time , AC.name as ac_name, CC.target_date,CC.owner as cc_owner,CC.record_time as cc_record_time, ")
            .append("CC.remote_user as cc_remote_user, CC.id as cc_id ").append("FROM EAADMIN.V_Alerts VA ")
            .append("JOIN EAADMIN.Software_Lpar SL ON SL.Id = VA.FK_Id ")
            .append("JOIN EAADMIN.cause_code CC ON (VA.id = CC.alert_id AND CC.alert_type_id = :alertTypeId) ")
            .append("JOIN EAADMIN.alert_cause AC ON CC.alert_cause_id = AC.id ")
            .append("LEFT OUTER JOIN EAADMIN.hw_sw_composite HSC on HSC.software_lpar_id = SL.id ")
            .append("LEFT OUTER JOIN EAADMIN.hardware_lpar HL on HL.id = HSC.hardware_lpar_id ")
            .append("LEFT OUTER JOIN EAADMIN.hardware H on H.id = HL.hardware_id ")
            .append("LEFT OUTER JOIN EAADMIN.machine_type MT on MT.id = H.machine_type_id ")
            .append("WHERE VA.Customer_Id = :customerId AND VA.Type = :type AND VA.Open = 1 ")
            .append("ORDER BY SL.Name ASC");

    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate())
            .createSQLQuery(dataQuery.toString()).setLong("customerId", pAccount.getId())
            .setString("type", "EXPIRED_SCAN").setInteger("alertTypeId", alertType.getId().intValue())
            .scroll(ScrollMode.FORWARD_ONLY);
    HSSFSheet sheet = phwb.createSheet("Alert Unexpired SW Lpar " + pAccount.getAccount() + " Report");
    printHeader(ALERT_EXPIRED_SCAN_REPORT_NAME, pAccount.getAccount(), ALERT_EXPIRED_SCAN_REPORT_COLUMN_HEADERS,
            sheet);
    int i = 3;
    while (lsrReport.next()) {
        int k = 1;
        if (i > 65535) {
            k++;
            sheet = phwb.createSheet("Alert Unexpired SW Lpar " + pAccount.getAccount() + " Report Sheet" + k);
            i = 1;
        }
        HSSFRow row = sheet.createRow((int) i);
        outputData(lsrReport.get(), row);
        i++;
    }

    @SuppressWarnings("unchecked")
    Iterator<Object[]> vCauseCodeSummary = getEntityManager()
            .createNamedQuery("getValidCauseCodesByAlertTypeId").setParameter("alertTypeId", alertType.getId())
            .getResultList().iterator();
    HSSFSheet sheet_2 = phwb.createSheet("Valid Cause Codes");
    HSSFRow rowhead0 = sheet_2.createRow((int) 0);
    outputData(ALERT_VALID_CAUSE_CODE_HEADERS, rowhead0);
    int j = 1;
    while (vCauseCodeSummary.hasNext()) {
        HSSFRow row = sheet_2.createRow((int) j);
        outputData(vCauseCodeSummary.next(), row);
        j++;
    }
    phwb.write(pOutputStream);
}

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

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getAlertHardwareLparReport(Account pAccount, String remoteUser, String lsName, HSSFWorkbook phwb,
        OutputStream pOutputStream) throws HibernateException, Exception {

    AlertType alertType = (AlertType) getEntityManager().createNamedQuery("getAlertTypeByCode")
            .setParameter("code", "HW_LPAR").getSingleResult();

    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT CASE WHEN VA.Alert_Age > 90 THEN 'Red' WHEN VA.Alert_Age > 45 THEN 'Yellow' ELSE 'Green' END, HL.Name AS HL_Name, H.Serial, MT.Name AS MT_Name, VA.Creation_Time, VA.Alert_Age, MT.Type, HL.OS_Type, VA.Remote_User, VA.Comments, VA.Record_Time, AC.name as ac_name, CC.target_date, CC.owner as cc_owner,CC.record_time as cc_record_time,CC.remote_user as cc_remote_user, CC.id as cc_id FROM EAADMIN.V_Alerts VA, EAADMIN.Hardware_Lpar HL, EAADMIN.Hardware H, EAADMIN.Machine_Type MT, EAADMIN.cause_code CC, EAADMIN.alert_cause AC WHERE VA.Customer_Id = :customerId AND VA.Type = 'HARDWARE_LPAR' AND VA.Open = 1 AND HL.Id = VA.FK_Id AND H.Id = HL.Hardware_Id AND MT.Id = H.Machine_Type_Id and VA.id=CC.alert_id and CC.alert_type_id = :alertTypeId and CC.alert_cause_id=AC.id ORDER BY HL.Name ASC")
            .setLong("customerId", pAccount.getId()).setInteger("alertTypeId", alertType.getId().intValue())
            .scroll(ScrollMode.FORWARD_ONLY);
    HSSFSheet sheet = phwb.createSheet("Alert HwLPAR Report");
    printHeader(ALERT_HARDWARE_LPAR_REPORT_NAME, pAccount.getAccount(),
            ALERT_HARDWARE_LPAR_REPORT_COLUMN_HEADERS, sheet);
    int i = 3;/*w  w w  .j av a2  s .  co m*/
    while (lsrReport.next()) {
        int k = 1;
        if (i > 65535) {
            k++;
            sheet = phwb.createSheet("Alert HWLpar Report Sheet" + k);
            i = 1;
        }
        HSSFRow row = sheet.createRow((int) i);
        outputData(lsrReport.get(), row);
        i++;
    }

    @SuppressWarnings("unchecked")
    Iterator<Object[]> vCauseCodeSummary = getEntityManager()
            .createNamedQuery("getValidCauseCodesByAlertTypeId").setParameter("alertTypeId", alertType.getId())
            .getResultList().iterator();
    HSSFSheet sheet_2 = phwb.createSheet("Valid Cause Codes");
    HSSFRow rowhead0 = sheet_2.createRow((int) 0);
    outputData(ALERT_VALID_CAUSE_CODE_HEADERS, rowhead0);
    int j = 1;
    while (vCauseCodeSummary.hasNext()) {
        HSSFRow row = sheet_2.createRow((int) j);
        outputData(vCauseCodeSummary.next(), row);
        j++;
    }
    phwb.write(pOutputStream);
}

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

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getAlertHardwareReport(Account pAccount, String remoteUser, String lsName, HSSFWorkbook phwb,
        OutputStream pOutputStream) throws HibernateException, Exception {

    AlertType alertType = (AlertType) getEntityManager().createNamedQuery("getAlertTypeByCode")
            .setParameter("code", "HARDWARE").getSingleResult();

    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(
            "SELECT CASE WHEN VA.Alert_Age > 90 THEN 'Red' WHEN VA.Alert_Age > 45 THEN 'Yellow' ELSE 'Green' END, H.Serial, MT.Name, VA.Creation_Time, VA.Alert_Age, MT.Type, VA.Remote_User, VA.Comments, VA.Record_Time,  AC.name as ac_name, CC.target_date,CC.owner as cc_owner,CC.record_time as cc_record_time,CC.remote_user as cc_remote_user, CC.id as cc_id FROM EAADMIN.V_Alerts VA, EAADMIN.Hardware H, EAADMIN.Machine_Type MT, EAADMIN.cause_code CC, EAADMIN.alert_cause AC WHERE VA.Customer_Id = :customerId AND VA.Type = 'HARDWARE' AND VA.Open = 1 AND H.Id = VA.FK_Id AND MT.Id = H.Machine_Type_Id and VA.id=CC.alert_id and CC.alert_type_id = :alertTypeId and CC.alert_cause_id=AC.id ORDER BY H.Serial ASC")
            .setLong("customerId", pAccount.getId()).setInteger("alertTypeId", alertType.getId().intValue())
            .scroll(ScrollMode.FORWARD_ONLY);
    HSSFSheet sheet = phwb.createSheet("Alert Hardware Report");
    printHeader(ALERT_HARDWARE_REPORT_NAME, pAccount.getAccount(), ALERT_HARDWARE_REPORT_COLUMN_HEADERS, sheet);
    int i = 3;//from   w  ww .ja  va  2s .  c  o m
    while (lsrReport.next()) {
        int k = 1;
        if (i > 65535) {
            k++;
            sheet = phwb.createSheet("Alert HW Report Sheet" + k);
            i = 1;
        }
        HSSFRow row = sheet.createRow((int) i);
        outputData(lsrReport.get(), row);
        i++;
    }

    @SuppressWarnings("unchecked")
    Iterator<Object[]> vCauseCodeSummary = getEntityManager()
            .createNamedQuery("getValidCauseCodesByAlertTypeId").setParameter("alertTypeId", alertType.getId())
            .getResultList().iterator();
    HSSFSheet sheet_2 = phwb.createSheet("Valid Cause Codes");
    HSSFRow rowhead0 = sheet_2.createRow((int) 0);
    outputData(ALERT_VALID_CAUSE_CODE_HEADERS, rowhead0);
    int j = 1;
    while (vCauseCodeSummary.hasNext()) {
        HSSFRow row = sheet_2.createRow((int) j);
        outputData(vCauseCodeSummary.next(), row);
        j++;
    }
    phwb.write(pOutputStream);
}

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

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getAlertSoftwareLparReport(Account pAccount, String remoteUser, String lsName, HSSFWorkbook phwb,
        OutputStream pOutputStream) throws HibernateException, Exception {

    AlertType alertType = (AlertType) getEntityManager().createNamedQuery("getAlertTypeByCode")
            .setParameter("code", "SW_LPAR").getSingleResult();

    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate()).createSQLQuery(SQL_QUERY_SW_LPAR)
            .setLong("customerId", pAccount.getId()).setString("type", "SOFTWARE_LPAR")
            .setInteger("alertTypeId", alertType.getId().intValue()).scroll(ScrollMode.FORWARD_ONLY);

    HSSFSheet sheet = phwb.createSheet("Alert SwLpar Report");
    printHeader(ALERT_SOFTWARE_LPAR_REPORT_NAME, pAccount.getAccount(), ALERT_SW_LPAR_REPORT_COLUMN_HEADERS,
            sheet);//from   ww w .  j a v a  2 s  .c om
    int i = 3;
    while (lsrReport.next()) {
        int k = 1;
        if (i > 65535) {
            k++;
            sheet = phwb.createSheet("Alert SWLpar Report Sheet" + k);
            i = 1;
        }
        HSSFRow row = sheet.createRow((int) i);
        outputData(lsrReport.get(), row);
        i++;
    }

    @SuppressWarnings("unchecked")
    Iterator<Object[]> vCauseCodeSummary = getEntityManager()
            .createNamedQuery("getValidCauseCodesByAlertTypeId").setParameter("alertTypeId", alertType.getId())
            .getResultList().iterator();
    HSSFSheet sheet_2 = phwb.createSheet("Valid Cause Codes");
    HSSFRow rowhead0 = sheet_2.createRow((int) 0);
    outputData(ALERT_VALID_CAUSE_CODE_HEADERS, rowhead0);
    int j = 1;
    while (vCauseCodeSummary.hasNext()) {
        HSSFRow row = sheet_2.createRow((int) j);
        outputData(vCauseCodeSummary.next(), row);
        j++;
    }
    phwb.write(pOutputStream);
}

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

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public void getAccountDataExceptionReport(Account pAccount, String remoteUser, String lsName, String pAlertCode,
        PrintWriter pPrintWriter) throws HibernateException, Exception {
    String sql_query_data_exception = null;
    String[] header_of_data_exception = null;
    for (DataExceptionTypeEnum l : DataExceptionTypeEnum.values()) {
        if (pAlertCode.equals(l.name().toString())) {
            if (l.getLevel().equals("SWLPAR")) {
                sql_query_data_exception = SQL_QUERY_ACCOUNT_DATAEXCEPTION_SWLPAR_Report;
                header_of_data_exception = ACCOUNT_DATA_EXCEPTIONS_REPORT_SWLPAR_COLUMN_HEADERS;
            }//from   w  ww  . j ava2s . co m
            if (l.getLevel().equals("HWLPAR")) {
                sql_query_data_exception = SQL_QUERY_ACCOUNT_DATAEXCEPTION_HWLPAR_Report;
                header_of_data_exception = ACCOUNT_DATA_EXCEPTIONS_REPORT_HWLPAR_COLUMN_HEADERS;
            }
            if (l.getLevel().equals("INSTSW")) {
                sql_query_data_exception = SQL_QUERY_ACCOUNT_DATAEXCEPTION_SWDSCEXP_Report;
                header_of_data_exception = ACCOUNT_DATA_EXCEPTIONS_REPORT_SWDSCEXP_COLUMN_HEADERS;
            }
        }
    }

    ScrollableResults lsrReport = ((Session) getEntityManager().getDelegate())
            .createSQLQuery(sql_query_data_exception).setLong("open", 1).setLong("customerId", pAccount.getId())
            .setString("alertCode", pAlertCode).scroll(ScrollMode.FORWARD_ONLY);

    printHeader(ACCOUNT_DATA_EXCEPTIONS_REPORT_NAME, pAccount.getAccount(), header_of_data_exception,
            pPrintWriter);
    while (lsrReport.next()) {
        pPrintWriter.println(outputData(lsrReport.get()));
    }
    lsrReport.close();
}