Java Code Examples for javax.transaction.Transaction#registerSynchronization()

The following examples show how to use javax.transaction.Transaction#registerSynchronization() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimerData.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void registerTimerDataSynchronization() throws TimerStoreException {
    if (synchronizationRegistered) {
        return;
    }

    try {
        final Transaction transaction = timerService.getTransactionManager().getTransaction();
        final int status = transaction == null ? Status.STATUS_NO_TRANSACTION : transaction.getStatus();

        if (transaction != null && status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK) {
            transaction.registerSynchronization(new TimerDataSynchronization());
            synchronizationRegistered = true;
            return;
        }
    } catch (final Exception e) {
        log.warning("Unable to register timer data transaction synchronization", e);
    }

    // there either wasn't a transaction or registration failed... call transactionComplete directly
    transactionComplete(true);
}
 
Example 2
Source File: SimpleTransactionSynchronizationRegistry.java    From tomee with Apache License 2.0 6 votes vote down vote up
public void putResource(final Object key, final Object value) {
    final Transaction transaction = getActiveTransaction();

    Map<Object, Object> resources = transactionResources.get(transaction);
    if (resources == null) {
        // after transaction completes clean up resources
        try {
            transaction.registerSynchronization(new RemoveTransactionResources(transaction));
        } catch (final Exception e) {
            throw new IllegalStateException("No transaction active", e);
        }
        resources = new HashMap<>();
        transactionResources.put(transaction, resources);
    }

    resources.put(key, value);
}
 
Example 3
Source File: XATransactionDataSource.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
/**
 * Get connection.
 *
 * @return XA transaction connection
 * @throws SQLException SQL exception
 * @throws SystemException system exception
 * @throws RollbackException rollback exception
 */
public Connection getConnection() throws SQLException, SystemException, RollbackException {
    if (CONTAINER_DATASOURCE_NAMES.contains(dataSource.getClass().getSimpleName())) {
        return dataSource.getConnection();
    }
    Connection result = dataSource.getConnection();
    XAConnection xaConnection = XAConnectionFactory.createXAConnection(databaseType, xaDataSource, result);
    final Transaction transaction = xaTransactionManager.getTransactionManager().getTransaction();
    if (!enlistedTransactions.get().contains(transaction)) {
        transaction.enlistResource(new SingleXAResource(resourceName, xaConnection.getXAResource()));
        transaction.registerSynchronization(new Synchronization() {
            @Override
            public void beforeCompletion() {
                enlistedTransactions.get().remove(transaction);
            }

            @Override
            public void afterCompletion(final int status) {
                enlistedTransactions.get().clear();
            }
        });
        enlistedTransactions.get().add(transaction);
    }
    return result;
}
 
Example 4
Source File: ServiceSynchronization.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
protected static ServiceSynchronization getInstance() throws GenericServiceException {
    ServiceSynchronization sync = null;
    try {
        Transaction transaction = TransactionFactoryLoader.getInstance().getTransactionManager().getTransaction();
        synchronized (transaction) {
            sync = syncingleton.get(transaction);
            if (sync == null) {
                sync = new ServiceSynchronization();
                transaction.registerSynchronization(sync);
                syncingleton.put(transaction, sync);
            }
        }
    } catch (SystemException | IllegalStateException | RollbackException e) {
        throw new GenericServiceException(e.getMessage(), e);
    }
    return sync;
}
 
Example 5
Source File: JtaTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations a List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 6
Source File: JtaTransactionContext.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void addTransactionListener(TransactionState transactionState, final TransactionListener transactionListener) {
  Transaction transaction = getTransaction();
  CommandContext commandContext = Context.getCommandContext();
  try {
    transaction.registerSynchronization(new TransactionStateSynchronization(transactionState, transactionListener, commandContext));
  }
  catch (Exception e) {
    throw LOG.exceptionWhileInteractingWithTransaction("registering synchronization", e);
  }
}
 
Example 7
Source File: SimpleTransactionSynchronizationRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void registerInterposedSynchronization(final Synchronization synchronization) {
    if (synchronization == null) {
        throw new NullPointerException("synchronization is null");
    }

    final Transaction transaction = getActiveTransaction();
    try {
        transaction.registerSynchronization(synchronization);
    } catch (final Exception ignored) {
        // no-op
    }
}
 
