javax.transaction.TransactionManager Java Examples

The following examples show how to use javax.transaction.TransactionManager. 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: EclipseLinkOSGiTransactionController.java    From lb-karaf-examples-jpa with Apache License 2.0 6 votes vote down vote up
@Override
protected TransactionManager acquireTransactionManager() throws Exception {
    Bundle bundle = FrameworkUtil.getBundle(EclipseLinkOSGiTransactionController.class);
    BundleContext ctx = bundle.getBundleContext();

    if (ctx != null) {
        ServiceReference<?> ref = ctx.getServiceReference(TransactionManager.class.getName());

        if (ref != null) {
            TransactionManager manager = (TransactionManager) ctx.getService(ref);
            return manager;
        }
    }

    return super.acquireTransactionManager();
}
 
Example #2
Source File: TransactionIntegrationImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor
 * @param tm The transaction manager
 * @param tsr The transaction synchronization registry
 * @param utr The user transaction registry
 * @param terminator The XA terminator
 * @param rr The recovery registry
 */
public TransactionIntegrationImpl(TransactionManager tm,
                                  TransactionSynchronizationRegistry tsr,
                                  org.jboss.tm.usertx.UserTransactionRegistry utr,
                                  org.jboss.tm.JBossXATerminator terminator,
                                  org.jboss.tm.XAResourceRecoveryRegistry rr)
{
   if (tm instanceof org.jboss.tm.TransactionTimeoutConfiguration)
   {
      this.tm = new TransactionManagerDelegator(tm);
   }
   else
   {
      this.tm = tm;
   }
   this.tsr = tsr;
   this.utr = new UserTransactionRegistryImpl(utr);
   this.terminator = terminator;
   this.rr = rr;
}
 
Example #3
Source File: TestBasicManagedDataSource.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
/** DBCP-564 */
@Test
public void testSetRollbackOnlyBeforeGetConnectionDoesNotLeak() throws Exception {
    final TransactionManager transactionManager = ((BasicManagedDataSource) ds).getTransactionManager();
    final int n = 3;
    ds.setMaxIdle(n);
    ds.setMaxTotal(n);

    for (int i = 0; i <= n; i++) { // loop n+1 times
        transactionManager.begin();
        transactionManager.setRollbackOnly();
        final Connection conn = getConnection();
        assertNotNull(conn);
        conn.close();
        transactionManager.rollback();
    }

    assertEquals(0, ds.getNumActive());
    assertEquals(1, ds.getNumIdle());
}
 
Example #4
Source File: SecurityInvocationHandlerTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    sessionContext = new TestSessionContext(null, null);
    callable = new Callable<Object>() {
        @Override
        public Void call() throws Exception {
            return null;
        }
    };
    ctx = new IInvocationCtx() {
        @Override
        public TransactionManager getTransactionManager() {
            return null;
        }

        @Override
        public boolean isApplicationException(Exception e) {
            return false;
        }
    };
}
 
Example #5
Source File: JtaExtension.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
void init(@Observes final AfterDeploymentValidation afterDeploymentValidation, final BeanManager bm) {
    if (!hasRegistry && hasManager) {
        afterDeploymentValidation.addDeploymentProblem(new IllegalStateException("You should produce a TransactionManager and TransactionSynchronizationRegistry"));
        return;
    }
    final TransactionManager manager = TransactionManager.class.cast(
            bm.getReference(bm.resolve(bm.getBeans(TransactionManager.class)), TransactionManager.class, bm.createCreationalContext(null)));
    final TransactionSynchronizationRegistry registry = TransactionSynchronizationRegistry.class.isInstance(manager) ?
            TransactionSynchronizationRegistry.class.cast(manager) :
            TransactionSynchronizationRegistry.class.cast(bm.getReference(bm.resolve(bm.getBeans(TransactionSynchronizationRegistry.class)),
                    TransactionSynchronizationRegistry.class, bm.createCreationalContext(null)));
    context.init(manager, registry);

    try {
        final Class<?> builder = Thread.currentThread().getContextClassLoader().loadClass("org.apache.meecrowave.Meecrowave$Builder");
        final JtaConfig ext = JtaConfig.class.cast(builder.getMethod("getExtension", Class.class).invoke(
                bm.getReference(bm.resolve(bm.getBeans(builder)), builder, bm.createCreationalContext(null)), JtaConfig.class));
        config.handleExceptionOnlyForClient = ext.handleExceptionOnlyForClient;
    } catch (final Exception e) {
        config.handleExceptionOnlyForClient = Boolean.getBoolean("meecrowave.jta.handleExceptionOnlyForClient");
    }
}
 
