List of usage examples for org.hibernate ScrollableResults get
Object get(int i);
From source file:org.medici.bia.dao.document.DocumentDAOJpaImpl.java
License:Open Source License
/** * //from w ww.j av a 2 s. c o m * @throws PersistenceException */ @Override public void updateIndex(Date fromDate) throws PersistenceException { Session session = null; FullTextSession fullTextSession = null; ScrollableResults results = null; try { EntityManager entityManager = getEntityManager(); session = ((HibernateEntityManager) entityManager).getSession(); session = session.getSessionFactory().openSession(); fullTextSession = org.hibernate.search.Search.getFullTextSession(session); Query queryTotal = entityManager .createQuery("SELECT count(entryId) FROM Document where lastUpdate>=:lastUpdate"); queryTotal.setParameter("lastUpdate", fromDate); Long total = (Long) queryTotal.getSingleResult(); logger.info("Total Entities to be updated : " + total); if (total > 0) { Integer numberOfElements = 50; Integer numberOfElementsBeforeGC = 1000; org.hibernate.Query query = session.createQuery("FROM Document where lastUpdate>=:lastUpdate"); query.setParameter("lastUpdate", fromDate); Transaction tx = fullTextSession.beginTransaction(); query.setReadOnly(true); query.setLockMode("a", LockMode.NONE); results = query.scroll(ScrollMode.FORWARD_ONLY); Integer resultNumber = 0; while (results.next()) { Document document = (Document) results.get(0); fullTextSession.delete(document); fullTextSession.index(document); resultNumber++; if (resultNumber % numberOfElements == 0) { flushingFullTextSession(total, resultNumber, fullTextSession); } if (resultNumber % numberOfElementsBeforeGC == 0) { System.gc(); logger.info("Invoked Garbage collector to prevent OutOfMemory Errors"); } } flushingFullTextSession(total, resultNumber, fullTextSession); /* logger.info("Initiating Lucene Index Optimze..."); SearchFactory searchFactory = fullTextSession.getSearchFactory(); searchFactory.optimize(Document.class); */ logger.info("Finished Lucene Index Optimze"); tx.commit(); } else { logger.info("No Entities found to be indexed."); } logger.info("Indexing documents terminated without errors."); } catch (Throwable throwable) { logger.error(throwable); } finally { if (results != null) { results.close(); } /*if (fullTextSession.isOpen()) { fullTextSession.close(); }*/ if (session.isOpen()) { session.close(); } } }
From source file:org.medici.bia.dao.JpaDao.java
License:Open Source License
/** * //from www . j a v a2 s . c o m * @param fromDate * @throws PersistenceException */ public void updateIndex(Date fromDate) throws PersistenceException { Session session = null; FullTextSession fullTextSession = null; ScrollableResults results = null; try { EntityManager entityManager = getEntityManager(); session = ((HibernateEntityManager) entityManager).getSession(); session = session.getSessionFactory().openSession(); fullTextSession = org.hibernate.search.Search.getFullTextSession(session); Query queryTotal = entityManager .createQuery("SELECT count(*) FROM " + entityClass + " where lastUpdate>=:lastUpdate"); queryTotal.setParameter("lastUpdate", fromDate); Long total = (Long) queryTotal.getSingleResult(); logger.info("Total Entities to be updated : " + total); if (total > 0) { Integer numberOfElements = 50; Integer numberOfElementsBeforeGC = 1000; org.hibernate.Query query = session .createQuery("FROM " + entityClass + " where lastUpdate>=:lastUpdate"); query.setParameter("lastUpdate", fromDate); Transaction tx = fullTextSession.beginTransaction(); query.setReadOnly(true); query.setLockMode("a", LockMode.NONE); results = query.scroll(ScrollMode.FORWARD_ONLY); Integer resultNumber = 0; while (results.next()) { Object entityClass = (Object) results.get(0); fullTextSession.delete(entityClass); fullTextSession.index(entityClass); resultNumber++; if (resultNumber % numberOfElements == 0) { flushingFullTextSession(total, resultNumber, fullTextSession); } if (resultNumber % numberOfElementsBeforeGC == 0) { System.gc(); logger.info("Invoked Garbage collector to prevent OutOfMemory Errors"); } } flushingFullTextSession(total, resultNumber, fullTextSession); tx.commit(); logger.info("Initiating Lucene Index Optimze..."); SearchFactory searchFactory = fullTextSession.getSearchFactory(); searchFactory.optimize(entityClass); logger.info("Finished Lucene Index Optimze"); } else { logger.info("No Entities found to be indexed."); } logger.info("Indexing documents terminated without errors."); } catch (Throwable throwable) { logger.error(throwable); } finally { if (results != null) { results.close(); } if (fullTextSession.isOpen()) { fullTextSession.close(); } if (session.isOpen()) { session.close(); } } }
From source file:org.mifos.application.master.persistence.Upgrade1286195484.java
License:Open Source License
@Override public void upgrade(Connection connection) throws IOException, SQLException { conditionalAlter(connection);/*from w w w . j a va 2 s . co m*/ Session session = StaticHibernateUtil.getSessionTL(); ScrollableResults results = session.createQuery("from CustomerAddressDetailEntity") .setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY); Query update = session.createQuery( "update CustomerAddressDetailEntity set address.phoneNumberStripped = :phoneNumberStripped where " + "customerAddressId = :id"); Transaction t = session.beginTransaction(); int modifyCount = 0; int resultCount = 0; while (results.next()) { ++resultCount; CustomerAddressDetailEntity address = (CustomerAddressDetailEntity) results.get(0); if (address.getAddress().getPhoneNumber() != null && !address.getAddress().getPhoneNumber().isEmpty()) { update.setString("phoneNumberStripped", address.getAddress().getPhoneNumberStripped()); update.setInteger("id", address.getCustomerAddressId()); update.executeUpdate(); ++modifyCount; if (modifyCount % COMMIT_EVERY == 0) { t.commit(); t = session.beginTransaction(); } } if (resultCount % FLUSH_EVERY == 0) { session.flush(); session.clear(); } if (resultCount % PRINT_EVERY == 0) { System.out.print("."); System.out.flush(); } } session.flush(); t.commit(); }
From source file:org.ng200.openolympus.services.TaskService.java
License:Open Source License
@PreAuthorize(SecurityExpressionConstants.IS_ADMIN) @Transactional//ww w . j av a 2 s .c o m public void rejudgeTask(final Task task) throws ExecutionException, IOException { final Lock lock = task.writeLock(); lock.lock(); try { this.verdictRepository.flush(); this.solutionRepository.flush(); this.verdictRepository.deleteBySolutionTask(task); this.verdictRepository.flush(); final StatelessSession session = ((Session) this.entityManager.getDelegate()).getSessionFactory() .openStatelessSession(); try { final Query query = session.createQuery("from Solution where task_id=:taskID"); query.setParameter("taskID", task.getId()); query.setFetchSize(Integer.valueOf(1000)); query.setReadOnly(false); final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); try { while (results.next()) { final Solution solution = (Solution) results.get(0); this.testingService.testSolutionOnAllTests(solution); } } finally { results.close(); } } finally { session.close(); } } finally { lock.unlock(); } }
From source file:org.openbravo.advpaymentmngt.actionHandler.MatchStatementOnLoadActionHandler.java
License:Open Source License
private int runAutoMatchingAlgorithm(String strReconciliationId, final String strFinancialAccountId, final FIN_FinancialAccount financialAccount, FIN_Reconciliation reconciliation) throws InterruptedException, SQLException { final MatchingAlgorithm ma = financialAccount.getMatchingAlgorithm(); final FIN_MatchingTransaction matchingTransaction = new FIN_MatchingTransaction(ma.getJavaClassName()); final ScrollableResults bankLinesSR = APRM_MatchingUtility .getPendingToBeMatchedBankStatementLines(strFinancialAccountId, strReconciliationId); final List<FIN_FinaccTransaction> excluded = new ArrayList<FIN_FinaccTransaction>(); int matchedLines = 0, i = 0; try {// ww w. j a v a 2s . com List<String> bankLines = new ArrayList<String>(); while (bankLinesSR.next()) { final FIN_BankStatementLine bankStatementLine = (FIN_BankStatementLine) bankLinesSR.get(0); bankLines.add(bankStatementLine.getId()); if ((i % 100) == 0) { OBDal.getInstance().getSession().clear(); } i++; } bankLinesSR.close(); i = 0; for (i = 0; i < bankLines.size(); i++) { final FIN_BankStatementLine bankStatementLine = OBDal.getInstance().get(FIN_BankStatementLine.class, bankLines.get(i)); FIN_MatchedTransaction matched; // try to match if exception is thrown continue try { matched = matchingTransaction.match(bankStatementLine, excluded); } catch (Exception e) { matched = new FIN_MatchedTransaction(null, FIN_MatchedTransaction.NOMATCH); } FIN_FinaccTransaction transaction = matched.getTransaction(); if (transaction != null && APRM_MatchingUtility.matchBankStatementLine(bankStatementLine, transaction, reconciliation, matched.getMatchLevel(), false)) { excluded.add(transaction); matchedLines++; // Required to persist current matching so that it is not rollbacked afterwards because // of // a // future error OBDal.getInstance().getConnection().commit(); } if ((i % 100) == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } } catch (Exception e) { OBDal.getInstance().rollbackAndClose(); } return matchedLines; }
From source file:org.openbravo.advpaymentmngt.utility.FIN_BankStatementImport.java
License:Open Source License
private BusinessPartner matchBusinessPartnerByNameTokens(String partnername, Organization organization) { if (partnername == null || "".equals(partnername.trim())) { return null; }//w w w .ja v a 2 s . co m String parsedPartnername = partnername.toLowerCase(); // Remove exceptions for (String eliminate : stringExceptions) { parsedPartnername = parsedPartnername.replaceAll(eliminate.toLowerCase(), ""); } StringTokenizer st = new StringTokenizer(parsedPartnername); List<String> list = new ArrayList<String>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.length() > 3) { list.add(token); } } if (list.isEmpty()) { return null; } final StringBuilder whereClause = new StringBuilder(); OBContext.setAdminMode(); ScrollableResults businessPartnersScroll = null; try { whereClause.append("select b.id as id, b.name as name from "); whereClause.append(" BusinessPartner b "); whereClause.append(" where ("); for (String token : list) { whereClause.append( " lower(b." + BusinessPartner.PROPERTY_NAME + ") like lower('%" + token + "%') or "); } whereClause.delete(whereClause.length() - 3, whereClause.length()).append(")"); whereClause.append(" and b." + BusinessPartner.PROPERTY_ORGANIZATION + ".id in ("); whereClause.append( Utility.getInStrSet(new OrganizationStructureProvider().getNaturalTree(organization.getId())) + ") "); final Query bl = OBDal.getInstance().getSession().createQuery(whereClause.toString()); businessPartnersScroll = bl.scroll(ScrollMode.SCROLL_SENSITIVE); if (!businessPartnersScroll.next()) { return null; } else { final Object[] resultObject = (Object[]) businessPartnersScroll.get(0); if (!businessPartnersScroll.next()) { String strParnterId = ""; if (resultObject.getClass().isArray()) { final Object[] values = resultObject; strParnterId = (String) values[0]; } BusinessPartner bp = OBDal.getInstance().get(BusinessPartner.class, strParnterId); return bp; } else { String closestId = closest(businessPartnersScroll, partnername); BusinessPartner closest = OBDal.getInstance().get(BusinessPartner.class, closestId); return closest; } } } finally { businessPartnersScroll.close(); OBContext.restorePreviousMode(); } }
From source file:org.openbravo.advpaymentmngt.utility.FIN_BankStatementImport.java
License:Open Source License
private String closest(ScrollableResults businessPartners, String partnername) { String targetBusinessPartnerId = ""; try {// w w w .j a v a 2 s .c o m businessPartners.beforeFirst(); businessPartners.next(); Object[] resultObject = (Object[]) businessPartners.get(0); String targetBusinessPartnerName = ""; if (resultObject.getClass().isArray()) { final Object[] values = resultObject; targetBusinessPartnerId = (String) values[0]; targetBusinessPartnerName = (String) values[1]; } int distance = StringUtils.getLevenshteinDistance(partnername, targetBusinessPartnerName); String parsedPartnername = partnername.toLowerCase(); // Remove exceptions for (String eliminate : stringExceptions) { parsedPartnername = parsedPartnername.replaceAll(eliminate.toLowerCase(), ""); } // Remove Numeric characters char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; for (char character : digits) { parsedPartnername = parsedPartnername.replace(character, ' '); parsedPartnername = parsedPartnername.trim(); } businessPartners.beforeFirst(); int i = 0; while (businessPartners.next()) { i++; String bpId = ""; String bpName = ""; resultObject = (Object[]) businessPartners.get(0); if (resultObject.getClass().isArray()) { final Object[] values = resultObject; bpId = (String) values[0]; bpName = (String) values[1]; } // Calculates distance between two strings meaning number of changes required for a string // to // convert in another string int bpDistance = StringUtils.getLevenshteinDistance(parsedPartnername, bpName.toLowerCase()); if (bpDistance < distance) { distance = bpDistance; targetBusinessPartnerId = bpId; } if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } return targetBusinessPartnerId; } catch (Exception e) { log4j.error(e.getStackTrace()); } finally { return targetBusinessPartnerId; } }
From source file:org.openbravo.client.application.event.AcctSchemaEventHandler.java
License:Open Source License
private void updateElementValues(Element _element, AcctSchema acctSchema, boolean assetPositive, boolean liabilityPositive, boolean ownersEquityPositive, boolean expensePositive, boolean revenuePositive) { StringBuffer where = new StringBuffer(); final String ACCOUNTSIGN_CREDIT = "C"; final String ACCOUNTSIGN_DEBIT = "D"; final String ACCOUNTTYPE_MEMO = "M"; Element element = OBDal.getInstance().get(Element.class, _element.getId()); where.append(ElementValue.PROPERTY_ACCOUNTINGELEMENT + ".id = :element"); OBQuery<ElementValue> elementValueQry = OBDal.getInstance().createQuery(ElementValue.class, where.toString());/* w w w. j ava 2 s . com*/ elementValueQry.setFilterOnActive(false); elementValueQry.setFilterOnReadableClients(false); elementValueQry.setFilterOnReadableOrganization(false); elementValueQry.setNamedParameter("element", element.getId()); elementValueQry.setFetchSize(1000); ScrollableResults elementvalues = elementValueQry.scroll(ScrollMode.FORWARD_ONLY); try { // TODO: Review with Martin to see if flush is permitted in handlers // int i = 0; while (elementvalues.next()) { ElementValue elementValue = (ElementValue) elementvalues.get(0); boolean isCredit = getAccountSign(elementValue.getAccountType(), assetPositive, liabilityPositive, ownersEquityPositive, expensePositive, revenuePositive); if (!ACCOUNTTYPE_MEMO.equals(elementValue.getAccountType())) { elementValue.setAccountSign(isCredit ? ACCOUNTSIGN_CREDIT : ACCOUNTSIGN_DEBIT); } // if ((i % 100) == 0) { // OBDal.getInstance().flush(); // OBDal.getInstance().getSession().clear(); // element = OBDal.getInstance().get(Element.class, element.getId()); // } // i++; } } finally { elementvalues.close(); } }
From source file:org.openbravo.costing.CostAdjustmentProcess.java
License:Open Source License
private void initializeLines(CostAdjustment costAdjustment) { // initialize is related transaction adjusted flag to false OBCriteria<CostAdjustmentLine> critLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class); critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, costAdjustment)); critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_ISRELATEDTRANSACTIONADJUSTED, true)); ScrollableResults lines = critLines.scroll(ScrollMode.FORWARD_ONLY); long count = 1L; try {/*w w w . j av a 2 s . c o m*/ while (lines.next()) { CostAdjustmentLine line = (CostAdjustmentLine) lines.get(0); line.setRelatedTransactionAdjusted(false); OBDal.getInstance().save(line); if (count % 1000 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } count++; } OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } finally { lines.close(); } }
From source file:org.openbravo.costing.CostAdjustmentProcess.java
License:Open Source License
private void generateTransactionCosts(CostAdjustmentLine costAdjustmentLine) { log.debug("Generate transaction costs of line: {}", costAdjustmentLine.getLineNo()); long t1 = System.currentTimeMillis(); OBCriteria<CostAdjustmentLine> critLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class); Date referenceDate = costAdjustmentLine.getCostAdjustment().getReferenceDate(); critLines.add(Restrictions.or(//from w w w. j a v a2 s .c o m Restrictions.eq(CostAdjustmentLine.PROPERTY_PARENTCOSTADJUSTMENTLINE, costAdjustmentLine), Restrictions.eq("id", costAdjustmentLine.getId()))); ScrollableResults lines = critLines.scroll(ScrollMode.FORWARD_ONLY); try { while (lines.next()) { CostAdjustmentLine line = (CostAdjustmentLine) lines.get(0); if (!line.getTransactionCostList().isEmpty()) { continue; } TransactionCost trxCost = OBProvider.getInstance().get(TransactionCost.class); // TODO: Review this // trxCost.setNewOBObject(true); MaterialTransaction trx = line.getInventoryTransaction(); trxCost.setInventoryTransaction(trx); trxCost.setOrganization(trx.getOrganization()); trxCost.setCostDate(referenceDate); trxCost.setCostAdjustmentLine(line); trxCost.setUnitCost(line.isUnitCost()); Date accountingDate = line.getAccountingDate(); if (accountingDate == null) { accountingDate = trx.getMovementDate(); } trxCost.setAccountingDate(accountingDate); BigDecimal convertedAmt = line.getAdjustmentAmount(); if (!line.getCurrency().getId().equals(trx.getCurrency().getId())) { convertedAmt = FinancialUtils.getConvertedAmount(convertedAmt, line.getCurrency(), trx.getCurrency(), accountingDate, trx.getOrganization(), "C"); } trxCost.setCost(convertedAmt); trxCost.setCurrency(trx.getCurrency()); OBDal.getInstance().save(trxCost); OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } finally { lines.close(); } log.debug("Transaction costs created. Time {}", System.currentTimeMillis() - t1); }