Example 8
Source File: XAStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private XATransactionContext<K, V> getCurrentContext() {
  try {
    final Transaction transaction = transactionManagerWrapper.getTransactionManager().getTransaction();
    if (transaction == null) {
      throw new XACacheException("Cannot access XA cache outside of XA transaction scope");
    }
    EhcacheXAResource<K, V> xaResource = xaResources.get(transaction);
    if (xaResource == null) {
      xaResource = new EhcacheXAResource<>(underlyingStore, journal, transactionContextFactory);
      transactionManagerWrapper.registerXAResource(uniqueXAResourceId, xaResource);
      transactionManagerWrapper.getTransactionManager().getTransaction().enlistResource(xaResource);
      xaResources.put(transaction, xaResource);
      final EhcacheXAResource<K, V> finalXaResource = xaResource;
      transaction.registerSynchronization(new Synchronization() {
        @Override
        public void beforeCompletion() {
        }

        @Override
        public void afterCompletion(int status) {
          transactionManagerWrapper.unregisterXAResource(uniqueXAResourceId, finalXaResource);
          xaResources.remove(transaction);
        }
      });
    }
    XATransactionContext<K, V> currentContext = xaResource.getCurrentContext();
    if (currentContext.hasTimedOut()) {
      throw new XACacheException("Current XA transaction has timed out");
    }
    return currentContext;
  } catch (SystemException se) {
    throw new XACacheException("Cannot get current XA transaction", se);
  } catch (RollbackException re) {
    throw new XACacheException("XA Transaction has been marked for rollback only", re);
  }
}
 
Example 9
Source File: MithraManager.java    From reladomo with Apache License 2.0 5 votes vote down vote up
private MithraRootTransaction createMithraRootTransaction(Transaction jtaTx, int timeoutInMilliseconds) throws SystemException, RollbackException
{
    MithraRootTransaction result = new MithraRootTransaction(jtaTx, timeoutInMilliseconds);
    MithraTransactionalPortal.initializeTransactionalQueryCache(result);
    jtaTx.registerSynchronization(result);
    return result;
}
 
Example 10
Source File: JtaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 11
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 12
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations a List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 13
Source File: SessionFactoryUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Register a JTA synchronization for the given Session, if any.
 * @param sessionHolder the existing thread-bound SessionHolder, if any
 * @param session the Session to register
 * @param sessionFactory the SessionFactory that the Session was created with
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 */
private static void registerJtaSynchronization(Session session, SessionFactory sessionFactory,
		SQLExceptionTranslator jdbcExceptionTranslator, SessionHolder sessionHolder) {

	// JTA synchronization is only possible with a javax.transaction.TransactionManager.
	// We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
	// in Hibernate configuration, it will contain a TransactionManager reference.
	TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, session);
	if (jtaTm != null) {
		try {
			Transaction jtaTx = jtaTm.getTransaction();
			if (jtaTx != null) {
				int jtaStatus = jtaTx.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					logger.debug("Registering JTA transaction synchronization for new Hibernate Session");
					SessionHolder holderToUse = sessionHolder;
					// Register JTA Transaction with existing SessionHolder.
					// Create a new SessionHolder if none existed before.
					if (holderToUse == null) {
						holderToUse = new SessionHolder(jtaTx, session);
					}
					else {
						holderToUse.addSession(jtaTx, session);
					}
					jtaTx.registerSynchronization(
							new SpringJtaSynchronizationAdapter(
									new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true),
									jtaTm));
					holderToUse.setSynchronizedWithTransaction(true);
					if (holderToUse != sessionHolder) {
						TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
					}
				}
			}
		}
		catch (Throwable ex) {
			throw new DataAccessResourceFailureException(
					"Could not register synchronization with JTA TransactionManager", ex);
		}
	}
}
 
