List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager registerSynchronization
public static void registerSynchronization(TransactionSynchronization synchronization) throws IllegalStateException
From source file:org.guzz.web.context.spring.TransactionManagerUtils.java
/** * Get a Guzz WriteTranSession for the given TransactionManager. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using {@link GuzzTransactionManager}. Will create a new * Session otherwise, if "allowCreate" is <code>true</code>. * <p>Same as {@link #getSession}, but throwing the original GuzzException. * @param transactionManager Guzz TransactionManager to create the session with * @param entityInterceptor Guzz entity interceptor, or <code>null</code> if none * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the * Session on transaction synchronization (may be <code>null</code>) * @param allowCreate whether a non-transactional Session should be created * when no transactional Session can be found for the current thread * @return the Guzz WriteTranSession// ww w. j a v a2 s . c o m * @throws GuzzException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is <code>false</code> */ private static WriteTranSession doGetSession(TransactionManager transactionManager) throws GuzzException, IllegalStateException { Assert.notNull(transactionManager, "No TransactionManager specified"); WriteTranSession session = null; WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager .getResource(transactionManager); if (writeTranSessionHolder != null) { // pre-bound Guzz WriteTranSession session = writeTranSessionHolder.getWriteTranSession(); } else { //????spring?????bug logger.debug("Opening Guzz WriteTranSession"); session = transactionManager.openRWTran(false); // Use same Session for further Guzz actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. logger.debug("Registering Spring transaction synchronization for new Guzz WriteTranSession"); writeTranSessionHolder = new WriteTranSessionHolder(session); TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(writeTranSessionHolder, transactionManager, true)); TransactionSynchronizationManager.bindResource(transactionManager, writeTranSessionHolder); writeTranSessionHolder.setSynchronizedWithTransaction(true); } // Check whether we are allowed to return the Session. if (!isSessionTransactional(session, transactionManager)) { closeSession(session); throw new IllegalStateException("No Guzz WriteTranSession bound to thread here"); } } if (writeTranSessionHolder.hasTimeout()) { session.setQueryTimeoutInSeconds(writeTranSessionHolder.getTimeToLiveInSeconds()); } return session; }
From source file:de.metas.procurement.webui.event.MFEventBus.java
private final PostAfterCommitCollector getPostAfterCommit() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { return null; }// w w w. j a va 2 s .com PostAfterCommitCollector instance = null; for (final TransactionSynchronization sync : TransactionSynchronizationManager.getSynchronizations()) { if (sync instanceof PostAfterCommitCollector) { instance = (PostAfterCommitCollector) sync; logger.debug("Found PostAfterCommitCollector instance: {}", instance); } } if (instance == null) { instance = new PostAfterCommitCollector(); TransactionSynchronizationManager.registerSynchronization(instance); logger.debug("Registered synchronization: {}", instance); } return instance; }
From source file:com.frank.search.solr.repository.support.SimpleSolrRepository.java
private void registerTransactionSynchronisationAdapter() { TransactionSynchronizationManager.registerSynchronization(SolrTransactionSynchronizationAdapterBuilder .forOperations(this.solrOperations).withDefaultBehaviour()); }
From source file:com.github.rholder.spring.transaction.TransactionBindingSupport.java
/** * Binds the Alfresco-specific to the transaction resources * /*from w w w . j av a 2 s . c o m*/ * @return Returns the current or new synchronization implementation */ private static TransactionSynchronizationImpl registerSynchronizations() { /* * No thread synchronization or locking required as the resources are all threadlocal */ if (!TransactionSynchronizationManager.isSynchronizationActive()) { Thread currentThread = Thread.currentThread(); throw new RuntimeException( "Transaction must be active and synchronization is required: " + currentThread); } TransactionSynchronizationImpl txnSynch = (TransactionSynchronizationImpl) TransactionSynchronizationManager .getResource(RESOURCE_KEY_TXN_SYNCH); if (txnSynch != null) { // synchronization already registered return txnSynch; } // we need a unique ID for the transaction String txnId = UUID.randomUUID().toString(); // register the synchronization txnSynch = new TransactionSynchronizationImpl(txnId); TransactionSynchronizationManager.registerSynchronization(txnSynch); // register the resource that will ensure we don't duplication the synchronization TransactionSynchronizationManager.bindResource(RESOURCE_KEY_TXN_SYNCH, txnSynch); // done if (logger.isDebugEnabled()) { logger.debug("Bound txn synch: " + txnSynch); } return txnSynch; }
From source file:de.metas.procurement.webui.sync.ServerSyncService.java
@Override public ISyncAfterCommitCollector syncAfterCommit() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new RuntimeException("Not in transaction"); }/*from w w w .j a va 2 s . co m*/ SyncAfterCommit instance = null; for (final TransactionSynchronization sync : TransactionSynchronizationManager.getSynchronizations()) { if (sync instanceof SyncAfterCommit) { instance = (SyncAfterCommit) sync; logger.debug("Found SyncAfterCommit instance: {}", instance); } } if (instance == null) { instance = new SyncAfterCommit(); TransactionSynchronizationManager.registerSynchronization(instance); logger.debug("Registered synchronization: {}", instance); } return instance; }
From source file:org.openvpms.component.business.dao.hibernate.im.lookup.LookupReplacer.java
/** * Executes an update query./*from w w w . j av a2s . com*/ * <p/> * If any updates are made, the second level caches associated with the persisent classes are also cleared. * <p/> * <strong>NOTE</strong>: There is a small window where the second level cache will not reflect the state of the * database. * * @param query the update query * @param session the hibernate session * @param persistentClasses the persistent classes affected by the update */ private void executeUpdate(Query query, final Session session, final Class... persistentClasses) { int updates = query.executeUpdate(); if (updates != 0) { final SessionFactory factory = session.getSessionFactory(); if (TransactionSynchronizationManager.isActualTransactionActive()) { // clear the cache when the transaction commits TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { if (status == STATUS_COMMITTED) { clearCaches(persistentClasses, factory); } } }); } else { clearCaches(persistentClasses, factory); } } }
From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImpl.java
private String saveEventByFingerprint(final byte[] fingerprintHash, final Collection<Event> events, final EventPreCreateContext context, final boolean createClearHash) throws ZepException { try {/* w w w .ja v a 2 s . co m*/ return metricRegistry.timer(getClass().getName() + ".saveEventByFingerprint") .time(new Callable<String>() { @Override public String call() throws Exception { final List<EventSummary.Builder> oldSummaryList = template.getJdbcOperations().query( "SELECT event_count,first_seen,last_seen,details_json,status_id,status_change,uuid" + " FROM event_summary WHERE fingerprint_hash=? FOR UPDATE", new RowMapperResultSetExtractor<EventSummary.Builder>(eventDedupMapper, 1), fingerprintHash); final EventSummary.Builder summary; if (!oldSummaryList.isEmpty()) { summary = oldSummaryList.get(0); } else { summary = EventSummary.newBuilder(); summary.setCount(0); summary.addOccurrenceBuilder(0); } boolean isNewer = false; for (Event event : events) { isNewer = merge(summary, event) || isNewer; } if (!events.isEmpty()) { summary.setUpdateTime(System.currentTimeMillis()); final long dedupCount; if (!oldSummaryList.isEmpty()) { dedupCount = events.size(); final Map<String, Object> fields = getUpdateFields(summary, isNewer, context, createClearHash); final StringBuilder updateSql = new StringBuilder("UPDATE event_summary SET "); int i = 0; for (String fieldName : fields.keySet()) { if (++i > 1) updateSql.append(','); updateSql.append(fieldName).append("=:").append(fieldName); } updateSql.append(" WHERE fingerprint_hash=:fingerprint_hash"); fields.put("fingerprint_hash", fingerprintHash); template.update(updateSql.toString(), fields); final String indexSql = "INSERT INTO event_summary_index_queue (uuid, update_time) SELECT uuid, " + String.valueOf(System.currentTimeMillis()) + " FROM event_summary WHERE fingerprint_hash=:fingerprint_hash"; template.update(indexSql, fields); } else { dedupCount = events.size() - 1; summary.setUuid(uuidGenerator.generate().toString()); final Map<String, Object> fields = getInsertFields(summary, context, createClearHash); fields.put(COLUMN_FINGERPRINT_HASH, fingerprintHash); insert.execute(fields); indexSignal(summary.getUuid(), System.currentTimeMillis()); } if (dedupCount > 0) { TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { counters.addToDedupedEventCount(dedupCount); } }); } } return summary.getUuid(); } }); } catch (ZepException e) { throw e; } catch (Exception e) { throw new ZepException(e); } }
From source file:org.openvpms.component.business.service.archetype.ArchetypeService.java
/** * Updates the descriptor cache. If a transaction is in progress, the * cache will only be updated on transaction commit. This means that the * descriptor will only be available via the <em>get*Descriptor</em> methods * on successful commit./*w w w. ja v a 2 s . co m*/ * * @param object the object to add to the cache */ private void updateCache(final IMObject object) { if (TransactionSynchronizationManager.isActualTransactionActive()) { // update the cache when the transaction commits TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { if (status == STATUS_COMMITTED) { addToCache(object); } } }); } else { addToCache(object); } }
From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImpl.java
private List<String> clearEvents(Event event, EventPreCreateContext context) throws ZepException { TypeConverter<Long> timestampConverter = databaseCompatibility.getTimestampConverter(); final List<byte[]> clearHashes = EventDaoUtils.createClearHashes(event, context); if (clearHashes.isEmpty()) { logger.debug("Clear event didn't contain any clear hashes: {}, {}", event, context); return Collections.emptyList(); }//from w w w .j a v a 2 s. com final long lastSeen = event.getCreatedTime(); Map<String, Object> fields = new HashMap<String, Object>(2); fields.put("_clear_created_time", timestampConverter.toDatabaseType(lastSeen)); fields.put("_clear_hashes", clearHashes); long updateTime = System.currentTimeMillis(); String indexSql = "INSERT INTO event_summary_index_queue (uuid, update_time) " + "SELECT uuid, " + String.valueOf(updateTime) + " FROM event_summary " + "WHERE last_seen <= :_clear_created_time " + "AND clear_fingerprint_hash IN (:_clear_hashes) " + "AND closed_status = FALSE "; this.template.update(indexSql, fields); /* Find events that this clear event would clear. */ final String sql = "SELECT uuid FROM event_summary " + "WHERE last_seen <= :_clear_created_time " + "AND clear_fingerprint_hash IN (:_clear_hashes) " + "AND closed_status = FALSE " + "FOR UPDATE"; final List<String> results = this.template.query(sql, new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { return uuidConverter.fromDatabaseType(rs, COLUMN_UUID); } }, fields); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { counters.addToClearedEventCount(results.size()); } }); return results; }