javax.transaction.UserTransaction Java Examples

The following examples show how to use javax.transaction.UserTransaction. 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: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #2
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Find the JTA UserTransaction through a default JNDI lookup:
 * "java:comp/UserTransaction".
 * @return the JTA UserTransaction reference, or {@code null} if not found
 * @see #DEFAULT_USER_TRANSACTION_NAME
 */
@Nullable
protected UserTransaction findUserTransaction() {
	String jndiName = DEFAULT_USER_TRANSACTION_NAME;
	try {
		UserTransaction ut = getJndiTemplate().lookup(jndiName, UserTransaction.class);
		if (logger.isDebugEnabled()) {
			logger.debug("JTA UserTransaction found at default JNDI location [" + jndiName + "]");
		}
		this.userTransactionObtainedFromJndi = true;
		return ut;
	}
	catch (NamingException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("No JTA UserTransaction found at default JNDI location [" + jndiName + "]", ex);
		}
		return null;
	}
}
 
Example #3
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example #4
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingAndPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #5
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronizationName("SYNCHRONIZATION_NEVER");
	tt.setTimeout(10);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut, atLeastOnce()).getStatus();
	verify(ut).rollback();
}
 
Example #6
Source File: BeanManagedUserTransactionStrategy.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected void applyTransactionTimeout()
{
    Integer transactionTimeout = getDefaultTransactionTimeoutInSeconds();

    if (transactionTimeout == null)
    {
        //the default configured for the container will be used
        return;
    }

    try
    {
        UserTransaction userTransaction = resolveUserTransaction();

        if (userTransaction != null && userTransaction.getStatus() != Status.STATUS_ACTIVE)
        {
            userTransaction.setTransactionTimeout(transactionTimeout);
        }
    }
    catch (SystemException e)
    {
        LOGGER.log(Level.WARNING, "UserTransaction#setTransactionTimeout failed", e);
    }
}
 
Example #7
Source File: TransactionAwareSingletonTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testRollback() throws Throwable
{
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();

        singleton.put(INTEGER_TWO);
        check(INTEGER_TWO, true);
        check(null, false);

        // rollback
        txn.rollback();
    }
    catch (Throwable e)
    {
        try { txn.rollback(); } catch (Throwable ee) {}
        throw e;
    }
    check(null, true);
    check(null, false);
}
 
Example #8
Source File: JtaTransaction.java    From cdi with Apache License 2.0 6 votes vote down vote up
private UserTransaction getUserTransaction() {
    try {
        logger.debug("Attempting to look up standard UserTransaction.");
        return (UserTransaction) new InitialContext().lookup(
                USER_TRANSACTION_LOCATION);
    } catch (NamingException ex) {
        logger.debug("Could not look up standard UserTransaction.", ex);

        try {
            logger.debug("Attempting to look up JBoss proprietary UserTransaction.");
            return (UserTransaction) new InitialContext().lookup(
                    JBOSS_USER_TRANSACTION_LOCATION);
        } catch (NamingException ex1) {
            logger.debug("Could not look up JBoss proprietary UserTransaction.", ex1);
        }
    }

    return null;
}
 
Example #9
Source File: JBossStandAloneJtaPlatform.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected UserTransaction locateUserTransaction() {
	//Try WildFly first as it's the "new generation":
	try {
		return wildflyBasedAlternative.locateUserTransaction();
	}
	catch ( Exception ignore) {
		// ignore and look for Arjuna class
	}

	try {
		final Class jbossUtClass = serviceRegistry()
				.getService( ClassLoaderService.class )
				.classForName( JBOSS_UT_CLASS_NAME );
		return (UserTransaction) jbossUtClass.getMethod( "userTransaction" ).invoke( null );
	}
	catch ( Exception e ) {
		throw new JtaPlatformException( "Could not obtain JBoss Transactions user transaction instance", e );
	}
}
 
Example #10
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new NotSupportedException("not supported")).given(ut).begin();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown NestedTransactionNotSupportedException");
	}
	catch (NestedTransactionNotSupportedException ex) {
		// expected
	}
}
 
Example #11
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #12
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #13
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIsolationLevel() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}
}
 