Example #6
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetJtaTransactionManager() throws Exception {
	DataSource ds = mock(DataSource.class);
	TransactionManager tm = mock(TransactionManager.class);
	UserTransaction ut = mock(UserTransaction.class);
	TransactionSynchronizationRegistry tsr = mock(TransactionSynchronizationRegistry.class);
	JtaTransactionManager jtm = new JtaTransactionManager();
	jtm.setTransactionManager(tm);
	jtm.setUserTransaction(ut);
	jtm.setTransactionSynchronizationRegistry(tsr);
	LocalSessionFactoryBuilder lsfb = new LocalSessionFactoryBuilder(ds);
	lsfb.setJtaTransactionManager(jtm);
	Object jtaPlatform = lsfb.getProperties().get(AvailableSettings.JTA_PLATFORM);
	assertNotNull(jtaPlatform);
	assertSame(tm, jtaPlatform.getClass().getMethod("retrieveTransactionManager").invoke(jtaPlatform));
	assertSame(ut, jtaPlatform.getClass().getMethod("retrieveUserTransaction").invoke(jtaPlatform));
	assertTrue(lsfb.getProperties().get(AvailableSettings.TRANSACTION_STRATEGY) instanceof CMTTransactionFactory);
}
 
Example #7
Source File: JMSConfigFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static TransactionManager getTransactionManager(Bus bus, JMSEndpoint endpoint) {
    String tmName = endpoint.getJndiTransactionManagerName();
    TransactionManager tm = null;
    ConfiguredBeanLocator locator = bus.getExtension(ConfiguredBeanLocator.class);
    if (tmName != null) {
        if (locator != null) {
            tm = locator.getBeanOfType(tmName, TransactionManager.class);
        }
        if (tm == null) {
            tm = getTransactionManagerFromJndi(tmName);
        }

    }
    if (tm == null && locator != null) {
        Collection<? extends TransactionManager> tms = locator.getBeansOfType(TransactionManager.class);
        if (tms.size() == 1) {
            tm = tms.iterator().next();
        }
    }
    return tm;
}
 
Example #8
Source File: JpaTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
public void testJta() throws Exception {
    transactionType = PersistenceUnitTransactionType.JTA;
    entityManagerFactory = createEntityManagerFactory();

    final Object jpaTestObject = getClass().getClassLoader().loadClass("org.apache.openejb.core.cmp.jpa.JpaTestObject").newInstance();
    set(jpaTestObject, "EntityManagerFactory", EntityManagerFactory.class, entityManagerFactory);
    set(jpaTestObject, "TransactionManager", TransactionManager.class, transactionManager);
    set(jpaTestObject, "NonJtaDs", DataSource.class, nonJtaDs);

    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    invoke(jpaTestObject, "setUp");
    try {
        invoke(jpaTestObject, "jpaLifecycle");
    } finally {
        invoke(jpaTestObject, "tearDown");
    }
}
 
