下面列出了org.hibernate.TransactionException#javax.transaction.Synchronization 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public CmrSet(final EntityBean source, final String sourceProperty, final BeanContext relatedInfo, final String relatedProperty, final Collection<Bean> relatedBeans) {
this.source = source;
this.sourceProperty = sourceProperty;
this.relatedInfo = relatedInfo;
this.relatedProperty = relatedProperty;
this.relatedBeans = relatedBeans;
relatedLocal = relatedInfo.getLocalInterface();
final TransactionSynchronizationRegistry transactionRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
try {
transactionRegistry.registerInterposedSynchronization(new Synchronization() {
public void beforeCompletion() {
}
public void afterCompletion(final int i) {
mutable = false;
}
});
} catch (final IllegalStateException ignored) {
// no tx so not mutable
mutable = false;
}
}
@GET
public boolean tryTxn() throws Exception {
final AtomicBoolean res = new AtomicBoolean();
userTransaction.begin();
trs.registerInterposedSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
res.set(true);
}
@Override
public void afterCompletion(int status) {
}
});
userTransaction.commit();
return res.get();
}
/**
* Test registerSynchronization method.
*
* @throws Exception when a serious error occurs.
*/
@Test
public void testRegisterSynchronization() throws Exception {
Synchronization synchronization = new Synchronization() {
@Override
public void beforeCompletion() {
System.setProperty("beforeCompletionCalled", "true");
throw new RuntimeException("Throwing an exception here");
}
@Override
public void afterCompletion(int status) {
}
};
DefaultTransaction transaction = new DefaultTransaction();
transaction.registerSynchronization(synchronization);
transaction.commit();
assertEquals("true", System.getProperty("beforeCompletionCalled"));
}
/**
* Test registerSynchronization method.
*
* @throws Exception when a serious error occurs.
*/
@Test
public void testRegisterSynchronization2() throws Exception {
Synchronization synchronization = new Synchronization() {
@Override
public void beforeCompletion() {
}
@Override
public void afterCompletion(int status) {
System.setProperty("afterCompletionCalled", "true");
throw new RuntimeException("Throwing an exception here");
}
};
DefaultTransaction transaction = new DefaultTransaction();
transaction.registerSynchronization(synchronization);
transaction.commit();
assertEquals("true", System.getProperty("afterCompletionCalled"));
}
@Override
public void registerSynchronization(Synchronization synchronization)
throws RollbackException, SystemException {
if (this.status != Status.STATUS_ACTIVE) {
throw new IllegalStateException("the transaction is not active");
}
if (this.rollbackOnly) {
throw new RollbackException("the transaction is signed to roll back only");
}
TransactionAdapter txAdapt =
(TransactionAdapter) TransactionManagerImpl.getManager().getTransaction();
if (txAdapt.getTx() != this) {
throw new IllegalStateException("the transaction is not held");
}
if (this.synList == null) {
this.synList = new ArrayList<Synchronization>();
}
this.synList.add(synchronization);
}
private void beforeCompletion()
{
try
{
for(int i=0;i<this.synchronizations.size();i++)
{
Synchronization s = this.synchronizations.get(i);
s.beforeCompletion();
}
}
catch(Throwable t)
{
logger.error("The synchronization before completion failed. marked for rollback ", t);
this.status.set(MARKED_ROLLBACK);
}
}
@Test
public void testClobStringTypeWithJtaSynchronizationAndRollback() throws Exception {
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
given(lobHandler.getClobAsString(rs, "column")).willReturn("content");
ClobStringType type = new ClobStringType(lobHandler, tm);
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
type.nullSafeSet(ps, "content", 1);
Synchronization synch = transaction.getSynchronization();
assertNotNull(synch);
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
verify(lobCreator).setClobAsString(ps, 1, "content");
}
/**
* 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;
}
@Transactional(value = REQUIRED, dontRollbackOn = AnotherException.class)
public void anotherException(final AtomicInteger status) {
try {
OpenEJB.getTransactionManager().getTransaction().registerSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
// no-op
}
@Override
public void afterCompletion(final int state) {
status.set(state);
}
});
} catch (final RollbackException | SystemException e) {
fail();
}
throw new AnotherException();
}
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);
}
}
@Override
public void registerSynchronization(Synchronization synchronization)
{
if (this.synchronizations == null)
{
this.synchronizations = new InternalList(2);
}
this.synchronizations.add(synchronization);
}
@Override
public void registerSynchronization(Synchronization synchronization) {
if (this.transactionSynchronizationRegistry != null) {
this.transactionSynchronizationRegistry.registerInterposedSynchronization(synchronization);
}
else {
try {
this.transactionManager.getTransaction().registerSynchronization(synchronization);
}
catch (Exception ex) {
throw new TransactionException("Could not access JTA Transaction to register synchronization", ex);
}
}
}
private void afterCompletion(int st) {
if (this.synList == null) {
return;
}
for (Synchronization syn : this.synList) {
syn.afterCompletion(st);
}
}
private void afterCompletion()
{
if (this.synchronizations != null)
{
for (int i = 0; i < synchronizations.size(); i++)
{
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(this.proxyStatus);
}
}
}
@Test
public void rollbackException() throws Exception {
for (int i = 0; i < 2; i++) {
final AtomicInteger status = new AtomicInteger();
final TransactionManager transactionManager = OpenEJB.getTransactionManager();
transactionManager.begin();
transactionManager.getTransaction().registerSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
// no-op
}
@Override
public void afterCompletion(int state) {
status.set(state);
}
});
try {
bean.anException();
fail();
} catch (final AnException e) {
// no-op
}
OpenEJB.getTransactionManager().rollback();
assertEquals(Status.STATUS_ROLLEDBACK, status.get());
}
}
private void beforeCompletion() {
if (this.synList == null) {
return;
}
for (Synchronization syn : this.synList) {
syn.beforeCompletion();
}
}
EntityManagerResult getEntityManager() {
if (isInTransaction()) {
EntityManager em = (EntityManager) tsr.getResource(transactionKey);
if (em != null) {
return new EntityManagerResult(em, false, true);
}
EntityManager newEm = emf.createEntityManager();
newEm.joinTransaction();
tsr.putResource(transactionKey, newEm);
tsr.registerInterposedSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
newEm.flush();
}
@Override
public void afterCompletion(int i) {
newEm.close();
}
});
return new EntityManagerResult(newEm, false, true);
} else {
//this will throw an exception if the request scope is not active
//this is expected as either the request scope or an active transaction
//is required to properly managed the EM lifecycle
RequestScopedEntityManagerHolder requestScopedEms = this.requestScopedEms.get();
return new EntityManagerResult(requestScopedEms.getOrCreateEntityManager(unitName, emf), false, false);
}
}
@Override
public void registerSynchronization(Synchronization synchronization) {
if (this.transactionSynchronizationRegistry != null) {
this.transactionSynchronizationRegistry.registerInterposedSynchronization(synchronization);
}
else {
try {
this.transactionManager.getTransaction().registerSynchronization(synchronization);
}
catch (Exception ex) {
throw new TransactionException("Could not access JTA Transaction to register synchronization", ex);
}
}
}
@Test
public void assertGetHikariConnection() throws SQLException, RollbackException, SystemException {
DataSource dataSource = DataSourceUtils.build(HikariDataSource.class, DatabaseTypes.getActualDatabaseType("H2"), "ds1");
XATransactionDataSource transactionDataSource = new XATransactionDataSource(DatabaseTypes.getActualDatabaseType("H2"), "ds1", dataSource, xaTransactionManager);
try (Connection ignored = transactionDataSource.getConnection()) {
verify(transaction).enlistResource(ArgumentMatchers.any(SingleXAResource.class));
verify(transaction).registerSynchronization(ArgumentMatchers.any(Synchronization.class));
}
try (Connection ignored = transactionDataSource.getConnection()) {
verify(transaction).enlistResource(ArgumentMatchers.any(SingleXAResource.class));
verify(transaction).registerSynchronization(ArgumentMatchers.any(Synchronization.class));
}
}
/**
* Constructor
* @param key The transaction key
*/
public TransactionImpl(Long key)
{
this.key = key;
this.status = Status.STATUS_ACTIVE;
this.syncs = new HashSet<Synchronization>();
this.resources = new HashMap<Object, Object>();
}
/**
* Create a new transaction synchronizer
*
* @param tx the transaction to synchronize with
* @param id the identifier for the transaction
*/
private TransactionSynchronizer(Transaction tx, Object id)
{
this.tx = tx;
this.identifier = id;
this.enlistingThread = null;
this.unenlisted = new ArrayList<Synchronization>(1);
this.enlisted = new ArrayList<Synchronization>(1);
}
/**
* Check whether we have a CCM synchronization
*
* @param tx the transaction
* @param ti the transaction integration
* @return synch
*/
public static Synchronization getCCMSynchronization(Transaction tx, TransactionIntegration ti)
{
Record record = records.get(ti.getIdentifier(tx));
if (record != null)
return record.getTransactionSynchronizer().ccmSynch;
return null;
}
/**
* Register a new CCM synchronization
*
* @param tx the transaction
* @param synch the synchronization
* @param ti the transaction integration
* @throws Exception e
*/
public static void registerCCMSynchronization(Transaction tx,
Synchronization synch,
TransactionIntegration ti)
throws Exception
{
TransactionSynchronizer ts = getRegisteredSynchronizer(tx, ti);
ts.ccmSynch = synch;
}
public void rollback() throws IllegalStateException, SystemException {
status = Status.STATUS_ROLLING_BACK;
// Synch.beforeCompletion() should *not* be called for rollbacks
// for ( int i=0; i<synchronizations.size(); i++ ) {
// Synchronization s = (Synchronization) synchronizations.get(i);
// s.beforeCompletion();
// }
status = Status.STATUS_ROLLEDBACK;
try {
connection.rollback();
connection.close();
}
catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
for ( int i=0; i<synchronizations.size(); i++ ) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(status);
}
//status = Status.STATUS_NO_TRANSACTION;
transactionManager.endCurrent(this);
}
private void doAfterCompletion(final int status) {
for (final Synchronization sync : new ArrayList<>(registeredSynchronizations)) {
try {
sync.afterCompletion(status);
} catch (final RuntimeException e) {
logger.warning("Synchronization afterCompletion threw a RuntimeException", e);
}
}
}
/**
* Invoke an afterCompletion
*
* @param synch the synchronization
* @param status the status of the transaction
*/
protected void invokeAfter(Synchronization synch, int status)
{
try
{
synch.afterCompletion(status);
}
catch (Throwable t)
{
log.transactionErrorInAfterCompletion(tx, synch, t);
}
}
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
}
}
@Override
public void registerSynchronization(Synchronization synchronization) {
if ( synchronization == null ) {
throw new NullSynchronizationException();
}
if ( synchronizations == null ) {
synchronizations = new LinkedHashSet<Synchronization>();
}
final boolean added = synchronizations.add( synchronization );
if ( !added ) {
log.synchronizationAlreadyRegistered( synchronization );
}
}
public void registerSynchronization(Synchronization synchronization) {
try {
retrieveTransactionManager().getTransaction().registerSynchronization(synchronization);
}
catch ( RollbackException | SystemException x ) {
throw new RuntimeException(x);
}
}
/**
* Constructor
* @param key The transaction key
*/
public TransactionImpl(Long key)
{
this.key = key;
this.status = Status.STATUS_ACTIVE;
this.syncs = new HashSet<Synchronization>();
this.resources = new HashMap<Object, Object>();
}