Example #14
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testIndexOnCommitForDestroy() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.destroy(x);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #15
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willThrow(new SystemException("system exception"));

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example #16
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #17
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * verify that queries on indexes work with transaction
 * @see bug#40842
 * @throws Exception
 */
public void testIndexOnCommitForPut() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.put(x, dsample);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #18
Source File: LazyCCMXATransactionTestCase.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Constructor
 * @param connectionFactory The CF
 * @param userTransaction The UT
 * @param enlist Enlistment
 * @param primary Primary worker
 * @param step1 Step 1 trigger
 * @param step2 Step 2 trigger
 * @param step3 Step 3 trigger
 * @param step4 Step 4 trigger
 * @param done Done trigger
 */
public Worker(LazyConnectionFactory connectionFactory, UserTransaction userTransaction,
              boolean enlist, boolean primary,
              CountDownLatch step1, CountDownLatch step2, CountDownLatch step3, CountDownLatch step4,
              CountDownLatch done)
{
   this.throwable = null;
   this.connectionFactory = connectionFactory;
   this.userTransaction = userTransaction;
   this.enlist = enlist;
   this.primary = primary;
   this.step1 = step1;
   this.step2 = step2;
   this.step3 = step3;
   this.step4 = step4;
   this.done = done;
}
 
Example #19
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithDoubleRollback() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition());
	assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	// first rollback
	ptm.rollback(status);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		// second rollback attempt
		ptm.rollback(status);
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}

	verify(ut).begin();
	verify(ut).rollback();
}
 
Example #20
Source File: UserTransactionFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
    // get the transaction manager
    final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
    if (transactionManager == null) {
        throw new NamingException("transaction manager not found");
    }

    // if transaction manager implements user transaction we are done
    if (transactionManager instanceof UserTransaction) {
        return transactionManager;
    }

    // wrap transaction manager with user transaction
    return new CoreUserTransaction(transactionManager);
}
 
Example #21
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testIndexOnCommitForDestroy() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.destroy(x);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #22
Source File: FTPAuthenticatorBase.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check if the user is an administrator user name
 * 
 * @param cInfo ClientInfo
 */
protected final void checkForAdminUserName(ClientInfo cInfo) {
	
	// Check if the user name is an administrator

	UserTransaction tx = getTransactionService().getUserTransaction();

	try {
		tx.begin();

		if ( cInfo.getLogonType() == ClientInfo.LogonNormal && getAuthorityService().isAdminAuthority(cInfo.getUserName())) {
			
			// Indicate that this is an administrator logon

			cInfo.setLogonType(ClientInfo.LogonAdmin);
		}
		tx.commit();
	}
	catch (Throwable ex) {
		try {
			tx.rollback();
		}
		catch (Throwable ex2) {
			logger.error("Failed to rollback transaction", ex2);
		}

		// Re-throw the exception

		if ( ex instanceof RuntimeException) {
			throw (RuntimeException) ex;
		}
		else {
			throw new RuntimeException("Error during execution of transaction.", ex);
		}
	}
}
 
Example #23
Source File: ConfigurableJtaPlatform.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new ConfigurableJtaPlatform instance with the given
 * JTA TransactionManager and optionally a given UserTransaction.
 * @param tm the JTA TransactionManager reference (required)
 * @param ut the JTA UserTransaction reference (optional)
 * @param tsr the JTA 1.1 TransactionSynchronizationRegistry (optional)
 */
public ConfigurableJtaPlatform(TransactionManager tm, @Nullable UserTransaction ut,
		@Nullable TransactionSynchronizationRegistry tsr) {

	Assert.notNull(tm, "TransactionManager reference must not be null");
	this.transactionManager = tm;
	this.userTransaction = (ut != null ? ut : new UserTransactionAdapter(tm));
	this.transactionSynchronizationRegistry = tsr;
}
 