Example #9
Source File: TransactionalService.java    From tutorials with MIT License 6 votes vote down vote up
public Integer getQuickHowManyVisits() {
    try {
        TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
        tm.begin();
        Integer howManyVisits = transactionalCache.get(KEY);
        howManyVisits++;
        System.out.println("Ill try to set HowManyVisits to " + howManyVisits);
        StopWatch watch = new StopWatch();
        watch.start();
        transactionalCache.put(KEY, howManyVisits);
        watch.stop();
        System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds");

        tm.commit();
        return howManyVisits;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}
 
Example #10
Source File: DefaultKeycloakTransactionManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void begin() {
    if (active) {
         throw new IllegalStateException("Transaction already active");
    }

    completed = false;

    if (jtaPolicy == JTAPolicy.REQUIRES_NEW) {
        JtaTransactionManagerLookup jtaLookup = session.getProvider(JtaTransactionManagerLookup.class);
        if (jtaLookup != null) {
            TransactionManager tm = jtaLookup.getTransactionManager();
            if (tm != null) {
               enlist(new JtaTransactionWrapper(session.getKeycloakSessionFactory(), tm));
            }
        }
    }

    for (KeycloakTransaction tx : transactions) {
        tx.begin();
    }

    active = true;
}
 
Example #11
Source File: SpringSessionContext.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new SpringSessionContext for the given Hibernate SessionFactory.
 * @param sessionFactory the SessionFactory to provide current Sessions for
 */
public SpringSessionContext(SessionFactoryImplementor sessionFactory) {
	this.sessionFactory = sessionFactory;
	try {
		Object jtaPlatform = sessionFactory.getServiceRegistry().getService(ConfigurableJtaPlatform.jtaPlatformClass);
		Method rtmMethod = ConfigurableJtaPlatform.jtaPlatformClass.getMethod("retrieveTransactionManager");
		this.transactionManager = (TransactionManager) ReflectionUtils.invokeMethod(rtmMethod, jtaPlatform);
		if (this.transactionManager != null) {
			this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory);
		}
	}
	catch (Exception ex) {
		LogFactory.getLog(SpringSessionContext.class).warn(
				"Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex);
	}
}
 
Example #12
Source File: JtaTransactionManager.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
protected TransactionManager getTransactionManager(TransactionLogger transactionLogger, UserTransaction ut) {
    if (ut instanceof TransactionManager) {
        transactionLogger.log("JTA UserTransaction object [{}] implements TransactionManager", ut);
        return (TransactionManager) ut;
    }

    if (jtaConfig.getTxManagerName() != null) {
        try {
            return (TransactionManager) jndiContext.lookup(jtaConfig.getTxManagerName());
        } catch (NamingException e) {
            throw SeedException.wrap(e, TransactionErrorCode.UNABLE_TO_FIND_JTA_TRANSACTION_MANAGER);
        }
    }

    for (String jndiName : AUTODETECT_TRANSACTION_MANAGER_NAMES) {
        try {
            TransactionManager tm = (TransactionManager) jndiContext.lookup(jndiName);
            transactionLogger.log("JTA TransactionManager found at JNDI location [{}]", jndiName);
            return tm;
        } catch (NamingException ex) {
            transactionLogger.log("No JTA TransactionManager found at JNDI location [{}]", jndiName, ex);
        }
    }

    return null;
}
 
Example #13
Source File: DSSXATransactionManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public void commit() throws DataServiceFault {
	TransactionManager txManager = getTransactionManager();
	if (txManager == null) {
           return;
       }
	try {
		if (log.isDebugEnabled()) {
			log.debug("transactionManager.commit()");
		}
		txManager.commit();			
	} catch (Exception e) {
		throw new DataServiceFault(e,
				"Error from transaction manager when committing: " + e.getMessage());
	} finally {
		this.beginTx.set(false);
	}
}
 
Example #14
Source File: BuiltInEnvironmentEntries.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void add(final JndiConsumer jndi, final DeploymentModule module, final DeploymentModule app, final boolean defaults) {

        // Standard names
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:module/ModuleName").value(module.getModuleId()).type(String.class));
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:app/AppName").value(app.getModuleId()).type(String.class));

        // Standard References to built-in objects
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/BeanManager").type(BeanManager.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/Validator").type(Validator.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/ValidatorFactory").type(ValidatorFactory.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/TransactionManager").type(TransactionManager.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/TransactionSynchronizationRegistry").type(TransactionSynchronizationRegistry.class));

        if (defaults) {
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedExecutorService").type(ManagedExecutorService.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedScheduledExecutorService").type(ManagedScheduledExecutorService.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedThreadFactory").type(ManagedThreadFactory.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultContextService").type(ContextService.class));
            try {
                final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                contextClassLoader.loadClass("org.apache.activemq.ActiveMQSslConnectionFactory");
                final ResourceEnvRef ref = new ResourceEnvRef().name("java:comp/DefaultJMSConnectionFactory")
                    .type(contextClassLoader.loadClass("javax.jms.ConnectionFactory"));
                add(jndi.getResourceEnvRefMap(), ref);
            } catch (final ClassNotFoundException | NoClassDefFoundError notThere) {
                // no-op
            }
        }


        // OpenEJB specific feature
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:comp/ComponentName").value(jndi.getJndiConsumerName()).type(String.class));

    }
 
Example #15
Source File: DataSourceJtaTransactionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	connection =mock(Connection.class);
	dataSource = mock(DataSource.class);
	userTransaction = mock(UserTransaction.class);
	transactionManager = mock(TransactionManager.class);
	transaction = mock(Transaction.class);
	given(dataSource.getConnection()).willReturn(connection);
}
 
