javax.transaction.Synchronization Java Examples

The following examples show how to use javax.transaction.Synchronization. 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: TransactionImpl.java    From clearpool with GNU General Public License v3.0 7 votes vote down vote up
@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);
}
 
Example #2
Source File: TransactionResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #3
Source File: CmrSet.java    From tomee with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #4
Source File: TransactionalTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
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 #6
Source File: DefaultTransactionTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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"));
}
 
Example #7
Source File: DefaultTransactionTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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"));
}
 
Example #8
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #9
Source File: MultiThreadedTx.java    From reladomo with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #10
Source File: TransactionImpl.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public synchronized void registerSynchronization(Synchronization sync)
		throws RollbackException, IllegalStateException, SystemException {

	if (this.transactionStatus == Status.STATUS_MARKED_ROLLBACK) {
		throw new RollbackException();
	} else if (this.transactionStatus == Status.STATUS_ACTIVE) {
		this.synchronizationList.registerSynchronizationQuietly(sync);
		logger.debug("{}> register-sync: sync= {}"//
				, ByteUtils.byteArrayToString(this.transactionContext.getXid().getGlobalTransactionId()), sync);
	} else {
		throw new IllegalStateException();
	}

}
 
Example #11
Source File: TransactionSynchronizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: TransactionSynchronizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;  
}
 
Example #13
Source File: MithraRemoteTransactionProxy.java    From reladomo with Apache License 2.0 5 votes vote down vote up
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);
        }
    }

}
 
Example #14
Source File: HibernateJtaTransactionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testJtaSessionSynchronizationWithRollback() throws Exception {

	TransactionManager tm = mock(TransactionManager.class);
	MockJtaTransaction transaction = new MockJtaTransaction();
	given(tm.getTransaction()).willReturn(transaction);
	final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
	final Session session = mock(Session.class);
	given(sf.openSession()).willReturn(session);
	given(sf.getTransactionManager()).willReturn(tm);
	given(session.isOpen()).willReturn(true);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	HibernateTemplate ht = new HibernateTemplate(sf);
	ht.setExposeNativeSession(true);
	for (int i = 0; i < 5; i++) {
		ht.executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(org.hibernate.Session sess) {
				assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
				assertEquals(session, sess);
				return null;
			}
		});
	}

	Synchronization synchronization = transaction.getSynchronization();
	assertTrue("JTA synchronization registered", synchronization != null);
	synchronization.afterCompletion(Status.STATUS_ROLLEDBACK);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	verify(session).close();
}
 
Example #15
Source File: TransactionSynchronizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #16
Source File: TransactionalTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #17
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 #18
Source File: DummyTransaction.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
	}
 
Example #19
Source File: TransactionAwareSessionContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Registers transaction synchronization with session in order to clean up and close the session when transaction
    * finishes.
    *
    * @param session
    *            Session to register into transaction synchronization. Cannot be null.
    * @return Returns <code>true</code> if the session was register into any available synchronization strategy,
    *         <code>false</code> otherwise.
    */
   private boolean registerSynchronization(final Session session) {
// Tries Spring's transaction manager synchronization.
if (TransactionSynchronizationManager.isSynchronizationActive()) {

    // If it's allowed, registers synchronization to cleanup session.
    TransactionSynchronizationManager.registerSynchronization(createTransactionSynchronization(session));
    return true;
} else {
    // Tries JTA transaction manager synchronization.
    JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class);

    // If it's allowed, registers synchronization to cleanup session.
    if (jtaPlatform.canRegisterSynchronization()) {
	List<TransactionSynchronization> synchronizations;

	synchronizations = Arrays.asList(createTransactionSynchronization(session));

	Synchronization jtaSync;
	jtaSync = new JtaAfterCompletionSynchronization(synchronizations);
	jtaPlatform.registerSynchronization(jtaSync);

	return true;
    }
}
return false;
   }
 
Example #20
Source File: PseudoTransactionService.java    From tomee with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example #21
Source File: TransactionSynchronizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
   }
}
 
Example #22
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 #23
Source File: SynchronizationRegistryStandardImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 );
	}
}
 
Example #24
Source File: SynchronizationImpl.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SynchronizationImpl(Synchronization sync) {
	if (sync == null) {
		throw new IllegalArgumentException();
	} else {
		this.delegate = sync;
		this.beforeRequired = true;
		this.finishRequired = true;
	}
}
 
Example #25
Source File: SynchronizationRegistryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void notifySynchronizationsBeforeTransactionCompletion() {
	if ( synchronizations != null ) {
		for ( Synchronization synchronization : synchronizations ) {
			try {
				synchronization.beforeCompletion();
			}
			catch ( Throwable t ) {
				LOG.synchronizationFailed( synchronization, t );
			}
		}
	}
}
 
Example #26
Source File: WebSphereLibertyJtaPlatform.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void registerSynchronization(Synchronization synchronization) {
	try {
		retrieveTransactionManager().getTransaction().registerSynchronization(synchronization);
	} 
	catch ( RollbackException | SystemException x ) {
		throw new RuntimeException(x);
	}
}
 
Example #27
Source File: TransactionImpl.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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>();
}
 
Example #28
Source File: WebSphereExtendedJtaPlatform.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void registerSynchronization(final Synchronization synchronization)
		throws RollbackException, IllegalStateException,
		SystemException {

	final InvocationHandler ih = new InvocationHandler() {

		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			if ( "afterCompletion".equals( method.getName() ) ) {
				int status = args[2].equals(Boolean.TRUE) ?
						Status.STATUS_COMMITTED :
						Status.STATUS_UNKNOWN;
				synchronization.afterCompletion(status);
			}
			else if ( "beforeCompletion".equals( method.getName() ) ) {
				synchronization.beforeCompletion();
			}
			else if ( "toString".equals( method.getName() ) ) {
				return synchronization.toString();
			}
			return null;
		}

	};

	final Object synchronizationCallback = Proxy.newProxyInstance(
			getClass().getClassLoader(),
			new Class[] {synchronizationCallbackClass},
			ih
	);

	try {
		registerSynchronizationMethod.invoke( extendedJTATransaction, synchronizationCallback );
	}
	catch (Exception e) {
		throw new HibernateException(e);
	}

}
 
Example #29
Source File: TransactionManagerBasedSynchronizationStrategy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void registerSynchronization(Synchronization synchronization) {
	try {
		transactionManagerAccess.getTransactionManager().getTransaction().registerSynchronization( synchronization );
	}
	catch (Exception e) {
		throw new JtaPlatformException( "Could not access JTA Transaction to register synchronization", e );
	}
}
 
Example #30
Source File: SynchronizationRegistryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void registerSynchronization(Synchronization synchronization) {
	if ( synchronization == null ) {
		throw new NullSynchronizationException();
	}

	if ( synchronizations == null ) {
		synchronizations = new LinkedHashSet<Synchronization>();
	}

	boolean added = synchronizations.add( synchronization );
	if ( !added ) {
		LOG.synchronizationAlreadyRegistered( synchronization );
	}
}