Example 14
Source File: SessionFactoryUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization.
 * @param sessionHolder the SessionHolder to check
 * @param sessionFactory the SessionFactory to get the JTA TransactionManager from
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 * @return the associated Session, if any
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 */
private static Session getJtaSynchronizedSession(
		SessionHolder sessionHolder, SessionFactory sessionFactory,
		SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException {

	// JTA synchronization is only possible with a javax.transaction.TransactionManager.
	// We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
	// in Hibernate configuration, it will contain a TransactionManager reference.
	TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
	if (jtaTm != null) {
		// Check whether JTA transaction management is active ->
		// fetch pre-bound Session for the current JTA transaction, if any.
		// (just necessary for JTA transaction suspension, with an individual
		// Hibernate Session per currently active/suspended transaction)
		try {
			// Look for transaction-specific Session.
			Transaction jtaTx = jtaTm.getTransaction();
			if (jtaTx != null) {
				int jtaStatus = jtaTx.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					Session session = sessionHolder.getValidatedSession(jtaTx);
					if (session == null && !sessionHolder.isSynchronizedWithTransaction()) {
						// No transaction-specific Session found: If not already marked as
						// synchronized with transaction, register the default thread-bound
						// Session as JTA-transactional. If there is no default Session,
						// we're a new inner JTA transaction with an outer one being suspended:
						// In that case, we'll return null to trigger opening of a new Session.
						session = sessionHolder.getValidatedSession();
						if (session != null) {
							logger.debug("Registering JTA transaction synchronization for existing Hibernate Session");
							sessionHolder.addSession(jtaTx, session);
							jtaTx.registerSynchronization(
									new SpringJtaSynchronizationAdapter(
											new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false),
											jtaTm));
							sessionHolder.setSynchronizedWithTransaction(true);
							// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
							// with FlushMode.NEVER, which needs to allow flushing within the transaction.
							FlushMode flushMode = session.getFlushMode();
							if (flushMode.lessThan(FlushMode.COMMIT)) {
								session.setFlushMode(FlushMode.AUTO);
								sessionHolder.setPreviousFlushMode(flushMode);
							}
						}
					}
					return session;
				}
			}
			// No transaction active -> simply return default thread-bound Session, if any
			// (possibly from OpenSessionInViewFilter/Interceptor).
			return sessionHolder.getValidatedSession();
		}
		catch (Throwable ex) {
			throw new DataAccessResourceFailureException("Could not check JTA transaction", ex);
		}
	}
	else {
		// No JTA TransactionManager -> simply return default thread-bound Session, if any
		// (possibly from OpenSessionInViewFilter/Interceptor).
		return sessionHolder.getValidatedSession();
	}
}
 
Example 15
Source File: JTANonClusteredSemaphore.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
/**
 * Grants a lock on the identified resource to the calling thread (blocking
 * until it is available).
 * 
 * @return true if the lock was obtained.
 */
public synchronized boolean obtainLock(Connection conn, String lockName) throws LockException {

    lockName = lockName.intern();

    Logger log = getLog();

    if(log.isDebugEnabled()) {
        log.debug(
            "Lock '" + lockName + "' is desired by: "
                    + Thread.currentThread().getName());
    }

    if (!isLockOwner(conn, lockName)) {
        if(log.isDebugEnabled()) {
            log.debug(
                "Lock '" + lockName + "' is being obtained: "
                        + Thread.currentThread().getName());
        }
        
        while (locks.contains(lockName)) {
            try {
                this.wait();
            } catch (InterruptedException ie) {
                if(log.isDebugEnabled()) {
                    log.debug(
                        "Lock '" + lockName + "' was not obtained by: "
                                + Thread.currentThread().getName());
                }
            }
        }

        // If we are in a transaction, register a callback to actually release
        // the lock when the transaction completes
        Transaction t = getTransaction();
        if (t != null) {
            try {
                t.registerSynchronization(new SemaphoreSynchronization(lockName));
            } catch (Exception e) {
                throw new LockException("Failed to register semaphore with Transaction.", e);
            }
        }
        
        if(log.isDebugEnabled()) {
            log.debug(
                "Lock '" + lockName + "' given to: "
                        + Thread.currentThread().getName());
        }
        
        
        getThreadLocks().add(lockName);
        locks.add(lockName);
    } else if(log.isDebugEnabled()) {
        log.debug(
            "Lock '" + lockName + "' already owned by: "
                    + Thread.currentThread().getName()
                    + " -- but not owner!",
            new Exception("stack-trace of wrongful returner"));
    }

    return true;
}
 
Example 16
Source File: JTANonClusteredSemaphore.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Grants a lock on the identified resource to the calling thread (blocking
 * until it is available).
 * 
 * @return true if the lock was obtained.
 */