Example #16
Source File: JBossJtaTransactionManagerLookup.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config.Scope config) {
    try {
        InitialContext ctx = new InitialContext();
        tm = (TransactionManager)ctx.lookup("java:jboss/TransactionManager");
        if (tm == null) {
            logger.debug("Could not locate TransactionManager");
        }
    } catch (NamingException e) {
        logger.debug("Could not load TransactionManager", e);
    }

}
 
Example #17
Source File: JOTMTransactionManagerLookup.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @see org.hibernate.transaction.TransactionManagerLookup#getTransactionManager(Properties)
 */
public TransactionManager getTransactionManager(Properties props) throws HibernateException {
	try {
		Class clazz = Class.forName("org.objectweb.jotm.Current");
		return (TransactionManager) clazz.getMethod("getTransactionManager", null).invoke(null, null);
	}
	catch (Exception e) {
		throw new HibernateException( "Could not obtain JOTM transaction manager instance", e );
	}
}
 
Example #18
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 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
 */
@Nullable
protected TransactionManager findTransactionManager(@Nullable 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 #19
Source File: LocalSessionFactoryBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Set the Spring {@link JtaTransactionManager} or the JTA {@link TransactionManager}
 * to be used with Hibernate, if any. Allows for using a Spring-managed transaction
 * manager for Hibernate 4's session and cache synchronization, with the
 * "hibernate.transaction.jta.platform" automatically set to it. Also sets
 * "hibernate.transaction.factory_class" to {@link CMTTransactionFactory},
 * instructing Hibernate to interact with externally managed transactions.
 * <p>A passed-in Spring {@link JtaTransactionManager} needs to contain a JTA
 * {@link TransactionManager} reference to be usable here, except for the WebSphere
 * case where we'll automatically set {@code WebSphereExtendedJtaPlatform} accordingly.
 * <p>Note: If this is set, the Hibernate settings should not contain a JTA platform
 * setting to avoid meaningless double configuration.
 */
public LocalSessionFactoryBuilder setJtaTransactionManager(Object jtaTransactionManager) {
	Assert.notNull(jtaTransactionManager, "Transaction manager reference must not be null");
	if (jtaTransactionManager instanceof JtaTransactionManager) {
		boolean webspherePresent = ClassUtils.isPresent("com.ibm.wsspi.uow.UOWManager", getClass().getClassLoader());
		if (webspherePresent) {
			getProperties().put(AvailableSettings.JTA_PLATFORM,
					ConfigurableJtaPlatform.getJtaPlatformBasePackage() + "internal.WebSphereExtendedJtaPlatform");
		}
		else {
			JtaTransactionManager jtaTm = (JtaTransactionManager) jtaTransactionManager;
			if (jtaTm.getTransactionManager() == null) {
				throw new IllegalArgumentException(
						"Can only apply JtaTransactionManager which has a TransactionManager reference set");
			}
			getProperties().put(AvailableSettings.JTA_PLATFORM,
					new ConfigurableJtaPlatform(jtaTm.getTransactionManager(), jtaTm.getUserTransaction(),
							jtaTm.getTransactionSynchronizationRegistry()).getJtaPlatformProxy());
		}
	}
	else if (jtaTransactionManager instanceof TransactionManager) {
		getProperties().put(AvailableSettings.JTA_PLATFORM,
				new ConfigurableJtaPlatform((TransactionManager) jtaTransactionManager, null, null).getJtaPlatformProxy());
	}
	else {
		throw new IllegalArgumentException(
				"Unknown transaction manager type: " + jtaTransactionManager.getClass().getName());
	}
	getProperties().put(AvailableSettings.TRANSACTION_STRATEGY, new CMTTransactionFactory());
	return this;
}
 
Example #20
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a UserTransaction handle based on the given TransactionManager.
 * @param transactionManager the TransactionManager
 * @return a corresponding UserTransaction handle
 */
protected UserTransaction buildUserTransaction(TransactionManager transactionManager) {
	if (transactionManager instanceof UserTransaction) {
		return (UserTransaction) transactionManager;
	}
	else {
		return new UserTransactionAdapter(transactionManager);
	}
}
 
Example #21
Source File: JMSConfigFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void tmByName(Bus bus, TransactionManager tmExpected) {
    JMSEndpoint endpoint = new JMSEndpoint("jms:queue:Foo.Bar?jndiTransactionManagerName=tm");
    Assert.assertEquals("tm", endpoint.getJndiTransactionManagerName());
    JMSConfiguration jmsConfig = JMSConfigFactory.createFromEndpoint(bus, endpoint);
    TransactionManager tm = jmsConfig.getTransactionManager();
    Assert.assertEquals(tmExpected, tm);
}
 
Example #22
Source File: TransactionManagerFactoryBeanTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testGetObject_Null() throws Exception {
    Jta.configure(null, null);
    TransactionManager transactionManager = transactionManagerFactoryBean.getObject();

    // should not be null, but should be a proxy to a non-existent transaction manager
    assertNotNull(transactionManager);
    assertTrue(Proxy.isProxyClass(transactionManager.getClass()));

    try {
        transactionManager.getTransaction();
        fail("IllegalStateException should have been thrown");
    } catch (IllegalStateException e) {}
}
 
Example #23
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 #24
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new JtaTransactionManager instance.
 * @param userTransaction the JTA UserTransaction to use as direct reference
 * @param transactionManager the JTA TransactionManager to use as direct reference
 */
public JtaTransactionManager(UserTransaction userTransaction, TransactionManager transactionManager) {
	this();
	Assert.notNull(userTransaction, "UserTransaction must not be null");
	Assert.notNull(transactionManager, "TransactionManager must not be null");
	this.userTransaction = userTransaction;
	this.transactionManager = transactionManager;
}
 
Example #25
Source File: JtaTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Look up the JTA TransactionManager in JNDI via the configured name.
 * <p>Called by {@code afterPropertiesSet} if no direct TransactionManager reference was set.
 * Can be overridden in subclasses to provide a different TransactionManager object.
 * @param transactionManagerName the JNDI name of the TransactionManager
 * @return the UserTransaction object
 * @throws TransactionSystemException if the JNDI lookup failed
 * @see #setJndiTemplate
 * @see #setTransactionManagerName
 */
protected TransactionManager lookupTransactionManager(String transactionManagerName)
		throws TransactionSystemException {
	try {
		if (logger.isDebugEnabled()) {
			logger.debug("Retrieving JTA TransactionManager from JNDI location [" + transactionManagerName + "]");
		}
		return getJndiTemplate().lookup(transactionManagerName, TransactionManager.class);
	}
	catch (NamingException ex) {
		throw new TransactionSystemException(
				"JTA TransactionManager is not available at JNDI location [" + transactionManagerName + "]", ex);
	}
}
 
Example #26
Source File: DataSourceJtaTransactionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	connection =mock(Connection.class);
	dataSource = mock(DataSource.class);
	userTransaction = mock(UserTransaction.class);
	transactionManager = mock(TransactionManager.class);
	transaction = mock(Transaction.class);
	given(dataSource.getConnection()).willReturn(connection);
}
 
