List of usage examples for org.hibernate FlushMode MANUAL
FlushMode MANUAL
To view the source code for org.hibernate FlushMode MANUAL.
Click Source Link
From source file:com.openkm.servlet.admin.RebuildIndexesServlet.java
License:Open Source License
/** * FlushToIndexes implementation// ww w. ja va 2 s. c om */ @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.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.java
License:Apache License
/** * Make the session (and the underlying {@link java.sql.Connection} read only * * @param session/*from w w w . ja v a 2s. co m*/ */ private void makeReadOnly(final Session session) { session.setDefaultReadOnly(true); session.setFlushMode(FlushMode.MANUAL); // Make the Connection read only session.doWork(SetJDBCConnectionReadOnlyWork.READ_ONLY); }
From source file:com.square.core.agent.RebuildingIndexAgentJmxThead.java
License:Open Source License
/** * Lancement indexation manuelle sur requete. *//*ww w . j a v a 2 s . c o m*/ private void runManualIndexer(Session session) { final FullTextSession fullTextSession = Search.getFullTextSession(session); try { fullTextSession.setFlushMode(FlushMode.MANUAL); fullTextSession.setCacheMode(CacheMode.IGNORE); final Transaction transaction = fullTextSession.beginTransaction(); // Scrollable results will avoid loading too many objects in memory final ScrollableResults results = fullTextSession.createQuery(agent.getRequete()) .setFetchSize(agent.getBatchSizeToLoad()).scroll(ScrollMode.FORWARD_ONLY); int index = 0; while (results.next()) { index++; logger.debug(agent.getMessageSourceUtil().get(AgentJmxKeyUtil.MESSAGE_INDEXATION_DE) + " " + results.get(0) + " (id = " + ((BaseModel) results.get(0)).getId() + ")"); fullTextSession.index(results.get(0)); // index each element if (index % agent.getBatchSizeToLoad() == 0) { fullTextSession.flushToIndexes(); // apply changes to indexes fullTextSession.clear(); // free memory since the queue is processed } } transaction.commit(); } catch (SearchException e) { e.printStackTrace(); } }
From source file:com.tida_okinawa.corona.io.dam.hibernate.IoService.java
License:Open Source License
/** * ?// w w w . j a v a 2 s . com * * @param connect * @param user * @param passwd * @return true/false */ @Override protected synchronized Boolean connectDam(String connect, String user, String passwd) { // TODO getPatternTypes()???? try { Configuration config = new org.hibernate.cfg.Configuration().configure() .setProperty("hibernate.connection.url", connect) //$NON-NLS-1$ .setProperty("hibernate.connection.username", user) //$NON-NLS-1$ .setProperty("hibernate.connection.password", passwd); //$NON-NLS-1$ ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = null; // config.buildSessionFactory(serviceRegistry); try { sessionFactory = config.buildSessionFactory(serviceRegistry); } catch (HibernateException ee) { throw ee; } catch (Exception ex) { ex.printStackTrace(); /* ???? NullPointerException????????? */ if (ex instanceof NullPointerException) { return false; } throw ex; } this.session = sessionFactory.openSession(); this.session.setFlushMode(FlushMode.MANUAL); /* */ this.session.beginTransaction(); if (!isConnect()) { // DB???????????? LicenseActivator license = LicenseActivator.getDefault(); String dbVersion = license.getDbVersion().trim(); CoronaDbVersionBean bean = new CoronaDbVersionBean(); bean.setVersion(dbVersion); this.session.save(bean); this.session.flush(); } this.getPatternTypes(); this.strConnect = connect; this.strUser = user; this.strPasswd = passwd; if (CoronaActivator.getDefault() != null) { CoronaActivator.getDefault().getLogger().getOutStream() .println(Messages.IoService_connectDatabaseSuccess + strConnect); } /* */ this.session.getTransaction().commit(); return true; } catch (HibernateException e) { System.err.println(Messages.IoService_errorConnectDatabase); e.printStackTrace(); if (this.session != null) { if (this.session.isConnected()) { this.session.disconnect(); this.session.close(); } } return false; } finally { if (session.getTransaction().isActive()) { this.session.getTransaction().rollback(); } } }
From source file:com.vmware.bdd.dal.DAL.java
License:Open Source License
/** * Helper routine for wrapping a piece of code in a Hibernate transaction. * * @param obj -- the body of the transaction. * @param readOnly -- true if the writes are to be disallowed * @param retriesLeft -- the max number of times to retry on lock-acquisition exceptions. * 0 if retries are to be disallowed.//w ww . j a v a2 s .co m **/ @SuppressWarnings("deprecation") private static <T> T inTransactionDoWork(Saveable<T> obj, boolean readOnly, int retriesLeft) { T retval; while (true) { Session sn = getSession(); Transaction tx = null; FlushMode flushMode = null; boolean doRndRollback = ConfigInfo.isDebugEnabled() && stressTxnRollback && (rnd.nextInt() % 5) == 0; AuAssert.check(!isInTransaction()); // Disallow nesting for now. try { tx = sn.beginTransaction(); if (readOnly && tx != null) { flushMode = sn.getFlushMode(); sn.setFlushMode(FlushMode.MANUAL); } sn.connection().setReadOnly(readOnly); retval = obj.body(); if (doRndRollback) { logger.warn("randomly rollback the transaction"); throw new LockAcquisitionException("Random Rollback", new SQLException("Random Rollback")); } if (flushMode != null) { sn.setFlushMode(flushMode); } tx.commit(); break; // must come right after commit } catch (Throwable ex) { if (tx != null) { if (flushMode != null) { sn.setFlushMode(flushMode); } tx.rollback(); flushTransactionCallbacks(false); } // Strip off the BddException wrapper if a callee added it. Throwable realEx = (ex instanceof BddException) ? ex.getCause() : ex; if (isRetryable(realEx)) { if (retriesLeft > 0) { if (!doRndRollback) { retriesLeft--; reportRetry(retriesLeft, realEx); } } else { throw TxRetryException.wrap(realEx, doRndRollback); } } else if (isUniqViolation(realEx)) { throw UniqueConstraintViolationException.wrap((ConstraintViolationException) realEx); } else { throw BddException.wrapIfNeeded(ex, "Exception in a DAL transaction"); } } } flushTransactionCallbacks(true); return retval; }
From source file:com.wideplay.warp.persist.hibernate.HibernateLocalTxnInterceptor.java
License:Apache License
public Object invoke(MethodInvocation methodInvocation) throws Throwable { Session session = sessionProvider.get(); //allow silent joining of enclosing transactional methods (NOTE: this ignores the current method's txn-al settings) if (session.getTransaction().isActive()) return methodInvocation.proceed(); //read out transaction settings Transactional transactional = readTransactionMetadata(methodInvocation); //read-only txn? FlushMode savedFlushMode = FlushMode.AUTO; if (TransactionType.READ_ONLY.equals(transactional.type())) session.setFlushMode(FlushMode.MANUAL); try {//from w ww . j a v a2s. co m //no transaction already started, so start one and enforce its semantics Transaction txn = session.beginTransaction(); Object result; try { result = methodInvocation.proceed(); } catch (Exception e) { //commit transaction only if rollback didnt occur if (rollbackIfNecessary(transactional, e, txn)) txn.commit(); //propagate whatever exception is thrown anyway throw e; } //everything was normal so commit the txn (do not move into try block as it interferes with the advised method's throwing semantics) Exception commitException = null; try { txn.commit(); } catch (RuntimeException re) { txn.rollback(); commitException = re; } //propagate anyway if (null != commitException) throw commitException; //or return result return result; } finally { //if read-only txn, then restore flushmode, default is automatic flush if (TransactionType.READ_ONLY.equals(transactional.type())) session.setFlushMode(savedFlushMode); } }
From source file:com.wideplay.warp.persist.hibernate.ReadOnlyTransactionsTest.java
License:Apache License
@Test public void testReadOnlyTxRestoresSessionFlushMode() { final ReadOnlyTransactionalObject txnal = injector.getInstance(ReadOnlyTransactionalObject.class); Session session = txnal.runReadOnlyTxnAndReturnSession(); // because the session gets closed in UnitOfWork.TRANSACTION, // we do NOT reset the flushmode in the interceptor Assert.assertTrue(session.getFlushMode() == FlushMode.MANUAL, "FlushMode has been reset with UnitOfWork.TRANSACTION and read-only transactions, " + "this means the session was not closed!"); }
From source file:com.xpn.xwiki.store.XWikiHibernateStore.java
License:Open Source License
public XWikiDocument loadXWikiDoc(XWikiDocument doc, XWikiContext context) throws XWikiException { // To change body of implemented methods use Options | File Templates. boolean bTransaction = true; MonitorPlugin monitor = Util.getMonitorPlugin(context); try {// w w w . j a v a 2 s . c o m // Start monitoring timer if (monitor != null) { monitor.startTimer("hibernate"); } doc.setStore(this); checkHibernate(context); SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context); bTransaction = bTransaction && beginTransaction(sfactory, false, context); Session session = getSession(context); session.setFlushMode(FlushMode.MANUAL); try { session.load(doc, new Long(doc.getId())); doc.setDatabase(context.getDatabase()); doc.setNew(false); doc.setMostRecent(true); // Fix for XWIKI-1651 doc.setDate(new Date(doc.getDate().getTime())); doc.setCreationDate(new Date(doc.getCreationDate().getTime())); doc.setContentUpdateDate(new Date(doc.getContentUpdateDate().getTime())); } catch (ObjectNotFoundException e) { // No document doc.setNew(true); return doc; } // Loading the attachment list if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) { loadAttachmentList(doc, context, false); } // TODO: handle the case where there are no xWikiClass and xWikiObject in the Database BaseClass bclass = new BaseClass(); String cxml = doc.getXClassXML(); if (cxml != null) { bclass.fromXML(cxml); bclass.setDocumentReference(doc.getDocumentReference()); doc.setXClass(bclass); } // Store this XWikiClass in the context so that we can use it in case of recursive usage // of classes context.addBaseClass(bclass); if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) { Query query = session.createQuery( "from BaseObject as bobject where bobject.name = :name order by " + "bobject.number"); query.setText("name", doc.getFullName()); @SuppressWarnings("unchecked") Iterator<BaseObject> it = query.list().iterator(); EntityReference localGroupEntityReference = new EntityReference("XWikiGroups", EntityType.DOCUMENT, new EntityReference("XWiki", EntityType.SPACE)); DocumentReference groupsDocumentReference = new DocumentReference(context.getDatabase(), localGroupEntityReference.getParent().getName(), localGroupEntityReference.getName()); boolean hasGroups = false; while (it.hasNext()) { BaseObject object = it.next(); DocumentReference classReference = object.getXClassReference(); if (classReference == null) { continue; } // It seems to search before is case insensitive. And this would break the loading if we get an // object which doesn't really belong to this document if (!object.getDocumentReference().equals(doc.getDocumentReference())) { continue; } BaseObject newobject; if (classReference.equals(doc.getDocumentReference())) { newobject = bclass.newCustomClassInstance(context); } else { newobject = BaseClass.newCustomClassInstance(classReference, context); } if (newobject != null) { newobject.setId(object.getId()); newobject.setXClassReference(object.getXClassReference()); newobject.setDocumentReference(object.getDocumentReference()); newobject.setNumber(object.getNumber()); newobject.setGuid(object.getGuid()); object = newobject; } if (classReference.equals(groupsDocumentReference)) { // Groups objects are handled differently. hasGroups = true; } else { loadXWikiCollection(object, doc, context, false, true); } doc.setXObject(object.getNumber(), object); } // AFAICT this was added as an emergency patch because loading of objects has proven // too slow and the objects which cause the most overhead are the XWikiGroups objects // as each group object (each group member) would otherwise cost 2 database queries. // This will do every group member in a single query. if (hasGroups) { Query query2 = session .createQuery("select bobject.number, prop.value from StringProperty as prop," + "BaseObject as bobject where bobject.name = :name and bobject.className='XWiki.XWikiGroups' " + "and bobject.id=prop.id.id and prop.id.name='member' order by bobject.number"); query2.setText("name", doc.getFullName()); @SuppressWarnings("unchecked") Iterator<Object[]> it2 = query2.list().iterator(); while (it2.hasNext()) { Object[] result = it2.next(); Integer number = (Integer) result[0]; String member = (String) result[1]; BaseObject obj = BaseClass.newCustomClassInstance(groupsDocumentReference, context); obj.setDocumentReference(doc.getDocumentReference()); obj.setXClassReference(localGroupEntityReference); obj.setNumber(number.intValue()); obj.setStringValue("member", member); doc.setXObject(obj.getNumber(), obj); } } } // We need to ensure that the loaded document becomes the original document doc.setOriginalDocument(doc.clone()); if (bTransaction) { endTransaction(context, false, false); } } catch (Exception e) { Object[] args = { doc.getDocumentReference() }; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_READING_DOC, "Exception while reading document [{0}]", e, args); } finally { try { if (bTransaction) { endTransaction(context, false, false); } } catch (Exception e) { } // End monitoring timer if (monitor != null) { monitor.endTimer("hibernate"); } } log.debug("Loaded XWikiDocument: " + doc.getDocumentReference()); return doc; }
From source file:com.yahoo.elide.datastores.hibernate5.HibernateTransaction.java
License:Apache License
@Override public void flush(RequestScope requestScope) { try {// ww w . j a v a 2s .com deferredTasks.forEach(Runnable::run); deferredTasks.clear(); FlushMode flushMode = session.getFlushMode(); if (flushMode != FlushMode.COMMIT && flushMode != FlushMode.MANUAL) { session.flush(); } } catch (HibernateException e) { throw new TransactionException(e); } }
From source file:com.zutubi.pulse.master.xwork.interceptor.HibernateSessionInterceptor.java
License:Apache License
protected Session openSession() { try {//from w ww . j a v a 2 s . c om Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); return session; } catch (HibernateException ex) { throw new PulseRuntimeException("Could not open Hibernate Session", ex); } }