public synchronized boolean obtainLock(Connection conn, String lockName) throws LockException {

    lockName = lockName.intern();

    if(log.isDebugEnabled()) {
        log.debug(
            "Lock '" + lockName + "' is desired by: "
                    + Thread.currentThread().getName());
    }

    if (!isLockOwner(conn, lockName)) {
        if(log.isDebugEnabled()) {
            log.debug(
                "Lock '" + lockName + "' is being obtained: "
                        + Thread.currentThread().getName());
        }
        
        while (locks.contains(lockName)) {
            try {
                this.wait();
            } catch (InterruptedException ie) {
                if(log.isDebugEnabled()) {
                    log.debug(
                        "Lock '" + lockName + "' was not obtained by: "
                                + Thread.currentThread().getName());
                }
            }
        }

        // If we are in a transaction, register a callback to actually release
        // the lock when the transaction completes
        Transaction t = getTransaction();
        if (t != null) {
            try {
                t.registerSynchronization(new SemaphoreSynchronization(lockName));
            } catch (Exception e) {
                throw new LockException("Failed to register semaphore with Transaction.", e);
            }
        }
        
        if(log.isDebugEnabled()) {
            log.debug(
                "Lock '" + lockName + "' given to: "
                        + Thread.currentThread().getName());
        }
        
        
        getThreadLocks().add(lockName);
        locks.add(lockName);
    } else if(log.isDebugEnabled()) {
        log.debug(
            "Lock '" + lockName + "' already owned by: "
                    + Thread.currentThread().getName()
                    + " -- but not owner!",
            new Exception("stack-trace of wrongful returner"));
    }

    return true;
}
 
Example 17
Source File: TestContainer.java    From development with Apache License 2.0 4 votes vote down vote up
private EntityManager createLazyEntityManager(
        final EntityManagerFactory factory) {
    InvocationHandler h = new InvocationHandler() {

        private final Map<Transaction, EntityManager> delegates = new HashMap<Transaction, EntityManager>();

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            final Transaction tx = persistence.getTransactionManager()
                    .getTransaction();
            if (tx == null) {
                throw new RuntimeException("No active Transaction");
            }
            EntityManager delegate = delegates.get(tx);
            if (delegate == null) {
                delegate = factory.createEntityManager();
                SessionFactory sessionFactory = persistence.getSf();
                final Session session = sessionFactory.openSession();
                delegates.put(tx, delegate);
                tx.registerSynchronization(new Synchronization() {

                    @Override
                    public void beforeCompletion() {
                    }

                    @Override
                    public void afterCompletion(int status) {
                        delegates.remove(tx).close();
                        session.close();
                    }
                });
            }
            try {
                return method.invoke(delegate, args);
            } catch (InvocationTargetException e) {
                throw e.getTargetException();
            }
        }
    };
    return (EntityManager) Proxy.newProxyInstance(this.getClass()
            .getClassLoader(), new Class[] { EntityManager.class }, h);
}
 
Example 18
Source File: TransactionSynchronizer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get a registered transaction synchronizer.
 *
 * @param tx the transaction
 * @param ti the transaction integration
 * @throws SystemException sys. exception
 * @throws RollbackException rollback exception
 * @return the registered transaction synchronizer for this transaction
 */
public static TransactionSynchronizer getRegisteredSynchronizer(Transaction tx, 
                                                                TransactionIntegration ti)
   throws SystemException, RollbackException
{
   Object id = ti.getIdentifier(tx);
   Record record = records.get(id);
   if (record == null)
   {
      Record newRecord = new Record(new ReentrantLock(true), new TransactionSynchronizer(tx, id));
      record = records.putIfAbsent(id, newRecord);
      if (record == null)
      {
         record = newRecord;

         if (log.isTraceEnabled())
            log.tracef("Adding: %s [%s]", System.identityHashCode(id), id.toString());

         try
         {
            if (ti.getTransactionSynchronizationRegistry() != null)
            {
               ti.getTransactionSynchronizationRegistry().
                  registerInterposedSynchronization(record.getTransactionSynchronizer());
            }
            else
            {
               tx.registerSynchronization(record.getTransactionSynchronizer());
            }
         }
         catch (Throwable t)
         {
            records.remove(id);

            if (t instanceof SystemException)
            {
               throw (SystemException)t;
            }
            else if (t instanceof RollbackException)
            {
               throw (RollbackException)t;
            }
            else
            {
               SystemException se = new SystemException(t.getMessage());
               se.initCause(t);
               throw se;
            }
         }
      }
   }
   return record.getTransactionSynchronizer();
}
 