Example #27
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobSerializableTypeWithJtaSynchronizationAndRollback() throws Exception {
	TransactionManager tm = mock(TransactionManager.class);
	MockJtaTransaction transaction = new MockJtaTransaction();
	given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.getTransaction()).willReturn(transaction);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(baos);
	oos.writeObject("content");
	oos.close();

	given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(
			new ByteArrayInputStream(baos.toByteArray()));

	BlobSerializableType type = new BlobSerializableType(lobHandler, tm);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(Serializable.class, type.returnedClass());
	assertTrue(type.isMutable());

	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).setBlobAsBytes(ps, 1, baos.toByteArray());
}
 
Example #28
Source File: SimpleDataSourceCreator.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource managed(final String name, final CommonDataSource ds) {
    final TransactionManager transactionManager = OpenEJB.getTransactionManager();
    if (XADataSource.class.isInstance(ds)) {
        return new ManagedXADataSource(XADataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    }
    return new ManagedDataSource(DataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
 
Example #29
Source File: JtaTransactionController.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected TransactionManager acquireTransactionManager() throws Exception {
    if (!Jta.isEnabled()) {
        throw new IllegalStateException("Attempting to use EclipseLink with JTA, but JTA is not configured properly"
                + "for this KRAD application!");
    }
    return Jta.getTransactionManager();
}
 
Example #30
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);
	willThrow(new SystemException()).given(ut).begin();

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	verify(tm).resume(tx);
}