List of usage examples for org.hibernate ScrollableResults next
boolean next();
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 www . jav a 2 s.co 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.CmsWallpaperService.java
License:Apache License
@Override public long renewResolution(StatusBean sb) { File f;/*from w w w . ja v a2 s . c o m*/ BufferedImage bi; sb.setTotal((Long) wallpaper_service.getSinglePropertyU("count(*)")); ScrollableResults sr = wallpaper_service.getScrollableResults("id, name", null, null, null, null); File img_dir = new File(wallpaper_service.getStorePath(), "full"); sr.beforeFirst(); while (sr.next()) { f = new File(img_dir, sr.getString(1)); try { bi = ImageUtils.readImage(f).getImage(); wallpaper_service.updateObjectArrayShortByProperty(WALLPAPER_RESOLUTION, new Object[] { bi.getWidth(), bi.getHeight() }, "id", new Object[] { sr.getLong(0) }); sb.increaseDone(1); } catch (Exception ex) { logger.error("while trying to read wallpaper's resolution id = " + sr.getLong(0), ex); } } return sb.getDone(); }
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 w w . ja v a2s .c o m*/ 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; }
From source file:com.mysema.query.jpa.IntegrationBase.java
License:Apache License
@Test public void Scroll() { session.save(new Cat("Bob", 10)); session.save(new Cat("Steve", 11)); HibernateQuery query = new HibernateQuery(session); ScrollableResults results = query.from(QCat.cat).scroll(ScrollMode.SCROLL_INSENSITIVE, QCat.cat); while (results.next()) { System.out.println(results.get(0)); }//from w ww . ja v a 2 s . co m results.close(); }
From source file:com.openkm.servlet.admin.RebuildIndexesServlet.java
License:Open Source License
/** * FlushToIndexes implementation/*from w ww.ja va 2 s .c o m*/ */ @SuppressWarnings("rawtypes") private void luceneIndexesFlushToIndexes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("luceneIndexesFlushToIndexes({}, {})", request, response); PrintWriter out = response.getWriter(); response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "Rebuild Lucene indexes", breadcrumb); out.flush(); FullTextSession ftSession = null; Session session = null; Transaction tx = null; // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_FORCE_REBUILD_INDEXES", null, null, null); try { Config.SYSTEM_MAINTENANCE = true; Config.SYSTEM_READONLY = true; out.println("<ul>"); out.println("<li>System into maintenance mode</li>"); FileLogger.info(BASE_NAME, "BEGIN - Rebuild Lucene indexes"); session = HibernateUtil.getSessionFactory().openSession(); ftSession = Search.getFullTextSession(session); ftSession.setFlushMode(FlushMode.MANUAL); ftSession.setCacheMode(CacheMode.IGNORE); tx = ftSession.beginTransaction(); Map<String, Long> total = new HashMap<String, Long>(); // Calculate number of entities for (Class cls : classes) { String nodeType = cls.getSimpleName(); out.println("<li>Calculate " + nodeType + "</li>"); out.flush(); long partial = NodeBaseDAO.getInstance().getCount(nodeType); FileLogger.info(BASE_NAME, "Number of {0}: {1}", nodeType, partial); out.println("<li>Number of " + nodeType + ": " + partial + "</li>"); out.flush(); total.put(nodeType, partial); } // Rebuild indexes out.println("<li>Rebuilding indexes</li>"); out.flush(); // Scrollable results will avoid loading too many objects in memory for (Class cls : classes) { String nodeType = cls.getSimpleName(); out.println("<li>Indexing " + nodeType + "</li>"); out.flush(); ProgressMonitor monitor = new ProgressMonitor(out, nodeType, total.get(nodeType)); ScrollableResults results = ftSession.createCriteria(cls) .setFetchSize(Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS) .scroll(ScrollMode.FORWARD_ONLY); int index = 0; while (results.next()) { monitor.documentsAdded(1); ftSession.index(results.get(0)); // Index each element if (index++ % Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS == 0) { ftSession.flushToIndexes(); // Apply changes to indexes ftSession.clear(); // Free memory since the queue is processed } } } tx.commit(); Config.SYSTEM_READONLY = false; Config.SYSTEM_MAINTENANCE = false; out.println("<li>System out of maintenance mode</li>"); out.flush(); // Finalized FileLogger.info(BASE_NAME, "END - Rebuild Lucene indexes"); out.println("<li>Index rebuilding completed!</li>"); out.println("</ul>"); out.flush(); } catch (Exception e) { tx.rollback(); out.println("<div class=\"warn\">Exception: " + e.getMessage() + "</div>"); out.flush(); } finally { Config.SYSTEM_READONLY = false; Config.SYSTEM_MAINTENANCE = false; HibernateUtil.close(ftSession); HibernateUtil.close(session); } // End page footer(out); out.flush(); out.close(); log.debug("luceneIndexesFlushToIndexes: void"); }
From source file:com.opensourcestrategies.financials.reports.FinancialReports.java
License:Open Source License
/** * <p>Look over invoice adjustments and transform them into into sales and tax invoice item facts. * Thus an adjustment amount is added into discount column of the fact table and this is only * currency column affected.</p>/*from www . j a v a 2s . c om*/ * * @param session Hibernate session * @throws GenericEntityException */ public static void loadInvoiceAdjustments(Session session, Delegator delegator) throws GenericEntityException { Transaction tx = session.beginTransaction(); // retrieve data as scrollable result set. // this is join of InvoiceAdjustment and Invoice entities and each record has all required data // to create new fact row Query invAdjQry = session.createQuery( "select IA.invoiceAdjustmentId, IA.invoiceId, IA.amount, I.partyIdFrom, I.invoiceDate, I.currencyUomId from InvoiceAdjustment IA, Invoice I where IA.invoiceId = I.invoiceId and I.invoiceTypeId = 'SALES_INVOICE' and I.statusId not in ('INVOICE_IN_PROCESS', 'INVOICE_CANCELLED', 'INVOICE_VOIDED', 'INVOICE_WRITEOFF')"); ScrollableResults adjustments = invAdjQry.scroll(); // iterate over record set while (adjustments.next()) { // keep result fields in variables as a matter of convenience String invoiceId = adjustments.getString(1); String invoiceAdjustmentId = adjustments.getString(0); BigDecimal amount = adjustments.getBigDecimal(2); String organizationPartyId = adjustments.getString(3); Timestamp invoiceDate = (Timestamp) adjustments.get(4); String currencyUomId = adjustments.getString(5); // lookup date dimension DateFormat dayOfMonthFmt = new SimpleDateFormat("dd"); DateFormat monthOfYearFmt = new SimpleDateFormat("MM"); DateFormat yearNumberFmt = new SimpleDateFormat("yyyy"); String dayOfMonth = dayOfMonthFmt.format(invoiceDate); String monthOfYear = monthOfYearFmt.format(invoiceDate); String yearNumber = yearNumberFmt.format(invoiceDate); EntityCondition dateDimConditions = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("dayOfMonth", dayOfMonth), EntityCondition.makeCondition("monthOfYear", monthOfYear), EntityCondition.makeCondition("yearNumber", yearNumber)); Long dateDimId = UtilEtl.lookupDimension("DateDim", "dateDimId", dateDimConditions, delegator); // lookup currency dimension Long currencyDimId = UtilEtl.lookupDimension("CurrencyDim", "currencyDimId", EntityCondition.makeCondition("uomId", currencyUomId), delegator); // lookup organization dimension Long organizationDimId = UtilEtl.lookupDimension("OrganizationDim", "organizationDimId", EntityCondition.makeCondition("organizationPartyId", organizationPartyId), delegator); // creates rows for both fact tables TaxInvoiceItemFact taxFact = new TaxInvoiceItemFact(); taxFact.setDateDimId(dateDimId); taxFact.setStoreDimId(0L); taxFact.setTaxAuthorityDimId(0L); taxFact.setCurrencyDimId(currencyDimId); taxFact.setOrganizationDimId(organizationDimId); taxFact.setInvoiceId(invoiceId); taxFact.setInvoiceAdjustmentId(invoiceAdjustmentId); taxFact.setGrossAmount(BigDecimal.ZERO); taxFact.setDiscounts(amount); taxFact.setRefunds(BigDecimal.ZERO); taxFact.setNetAmount(BigDecimal.ZERO); taxFact.setTaxable(BigDecimal.ZERO); taxFact.setTaxDue(BigDecimal.ZERO); session.save(taxFact); SalesInvoiceItemFact salesFact = new SalesInvoiceItemFact(); salesFact.setDateDimId(dateDimId); salesFact.setStoreDimId(0L); salesFact.setCurrencyDimId(currencyDimId); salesFact.setOrganizationDimId(organizationDimId); salesFact.setInvoiceId(invoiceId); salesFact.setInvoiceAdjustmentId(invoiceAdjustmentId); salesFact.setGrossAmount(BigDecimal.ZERO); salesFact.setDiscounts(amount); salesFact.setRefunds(BigDecimal.ZERO); salesFact.setNetAmount(BigDecimal.ZERO); session.save(salesFact); } adjustments.close(); tx.commit(); // persist result, don't move this statement upper }
From source file:com.orig.gls.group.dao.Group.java
public static void verifyGroup(int groupId) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null;/*www . j av a 2 s . c o m*/ try { tx = session.beginTransaction(); Criteria cr = session.createCriteria(GroupsTableMod.class); cr.add(Restrictions.eq("groupId", groupId)); int count = 0; ScrollableResults items = cr.scroll(); while (items.next()) { GroupsTableMod group = (GroupsTableMod) items.get(0); session.delete(group); if (++count % 100 == 0) { session.flush(); session.clear(); } } tx.commit(); } catch (Exception asd) { log.debug(asd.getMessage()); if (tx != null) { tx.rollback(); } } finally { session.close(); } }
From source file:com.orig.gls.subgroup.dao.SubGroup.java
public static void verifySubGroup(int groupId) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null;// w w w . j ava 2 s . com try { tx = session.beginTransaction(); Criteria cr = session.createCriteria(SubGrpTableMod.class); cr.add(Restrictions.eq("subGroupId", groupId)); int count = 0; ScrollableResults items = cr.scroll(); while (items.next()) { SubGrpTableMod group = (SubGrpTableMod) items.get(0); session.delete(group); if (++count % 100 == 0) { session.flush(); session.clear(); } } tx.commit(); } catch (Exception asd) { log.debug(asd.getMessage()); if (tx != null) { tx.rollback(); } } finally { session.close(); } }
From source file:com.querydsl.jpa.IntegrationBase.java
License:Apache License
@Test public void Scroll() { session.save(new Cat("Bob", 10)); session.save(new Cat("Steve", 11)); QCat cat = QCat.cat;//www. ja v a2 s.c o m HibernateQuery<?> query = new HibernateQuery<Void>(session); ScrollableResults results = query.from(cat).select(cat).scroll(ScrollMode.SCROLL_INSENSITIVE); while (results.next()) { assertNotNull(results.get(0)); } results.close(); }
From source file:com.reignite.query.StructuredQuery.java
License:Open Source License
private void join(List<Object> rows) { for (Join join : joins) { Set<Object> ids = new HashSet<Object>(); for (Object obj : rows) { if (obj instanceof Map) { ids.add(((Map<?, ?>) obj).get(join.getJoinId())); }/*from w ww . j a va 2s. c om*/ } // prepare the join by setting the order and adding an "in" // clause join.prepare(ids); // if ids is size 1 then we are either doing a per row join or there is only 1 result to join to int firstRow = ids.size() == 1 ? join.getStartIndex() : 0; ScrollableResults scroll = join.getCriteria().scroll(ScrollMode.FORWARD_ONLY); if (scroll.setRowNumber(firstRow)) { do { Object[] row = scroll.get(); mergeResult(rows, row, join); } while (scroll.next()); } scroll.close(); } }