Example #24
Source File: JtaTransactionManagerSerializationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void serializable() throws Exception {
	UserTransaction ut1 = mock(UserTransaction.class);
	UserTransaction ut2 = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);

	JtaTransactionManager jtam = new JtaTransactionManager();
	jtam.setUserTransaction(ut1);
	jtam.setTransactionManager(tm);
	jtam.setRollbackOnCommitFailure(true);
	jtam.afterPropertiesSet();

	SimpleNamingContextBuilder jndiEnv = SimpleNamingContextBuilder
			.emptyActivatedContextBuilder();
	jndiEnv.bind(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, ut2);
	JtaTransactionManager serializedJtatm = (JtaTransactionManager) SerializationTestUtils
			.serializeAndDeserialize(jtam);

	// should do client-side lookup
	assertNotNull("Logger must survive serialization",
			serializedJtatm.logger);
	assertTrue("UserTransaction looked up on client", serializedJtatm
			.getUserTransaction() == ut2);
	assertNull("TransactionManager didn't survive", serializedJtatm
			.getTransactionManager());
	assertEquals(true, serializedJtatm.isRollbackOnCommitFailure());
}
 
Example #25
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the JTA TransactionManager through autodetection: checking whether the
 * UserTransaction object implements the TransactionManager, and checking the
 * fallback JNDI locations.
 * @param ut the JTA UserTransaction object
 * @return the JTA TransactionManager reference, or {@code null} if not found
 * @see #FALLBACK_TRANSACTION_MANAGER_NAMES
 */
protected TransactionManager findTransactionManager(UserTransaction ut) {
	if (ut instanceof TransactionManager) {
		if (logger.isDebugEnabled()) {
			logger.debug("JTA UserTransaction object [" + ut + "] implements TransactionManager");
		}
		return (TransactionManager) ut;
	}

	// Check fallback JNDI locations.
	for (String jndiName : FALLBACK_TRANSACTION_MANAGER_NAMES) {
		try {
			TransactionManager tm = getJndiTemplate().lookup(jndiName, TransactionManager.class);
			if (logger.isDebugEnabled()) {
				logger.debug("JTA TransactionManager found at fallback JNDI location [" + jndiName + "]");
			}
			return tm;
		}
		catch (NamingException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No JTA TransactionManager found at fallback JNDI location [" + jndiName + "]", ex);
			}
		}
	}

	// OK, so no JTA TransactionManager is available...
	return null;
}
 
Example #26
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollback() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);
	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setTimeout(10);
	tt.setName("txName");

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			assertEquals("txName", TransactionSynchronizationManager.getCurrentTransactionName());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut).rollback();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
 
Example #27
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);
	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	tt.setTimeout(10);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut).rollback();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
 
Example #28
Source File: JtaTransactionHelper.java    From snakerflow with Apache License 2.0 5 votes vote down vote up
public static int getUserTransactionStatus(UserTransaction userTransaction) {
	int status = -1;
	try {
		status = userTransaction.getStatus();
	} catch (SystemException e) {
		throw new SnakerException("无法获取事务状态:" + e.getMessage(), e);
	}
	return status;
}
 
Example #29
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);
	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	tt.setTimeout(10);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut).rollback();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
 
Example #30
Source File: JtaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Find the JTA TransactionManager through autodetection: checking whether the
 * UserTransaction object implements the TransactionManager, and checking the
 * fallback JNDI locations.
 * @param ut the JTA UserTransaction object
 * @return the JTA TransactionManager reference, or {@code null} if not found
 * @see #FALLBACK_TRANSACTION_MANAGER_NAMES
 */
protected TransactionManager findTransactionManager(UserTransaction ut) {
	if (ut instanceof TransactionManager) {
		if (logger.isDebugEnabled()) {
			logger.debug("JTA UserTransaction object [" + ut + "] implements TransactionManager");
		}
		return (TransactionManager) ut;
	}

	// Check fallback JNDI locations.
	for (String jndiName : FALLBACK_TRANSACTION_MANAGER_NAMES) {
		try {
			TransactionManager tm = getJndiTemplate().lookup(jndiName, TransactionManager.class);
			if (logger.isDebugEnabled()) {
				logger.debug("JTA TransactionManager found at fallback JNDI location [" + jndiName + "]");
			}
			return tm;
		}
		catch (NamingException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No JTA TransactionManager found at fallback JNDI location [" + jndiName + "]", ex);
			}
		}
	}

	// OK, so no JTA TransactionManager is available...
	return null;
}