Example 19
Source File: SessionFactoryUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Register a JTA synchronization for the given Session, if any.
 * @param sessionHolder the existing thread-bound SessionHolder, if any
 * @param session the Session to register
 * @param sessionFactory the SessionFactory that the Session was created with
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 */
private static void registerJtaSynchronization(Session session, SessionFactory sessionFactory,
		SQLExceptionTranslator jdbcExceptionTranslator, SessionHolder sessionHolder) {

	// JTA synchronization is only possible with a javax.transaction.TransactionManager.
	// We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
	// in Hibernate configuration, it will contain a TransactionManager reference.
	TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, session);
	if (jtaTm != null) {
		try {
			Transaction jtaTx = jtaTm.getTransaction();
			if (jtaTx != null) {
				int jtaStatus = jtaTx.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					logger.debug("Registering JTA transaction synchronization for new Hibernate Session");
					SessionHolder holderToUse = sessionHolder;
					// Register JTA Transaction with existing SessionHolder.
					// Create a new SessionHolder if none existed before.
					if (holderToUse == null) {
						holderToUse = new SessionHolder(jtaTx, session);
					}
					else {
						holderToUse.addSession(jtaTx, session);
					}
					jtaTx.registerSynchronization(
							new SpringJtaSynchronizationAdapter(
									new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true),
									jtaTm));
					holderToUse.setSynchronizedWithTransaction(true);
					if (holderToUse != sessionHolder) {
						TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
					}
				}
			}
		}
		catch (Throwable ex) {
			throw new DataAccessResourceFailureException(
					"Could not register synchronization with JTA TransactionManager", ex);
		}
	}
}
 
Example 20
Source File: SessionFactoryUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization.
 * @param sessionHolder the SessionHolder to check
 * @param sessionFactory the SessionFactory to get the JTA TransactionManager from
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 * @return the associated Session, if any
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 */
private static Session getJtaSynchronizedSession(
		SessionHolder sessionHolder, SessionFactory sessionFactory,
		SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException {

	// JTA synchronization is only possible with a javax.transaction.TransactionManager.
	// We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
	// in Hibernate configuration, it will contain a TransactionManager reference.
	TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
	if (jtaTm != null) {
		// Check whether JTA transaction management is active ->
		// fetch pre-bound Session for the current JTA transaction, if any.
		// (just necessary for JTA transaction suspension, with an individual
		// Hibernate Session per currently active/suspended transaction)
		try {
			// Look for transaction-specific Session.
			Transaction jtaTx = jtaTm.getTransaction();
			if (jtaTx != null) {
				int jtaStatus = jtaTx.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					Session session = sessionHolder.getValidatedSession(jtaTx);
					if (session == null && !sessionHolder.isSynchronizedWithTransaction()) {
						// No transaction-specific Session found: If not already marked as
						// synchronized with transaction, register the default thread-bound
						// Session as JTA-transactional. If there is no default Session,
						// we're a new inner JTA transaction with an outer one being suspended:
						// In that case, we'll return null to trigger opening of a new Session.
						session = sessionHolder.getValidatedSession();
						if (session != null) {
							logger.debug("Registering JTA transaction synchronization for existing Hibernate Session");
							sessionHolder.addSession(jtaTx, session);
							jtaTx.registerSynchronization(
									new SpringJtaSynchronizationAdapter(
											new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false),
											jtaTm));
							sessionHolder.setSynchronizedWithTransaction(true);
							// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
							// with FlushMode.NEVER, which needs to allow flushing within the transaction.
							FlushMode flushMode = session.getFlushMode();
							if (flushMode.lessThan(FlushMode.COMMIT)) {
								session.setFlushMode(FlushMode.AUTO);
								sessionHolder.setPreviousFlushMode(flushMode);
							}
						}
					}
					return session;
				}
			}
			// No transaction active -> simply return default thread-bound Session, if any
			// (possibly from OpenSessionInViewFilter/Interceptor).
			return sessionHolder.getValidatedSession();
		}
		catch (Throwable ex) {
			throw new DataAccessResourceFailureException("Could not check JTA transaction", ex);
		}
	}
	else {
		// No JTA TransactionManager -> simply return default thread-bound Session, if any
		// (possibly from OpenSessionInViewFilter/Interceptor).
		return sessionHolder.getValidatedSession();
	}
}