@Test public void test_RollbackExceptionHandling_rollbackafterthrown() throws Exception { TransactionManager tm = mockTm(); when(tm.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_MARKED_ROLLBACK); doThrow(new RollbackException().initCause(new OptimisticLockException())).when(tm).commit(); XAJpaTemplate tx = new XAJpaTemplate(emSupplier, tm, coordinator); try { tx.tx(TransactionType.Required, new EmConsumer() { public void accept(EntityManager em) { em.persist(new Object()); } }); } catch (RuntimeException e) { // this is ok } verify(tm, times(5)).getStatus(); verify(tm, times(1)).commit(); verify(tm, times(1)).rollback(); }
@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; } }; }
@Bean(name = "dataSource") public DataSource getDataSource(@Autowired XADataSource xaDataSource, @Autowired TransactionManager transactionManager) { BasicManagedDataSource bds = new BasicManagedDataSource(); bds.setXaDataSourceInstance(xaDataSource); bds.setTransactionManager(transactionManager); bds.setMaxTotal(50); bds.setInitialSize(20); bds.setMaxWaitMillis(60000); bds.setMinIdle(6); bds.setLogAbandoned(true); bds.setRemoveAbandonedOnBorrow(true); bds.setRemoveAbandonedOnMaintenance(true); bds.setRemoveAbandonedTimeout(1800); bds.setTestWhileIdle(true); bds.setTestOnBorrow(false); bds.setTestOnReturn(false); bds.setValidationQuery("select 'x' "); bds.setValidationQueryTimeout(1); bds.setTimeBetweenEvictionRunsMillis(30000); bds.setNumTestsPerEvictionRun(20); return bds; }
@Before public void setup() { sessionContext = new TestSessionContext(null, null); callable = new Callable<Object>() { @Override public Void call() { return null; } }; ctx = new IInvocationCtx() { @Override public TransactionManager getTransactionManager() { return null; } @Override public boolean isApplicationException(Exception e) { return false; } }; }
@Test @DisplayName( "Multiple close test" ) public void multipleCloseTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { // there is a call to connection#close in the try-with-resources block and another on the callback from the transaction#commit() try ( Connection connection = dataSource.getConnection() ) { logger.info( format( "Got connection {0}", connection ) ); try { txManager.begin(); txManager.commit(); } catch ( NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e ) { fail( "Exception: " + e.getMessage() ); } } } }
private void connect() throws HibernateException { if (!isCurrentTransaction) { //if there is no current transaction callback registered //when we obtain the connection, try to register one now //note that this is not going to handle the case of //multiple-transactions-per-connection when the user is //manipulating transactions (need to use Hibernate txn) TransactionManager tm = factory.getTransactionManager(); if (tm!=null) { try { javax.transaction.Transaction tx = tm.getTransaction(); if ( isJTATransactionActive(tx) ) { tx.registerSynchronization( new CacheSynchronization(this) ); isCurrentTransaction = true; } } catch (Exception e) { throw new TransactionException("could not register synchronization with JTA TransactionManager", e); } } } connection = batcher.openConnection(); connect = false; }
public SpringSessionSynchronization( SessionHolder sessionHolder, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) { this.sessionHolder = sessionHolder; this.sessionFactory = sessionFactory; this.jdbcExceptionTranslator = jdbcExceptionTranslator; this.newSession = newSession; // Check whether the SessionFactory has a JTA TransactionManager. TransactionManager jtaTm = SessionFactoryUtils.getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession()); if (jtaTm != null) { this.hibernateTransactionCompletion = true; // Fetch current JTA Transaction object // (just necessary for JTA transaction suspension, with an individual // Hibernate Session per currently active/suspended transaction). try { this.jtaTransaction = jtaTm.getTransaction(); } catch (SystemException ex) { throw new DataAccessResourceFailureException("Could not access JTA transaction", ex); } } }
@Bean(name = "mybatisDataSource") public DataSource getDataSource(@Autowired XADataSource xaDataSource, @Autowired TransactionManager transactionManager) { BasicManagedDataSource bds = new BasicManagedDataSource(); bds.setXaDataSourceInstance(xaDataSource); bds.setTransactionManager(transactionManager); bds.setMaxTotal(50); bds.setInitialSize(20); bds.setMaxWaitMillis(60000); bds.setMinIdle(6); bds.setLogAbandoned(true); bds.setRemoveAbandonedOnBorrow(true); bds.setRemoveAbandonedOnMaintenance(true); bds.setRemoveAbandonedTimeout(1800); bds.setTestWhileIdle(true); bds.setTestOnBorrow(false); bds.setTestOnReturn(false); bds.setValidationQuery("select 'x' "); bds.setValidationQueryTimeout(1); bds.setTimeBetweenEvictionRunsMillis(30000); bds.setNumTestsPerEvictionRun(20); return bds; }
@Test public void testBug46169() throws Exception { String tableName = CacheUtils.init("CacheTest"); assertFalse(tableName == null || tableName.equals("")); logger.debug("Table name: " + tableName); logger.debug("init for bug46169 Successful!"); Cache cache = CacheUtils.getCache(); TransactionManager xmanager = (TransactionManager) cache.getJNDIContext().lookup("java:/TransactionManager"); assertNotNull(xmanager); Transaction trans = xmanager.suspend(); assertNull(trans); try { logger.debug("Destroying table: " + tableName); CacheUtils.destroyTable(tableName); logger.debug("Closing cache..."); logger.debug("destroyTable for bug46169 Successful!"); } finally { CacheUtils.closeCache(); } }
@Test @DisplayName( "Basic rollback test" ) public void basicRollbackTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { txManager.begin(); Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); txManager.rollback(); assertTrue( connection.isClosed() ); } catch ( NotSupportedException | SystemException e ) { fail( "Exception: " + e.getMessage() ); } }
@Test @DisplayName( "Connection outside the scope of a transaction test" ) public void connectionOutsideTransactionTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); connection.close(); assertTrue( connection.isClosed() ); } }
public TestEEfiJtaPlatform( final TransactionManager transactionManager, final TransactionServices transactionServices ) { this.transactionManager = transactionManager; this.transactionServices = transactionServices; }
@Override public void removedService(ServiceReference<TransactionManager> reference, ServiceRegistration reg) { try { reg.unregister(); context.ungetService(reference); } catch (Exception e) { LOG.debug("Exception during unregister", e); } }
@Test public void test_RollbackExceptionHandling_rollbackiscalledonmarkedrollback() throws Exception { TransactionManager tm = mockTm(); when(tm.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_MARKED_ROLLBACK); XAJpaTemplate tx = new XAJpaTemplate(emSupplier, tm, coordinator); tx.tx(TransactionType.Required, new EmConsumer() { public void accept(EntityManager em) { em.persist(new Object()); } }); verify(tm, times(3)).getStatus(); verify(tm, never()).commit(); verify(tm, times(1)).rollback(); }
@Override public TransactionManager create() { TransactionManager transactionManager = null; ApplicationServer as = ApplicationServer.currentApplicationServer(); if ( as == ApplicationServer.WEBSPHERE ) { transactionManager = DelegatingTransactionManager.transactionManager(); } else { transactionManager = platform.retrieveTransactionManager(); } return transactionManager; }
/** * Atomikos transaction manager. * @return atomikos transaction manager */ @Bean(initMethod = "init", destroyMethod = "close") public TransactionManager atomikosTransactionManager() { final UserTransactionManager userTransactionManager = new UserTransactionManager(); userTransactionManager.setForceShutdown(false); return userTransactionManager; }
public void init() throws Exception { List<String> clazzes = new ArrayList<>(); clazzes.add(TransactionManager.class.getName()); clazzes.add(TransactionSynchronizationRegistry.class.getName()); clazzes.add(UserTransaction.class.getName()); clazzes.add(RecoverableTransactionManager.class.getName()); if (useSpring) { clazzes.add(PLATFORM_TRANSACTION_MANAGER_CLASS); } String[] ifar = clazzes.toArray(new String[clazzes.size()]); serviceRegistration = bundleContext.registerService(ifar, transactionManager, null); wrapperRegistration = bundleContext.registerService(org.ops4j.pax.transx.tm.TransactionManager.class, new TransactionManagerWrapper(transactionManager), null); }
/** * 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; }
/** * Create a new JtaTransactionManager instance. * @param transactionManager the JTA TransactionManager to use as direct reference */ public JtaTransactionManager(TransactionManager transactionManager) { this(); Assert.notNull(transactionManager, "TransactionManager must not be null"); this.transactionManager = transactionManager; this.userTransaction = buildUserTransaction(transactionManager); }
/** * 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); } }
/** * 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); } }
/** * 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; }
/** * Find the JTA 1.1 TransactionSynchronizationRegistry through autodetection: * checking whether the UserTransaction object or TransactionManager object * implements it, and checking Java EE 5's standard JNDI location. * <p>The default implementation simply returns {@code null}. * @param ut the JTA UserTransaction object * @param tm the JTA TransactionManager object * @return the JTA TransactionSynchronizationRegistry handle to use, * or {@code null} if none found * @throws TransactionSystemException in case of errors */ protected TransactionSynchronizationRegistry findTransactionSynchronizationRegistry(UserTransaction ut, TransactionManager tm) throws TransactionSystemException { if (this.userTransactionObtainedFromJndi) { // UserTransaction has already been obtained from JNDI, so the // TransactionSynchronizationRegistry probably sits there as well. String jndiName = DEFAULT_TRANSACTION_SYNCHRONIZATION_REGISTRY_NAME; try { TransactionSynchronizationRegistry tsr = getJndiTemplate().lookup(jndiName, TransactionSynchronizationRegistry.class); if (logger.isDebugEnabled()) { logger.debug("JTA TransactionSynchronizationRegistry found at default JNDI location [" + jndiName + "]"); } return tsr; } catch (NamingException ex) { if (logger.isDebugEnabled()) { logger.debug( "No JTA TransactionSynchronizationRegistry found at default JNDI location [" + jndiName + "]", ex); } } } // Check whether the UserTransaction or TransactionManager implements it... if (ut instanceof TransactionSynchronizationRegistry) { return (TransactionSynchronizationRegistry) ut; } if (tm instanceof TransactionSynchronizationRegistry) { return (TransactionSynchronizationRegistry) tm; } // OK, so no JTA 1.1 TransactionSynchronizationRegistry is available... return null; }
@Override public Transaction createTransaction(String name, int timeout) throws NotSupportedException, SystemException { TransactionManager tm = getTransactionManager(); Assert.state(tm != null, "No JTA TransactionManager available"); if (timeout >= 0) { tm.setTransactionTimeout(timeout); } tm.begin(); return new ManagedTransactionAdapter(tm); }
public static TransactionManager transactionManager() { if ( INSTANCE == null ) { synchronized ( DelegatingTransactionManager.class ) { if ( INSTANCE == null ) { try { TransactionManager delegate = null; final ApplicationServer applicationServer = ApplicationServer.currentApplicationServer(); switch ( applicationServer ) { case WEBSPHERE: delegate = initWebSphereTransactionManager(); break; case JBOSS: delegate = initJBossTransactionManager(); break; default: throw log.unsupportedApplicationServer(); } INSTANCE = new DelegatingTransactionManager( delegate, applicationServer ); } catch ( ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NamingException e ) { throw new HibernateException( "Cannot instantiate TransactionManager", e ); } } } } return INSTANCE; }
/** * Register a transaction synchronization for closing the given LobCreator, * preferring Spring transaction synchronization and falling back to * plain JTA transaction synchronization. * @param lobCreator the LobCreator to close after transaction completion * @param jtaTransactionManager the JTA TransactionManager to fall back to * when no Spring transaction synchronization is active (may be {@code null}) * @throws IllegalStateException if there is neither active Spring transaction * synchronization nor active JTA transaction synchronization */ public static void registerTransactionSynchronization( LobCreator lobCreator, TransactionManager jtaTransactionManager) throws IllegalStateException { if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering Spring transaction synchronization for LobCreator"); TransactionSynchronizationManager.registerSynchronization( new SpringLobCreatorSynchronization(lobCreator)); } else { if (jtaTransactionManager != null) { try { int jtaStatus = jtaTransactionManager.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { logger.debug("Registering JTA transaction synchronization for LobCreator"); jtaTransactionManager.getTransaction().registerSynchronization( new JtaLobCreatorSynchronization(lobCreator)); return; } } catch (Throwable ex) { throw new TransactionSystemException( "Could not register synchronization with JTA TransactionManager", ex); } } throw new IllegalStateException("Active Spring transaction synchronization or active " + "JTA transaction with specified [javax.transaction.TransactionManager] required"); } }
/** * Set the the XA transaction manager to use for wrapping endpoint * invocations, enlisting the endpoint resource in each such transaction. * <p>The passed-in object may be a transaction manager which implements * Spring's {@link org.springframework.transaction.jta.TransactionFactory} * interface, or a plain {@link javax.transaction.TransactionManager}. * <p>If no transaction manager is specified, the endpoint invocation * will simply not be wrapped in an XA transaction. Check out your * resource provider's ActivationSpec documentation for local * transaction options of your particular provider. * @see #setTransactionName * @see #setTransactionTimeout */ public void setTransactionManager(Object transactionManager) { if (transactionManager instanceof TransactionFactory) { this.transactionFactory = (TransactionFactory) transactionManager; } else if (transactionManager instanceof TransactionManager) { this.transactionFactory = new SimpleTransactionFactory((TransactionManager) transactionManager); } else { throw new IllegalArgumentException("Transaction manager [" + transactionManager + "] is neither a [org.springframework.transaction.jta.TransactionFactory} nor a " + "[javax.transaction.TransactionManager]"); } }
/** * 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; }
public LocalTransactionManagerLookup() { TransactionManager tm = LocalSessionFactoryBean.getConfigTimeTransactionManager(); // absolutely needs thread-bound TransactionManager to initialize if (tm == null) { throw new IllegalStateException("No JTA TransactionManager found - " + "'jtaTransactionManager' property must be set on LocalSessionFactoryBean"); } this.transactionManager = tm; }
@Override protected TransactionManager locateTransactionManager() { try { Class transactionManagerServicesClass = serviceRegistry().getService( ClassLoaderService.class ).classForName( TM_CLASS_NAME ); final Method getTransactionManagerMethod = transactionManagerServicesClass.getMethod( "getTransactionManager" ); return (TransactionManager) getTransactionManagerMethod.invoke( null ); } catch (Exception e) { throw new JtaPlatformException( "Could not locate Bitronix TransactionManager", e ); } }
@Override protected TransactionManager locateTransactionManager() { try { final Class clazz = Class.forName( TM_CLASS_NAME ); final Method getTransactionManagerMethod = clazz.getMethod( "getTransactionManager" ); return (TransactionManager) getTransactionManagerMethod.invoke( null ); } catch (Exception e) { throw new JtaPlatformException( "Could not obtain JOnAS transaction manager instance", e ); } }
@Override protected TransactionManager locateTransactionManager() { try { final Class jbossTmClass = serviceRegistry() .getService( ClassLoaderService.class ) .classForName( JBOSS_TM_CLASS_NAME ); return (TransactionManager) jbossTmClass.getMethod( "transactionManager" ).invoke( null ); } catch ( Exception e ) { throw new JtaPlatformException( "Could not obtain JBoss Transactions transaction manager instance", e ); } }
@Override protected TransactionManager locateTransactionManager() { try { return (TransactionManager) jndiService().locate( AS7_TM_NAME ); } catch (JndiException jndiException) { try { return (TransactionManager) jndiService().locate( AS4_TM_NAME ); } catch (JndiException jndiExceptionInner) { throw new JndiException( "unable to find transaction manager", jndiException ); } } }
@Test @DisplayName( "Connection acquire test" ) public void basicConnectionAcquireTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) .connectionFactoryConfiguration( cf -> cf.autoCommit( true ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { txManager.begin(); Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); assertAll( () -> { assertThrows( SQLException.class, () -> connection.setAutoCommit( true ) ); assertFalse( connection.getAutoCommit(), "Expect connection to have autocommit not set" ); // TODO: comparing toString is brittle. Find a better way to make sure the underlying physical connection is the same. assertEquals( connection.toString(), dataSource.getConnection().toString(), "Expect the same connection under the same transaction" ); } ); txManager.commit(); assertTrue( connection.isClosed() ); } catch ( NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e ) { fail( "Exception: " + e.getMessage() ); } }
@Override @SuppressWarnings("unchecked") protected TransactionManager locateTransactionManager() { try { final Method method = transactionManagerAccessClass.getMethod( "getTransactionManager" ); return (TransactionManager) method.invoke( null ); } catch (Exception e) { throw new JtaPlatformException( "Could not obtain WebSphere TransactionManager", e ); } }
@Test @DisplayName( "Lazy enlistment test" ) public void lazyEnlistmentTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); try { txManager.begin(); assertThrows( SQLException.class, connection::createStatement ); logger.info( format( "Call to a method on the connection thrown a SQLException" ) ); txManager.commit(); assertFalse( connection.isClosed(), "Not expecting the connection to be close since it was not enrolled into the transaction" ); } catch ( NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e ) { fail( "Exception: " + e.getMessage() ); } } }
/** * Extract the status code from the current {@link javax.transaction.Transaction} associated with the * given {@link TransactionManager} * * @param transactionManager The {@link TransactionManager} from which to extract the status. * * @return The transaction status * * @throws TransactionException If the {@link TransactionManager} reports the status as unknown */ public static int getStatus(TransactionManager transactionManager) { try { final int status = transactionManager.getStatus(); if ( status == Status.STATUS_UNKNOWN ) { throw new TransactionException( "TransactionManager reported transaction status as unknwon" ); } return status; } catch ( SystemException se ) { throw new TransactionException( "Could not determine transaction status", se ); } }
@Test @DisplayName( "Enroll connection after previous connection close test" ) public void enrollConnectionCloseTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) .connectionFactoryConfiguration( cf -> cf .autoCommit( true ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { txManager.begin(); Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); String connectionToString = connection.toString(); connection.close(); Connection secondConnection = dataSource.getConnection(); logger.info( format( "Got connection {0}", secondConnection ) ); // TODO: comparing toString is brittle. Find a better way to make sure the underlying physical connection is the same. assertEquals( connectionToString, secondConnection.toString(), "Expect the same connection under the same transaction" ); assertFalse( secondConnection.getAutoCommit(), "AutoCommit temporarily disabled in enlisted connection" ); secondConnection.close(); txManager.commit(); assertTrue( connection.isClosed() ); assertTrue( secondConnection.isClosed() ); } catch ( NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e ) { fail( "Exception: " + e.getMessage() ); } }
public TransactionManager getTransactionManager() { return transactionManager; }
public PooledXAConnection(Connection connection, TransactionManager transactionManager) { super(connection); this.transactionManager = transactionManager; }