Java Code Examples for javax.transaction.TransactionManager#begin()
The following examples show how to use
javax.transaction.TransactionManager#begin() .
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: DSSXATransactionManager.java From micro-integrator with Apache License 2.0 | 6 votes |
public void begin() throws DataServiceFault { TransactionManager txManager = getTransactionManager(); if (txManager == null) { return; } try { if (log.isDebugEnabled()) { log.debug("DXXATransactionManager.begin()"); } txManager.begin(); this.beginTx.set(true); } catch (Exception e) { throw new DataServiceFault(e, "Error from transaction manager in " + "begin(): " + e.getMessage()); } }
Example 2
Source File: TransactionalService.java From tutorials with MIT License | 6 votes |
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 3
Source File: EditorUnitTest.java From tutorials with MIT License | 6 votes |
private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); EntityManager entityManager; transactionManager.begin(); entityManager = entityManagerFactory.createEntityManager(); Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); assertThat(loadedEditor).isNotNull(); assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") .containsOnly("Maria", "Mike"); Map<String, Author> loadedAuthors = loadedEditor.getAssignedAuthors() .stream() .collect(Collectors.toMap(Author::getAuthorName, e -> e)); assertThat(loadedAuthors.get("Maria") .getAuthoredArticles()).onProperty("articleTitle") .containsOnly("Basic of Hibernate OGM"); assertThat(loadedAuthors.get("Mike") .getAuthoredArticles()).onProperty("articleTitle") .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); entityManager.close(); transactionManager.commit(); }
Example 4
Source File: TestBasicManagedDataSource.java From commons-dbcp with Apache License 2.0 | 6 votes |
/** 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 5
Source File: JtaTransactionManager.java From spring-analysis-note with MIT License | 5 votes |
@Override public Transaction createTransaction(@Nullable 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); }
Example 6
Source File: JtaTransactionWrapper.java From keycloak with Apache License 2.0 | 5 votes |
public JtaTransactionWrapper(KeycloakSessionFactory factory, TransactionManager tm) { this.tm = tm; this.factory = factory; try { suspended = tm.suspend(); logger.debug("new JtaTransactionWrapper"); logger.debugv("was existing? {0}", suspended != null); tm.begin(); ut = tm.getTransaction(); //ended = new Exception(); } catch (Exception e) { throw new RuntimeException(e); } }
Example 7
Source File: StatefulContainerTest.java From tomee with Apache License 2.0 | 5 votes |
public void testBusinessRemoteInterfaceInTx() throws Exception { final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class); transactionManager.begin(); try { testBusinessRemoteInterface(inTxExpectedLifecycle); } finally { transactionManager.commit(); } }
Example 8
Source File: TransactionalTest.java From tomee with Apache License 2.0 | 5 votes |
@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 9
Source File: JdbcConfigTest.java From tomee with Apache License 2.0 | 5 votes |
public void test() throws Exception { final ConfigurationFactory config = new ConfigurationFactory(); final Assembler assembler = new Assembler(); // System services assembler.createProxyFactory(config.configureService(ProxyFactoryInfo.class)); assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class)); assembler.createSecurityService(config.configureService(SecurityServiceInfo.class)); // managed JDBC assembler.createResource(config.configureService("Default JDBC Database", ResourceInfo.class)); // unmanaged JDBC assembler.createResource(config.configureService("Default Unmanaged JDBC Database", ResourceInfo.class)); final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class); final DataSource managedDS = (DataSource) containerSystem.getJNDIContext().lookup("openejb/Resource/Default JDBC Database"); assertNotNull("managedDS is null", managedDS); final DataSource unmanagedDS = (DataSource) containerSystem.getJNDIContext().lookup("openejb/Resource/Default Unmanaged JDBC Database"); assertNotNull("unmanagedDS is null", unmanagedDS); // test without a transaction // NOTE: without a transaction all connections work as unmanaged verifyUnmanagedConnections(managedDS); verifyUnmanagedConnections(unmanagedDS); // test in the context of a transaction final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class); transactionManager.begin(); try { verifyManagedConnections(managedDS); verifyUnmanagedConnections(unmanagedDS); } finally { // commit the transaction transactionManager.commit(); } }
Example 10
Source File: InfinispanTx.java From infinispan-simple-tutorials with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Construct a local cache manager DefaultCacheManager cacheManager = new DefaultCacheManager(); // Create a transaction cache config ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL); Configuration cacheConfig = builder.build(); // Create a cache with the config Cache<String, String> cache = cacheManager.administration() .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache("cache", cacheConfig); // Obtain the transaction manager TransactionManager transactionManager = cache.getAdvancedCache().getTransactionManager(); // Perform some operations within a transaction and commit it transactionManager.begin(); cache.put("key1", "value1"); cache.put("key2", "value2"); transactionManager.commit(); // Display the current cache contents System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2")); // Perform some operations within a transaction and roll it back transactionManager.begin(); cache.put("key1", "value3"); cache.put("key2", "value4"); transactionManager.rollback(); // Display the current cache contents System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2")); // Stop the cache manager and release all resources cacheManager.stop(); }
Example 11
Source File: JtaTransactionManager.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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); }
Example 12
Source File: JtaTransactionManager.java From lams with GNU General Public License v2.0 | 5 votes |
@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); }
Example 13
Source File: JtaTransactionManager.java From java-technology-stack with MIT License | 5 votes |
@Override public Transaction createTransaction(@Nullable 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); }
Example 14
Source File: TestJtaTxServlet.java From ignite with Apache License 2.0 | 4 votes |
/** {@inheritDoc} */ @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { final int key1 = 1; final int key2 = 2; final String correctVal1 = "correct_val1"; final String correctVal2 = "correct_val1"; final String incorrectVal1 = "incorrect_val2"; final String incorrectVal2 = "incorrect_val2"; final PrintWriter writer = res.getWriter(); try { final Ignite ignite = Ignition.ignite(); final IgniteCache<Integer, String> cache = ignite.cache("tx"); TransactionManager tmMgr = TransactionManagerFactory.getTransactionManager(); tmMgr.begin(); cache.put(key1, correctVal1); cache.put(key2, correctVal2); writer.println("Transaction #1. Put values [key1=" + key1 + ", val1=" + cache.get(key1) + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]"); writer.println(); tmMgr.commit(); try { tmMgr.begin(); writer.println("Transaction #2. Current values [key1=" + key1 + ", val1=" + cache.get(key1) + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]"); cache.put(key1, incorrectVal1); cache.put(key2, incorrectVal2); writer.println("Transaction #2. Put values [key1=" + key1 + ", val1=" + cache.get(key1) + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]"); tmMgr.setRollbackOnly(); tmMgr.commit(); } catch (final RollbackException ignored) { writer.println("Transaction #2. setRollbackOnly [key1=" + key1 + ", val1=" + cache.get(key1) + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]"); } writer.println(); tmMgr.begin(); writer.println("Transaction #2. Current values [key1=" + key1 + ", val1=" + cache.get(key1) + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]"); tmMgr.commit(); } catch (final Throwable e) { e.printStackTrace(writer); } }
Example 15
Source File: UpdateUserBoardTask.java From hibernate-demos with Apache License 2.0 | 4 votes |
/** * Updates the board with the last message. * * @return the new size of the board, after we've added the message * @throws Exception */ @Override public Integer call() throws Exception { Cache<MessageId, Message> messages = getCache( Message.CACHE_NAME ); Cache<BoardId, Board> boards = getCache( Board.CACHE_NAME ); Cache<BoardMessageId, BoardMessage> joinCache = getCache( BoardMessage.CACHE_NAME ); MessageId key = new MessageId( messageId ); Message message = getWithTranscoding( key, messages ); if ( message == null ) { throw new KeyNotFoundException( key, messages ); } TransactionManager transactionManager = boards.getAdvancedCache().getTransactionManager(); transactionManager.begin(); BoardId boardId = new BoardId( message.getUsername() ); // transaction-config LockingMode seems strangely OPTIMISTIC // OGM should have been created it PESSIMISTIC //TODO: after the problem is solved, we will restore the lock here: // // inserts on the **same user** board must be serialized // // according to the Infinispan API the lock will be released at the end of transaction // --> boards.getAdvancedCache().lock( boardId ); <-- Board board = getWithTranscoding( boardId, boards ); if ( board == null ) { board = new Board( message.getUsername() ); } // add message to the board BoardMessageId id = new BoardMessageId( message.getUsername(), board.getNext() ); BoardMessage value = new BoardMessage( message.getUsername(), messageId, board.getNext() ); putWithTranscoding( id, value, joinCache ); // increment for the next insert board.increment(); putWithTranscoding( boardId, board, boards ); // free lock here: transactionManager.commit(); return board.getNext(); }
Example 16
Source File: InfinispanRemoteTx.java From infinispan-simple-tutorials with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { // Create a configuration for a locally-running server ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer() .host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .security().authentication() //Add user credentials. .username("username") .password("password") .realm("default") .saslMechanism("DIGEST-MD5"); // Configure the RemoteCacheManager to use a transactional cache as default // Use the simple TransactionManager in hot rod client builder.transaction().transactionManagerLookup(RemoteTransactionManagerLookup.getInstance()); // The cache will be enlisted as Synchronization builder.transaction().transactionMode(TransactionMode.NON_XA); // Connect to the server RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // Create a transactional cache in the server since there is none available by default. cacheManager.administration().createCache(CACHE_NAME, new XMLStringConfiguration(TEST_CACHE_XML_CONFIG)); RemoteCache<String, String> cache = cacheManager.getCache(CACHE_NAME); // Obtain the transaction manager TransactionManager transactionManager = cache.getTransactionManager(); // Perform some operations within a transaction and commit it transactionManager.begin(); cache.put("key1", "value1"); cache.put("key2", "value2"); transactionManager.commit(); // Display the current cache contents System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2")); // Perform some operations within a transaction and roll it back transactionManager.begin(); cache.put("key1", "value3"); cache.put("key2", "value4"); transactionManager.rollback(); // Display the current cache contents System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2")); // Stop the cache manager and release all resources cacheManager.stop(); }
Example 17
Source File: CommonDataAccess.java From mdw with Apache License 2.0 | 4 votes |
/** * Should only be used with MDW data source */ @SuppressWarnings("squid:S2095") public TransactionWrapper startTransaction() throws DataAccessException { TransactionWrapper transaction = new TransactionWrapper(); TransactionUtil transUtil = TransactionUtil.getInstance(); TransactionManager transManager = transUtil.getTransactionManager(); try { if (logger.isTraceEnabled()) { logger.trace("startTransaction - transaction manager=" + transManager.hashCode() + " (status=" + transManager.getStatus() + ")"); } transaction.setDatabaseAccess(db); if (transManager.getStatus()==Status.STATUS_NO_TRANSACTION) { transaction.setTransactionAlreadyStarted(false); // Get connection BEFORE beginning transaction to avoid transaction timeout (10 minutes) exceptions (Fail to stop the transaction) db.openConnection().setAutoCommit(false); // Also set autoCommit to false transManager.begin(); transUtil.setCurrentConnection(db.getConnection()); } else { if (logger.isTraceEnabled()) logger.trace(" ... transaction already started, status=" + transManager.getStatus()); transaction.setTransactionAlreadyStarted(true); if (db.connectionIsOpen()) { transaction.setDatabaseConnectionAlreadyOpened(true); } else { if (logger.isTraceEnabled()) logger.trace(" ... but database is not open"); // not opened through this DatabaseAccess transaction.setDatabaseConnectionAlreadyOpened(false); if (transUtil.getCurrentConnection() == null) { db.openConnection().setAutoCommit(false); // Set autoCommit to false transUtil.setCurrentConnection(db.getConnection()); } else { db.setConnection(transUtil.getCurrentConnection()); } } } transaction.setTransaction(transManager.getTransaction()); return transaction; } catch (Throwable e) { if (transaction.getTransaction()!=null) stopTransaction(transaction); throw new DataAccessException(0, "Fail to start transaction", e); } }
Example 18
Source File: TransactionalInterceptorBase.java From quarkus with Apache License 2.0 | 4 votes |
protected Object invokeInOurTx(InvocationContext ic, TransactionManager tm, RunnableWithException afterEndTransaction) throws Exception { TransactionConfiguration configAnnotation = getTransactionConfiguration(ic); int currentTmTimeout = ((CDIDelegatingTransactionManager) transactionManager).getTransactionTimeout(); if (configAnnotation != null && configAnnotation.timeout() != TransactionConfiguration.UNSET_TIMEOUT) { tm.setTransactionTimeout(configAnnotation.timeout()); } Transaction tx; try { tm.begin(); tx = tm.getTransaction(); } finally { if (configAnnotation != null && configAnnotation.timeout() != TransactionConfiguration.UNSET_TIMEOUT) { //restore the default behaviour tm.setTransactionTimeout(currentTmTimeout); } } boolean throwing = false; Object ret = null; try { ret = ic.proceed(); } catch (Exception e) { throwing = true; handleException(ic, e, tx); } finally { // handle asynchronously if not throwing if (!throwing && ret != null) { ReactiveTypeConverter<Object> converter = null; if (ret instanceof CompletionStage == false && (ret instanceof Publisher == false || ic.getMethod().getReturnType() != Publisher.class)) { @SuppressWarnings({ "rawtypes", "unchecked" }) Optional<ReactiveTypeConverter<Object>> lookup = Registry.lookup((Class) ret.getClass()); if (lookup.isPresent()) { converter = lookup.get(); if (converter.emitAtMostOneItem()) { ret = converter.toCompletionStage(ret); } else { ret = converter.toRSPublisher(ret); } } } if (ret instanceof CompletionStage) { ret = handleAsync(tm, tx, ic, ret, afterEndTransaction); // convert back if (converter != null) ret = converter.fromCompletionStage((CompletionStage<?>) ret); } else if (ret instanceof Publisher) { ret = handleAsync(tm, tx, ic, ret, afterEndTransaction); // convert back if (converter != null) ret = converter.fromPublisher((Publisher<?>) ret); } else { // not async: handle synchronously endTransaction(tm, tx, afterEndTransaction); } } else { // throwing or null: handle synchronously endTransaction(tm, tx, afterEndTransaction); } } return ret; }
Example 19
Source File: GridJtaTransactionManagerSelfTest.java From ignite with Apache License 2.0 | 2 votes |
/** * Test for switching tx context by JTA Manager. * * @throws Exception If failed. */ @Test public void testJtaTxContextSwitch() throws Exception { for (TransactionIsolation isolation : TransactionIsolation.values()) { TransactionConfiguration cfg = grid().context().config().getTransactionConfiguration(); cfg.setDefaultTxConcurrency(txConcurrency); cfg.setDefaultTxIsolation(isolation); TransactionManager jtaTm = jotm.getTransactionManager(); IgniteCache<Integer, String> cache = jcache(); assertNull(grid().transactions().tx()); jtaTm.begin(); Transaction tx1 = jtaTm.getTransaction(); cache.put(1, Integer.toString(1)); assertNotNull(grid().transactions().tx()); assertEquals(ACTIVE, grid().transactions().tx().state()); assertEquals(Integer.toString(1), cache.get(1)); jtaTm.suspend(); assertNull(grid().transactions().tx()); assertNull(cache.get(1)); jtaTm.begin(); Transaction tx2 = jtaTm.getTransaction(); assertNotSame(tx1, tx2); cache.put(2, Integer.toString(2)); assertNotNull(grid().transactions().tx()); assertEquals(ACTIVE, grid().transactions().tx().state()); assertEquals(Integer.toString(2), cache.get(2)); jtaTm.commit(); assertNull(grid().transactions().tx()); assertEquals(Integer.toString(2), cache.get(2)); jtaTm.resume(tx1); assertNotNull(grid().transactions().tx()); assertEquals(ACTIVE, grid().transactions().tx().state()); cache.put(3, Integer.toString(3)); jtaTm.commit(); assertEquals("1", cache.get(1)); assertEquals("2", cache.get(2)); assertEquals("3", cache.get(3)); assertNull(grid().transactions().tx()); cache.removeAll(); } }
Example 20
Source File: GridJtaTransactionManagerSelfTest.java From ignite with Apache License 2.0 | 2 votes |
/** * @throws Exception If failed. */ @Test public void testJtaTxContextSwitchWithExistingTx() throws Exception { for (TransactionIsolation isolation : TransactionIsolation.values()) { TransactionConfiguration cfg = grid().context().config().getTransactionConfiguration(); cfg.setDefaultTxConcurrency(txConcurrency); cfg.setDefaultTxIsolation(isolation); TransactionManager jtaTm = jotm.getTransactionManager(); IgniteCache<Integer, String> cache = jcache(); jtaTm.begin(); Transaction tx1 = jtaTm.getTransaction(); cache.put(1, Integer.toString(1)); assertNotNull(grid().transactions().tx()); assertEquals(ACTIVE, grid().transactions().tx().state()); assertEquals(Integer.toString(1), cache.get(1)); jtaTm.suspend(); jtaTm.begin(); Transaction tx2 = jtaTm.getTransaction(); assertNotSame(tx1, tx2); cache.put(2, Integer.toString(2)); try { jtaTm.resume(tx1); fail("jtaTm.resume shouldn't success."); } catch (IllegalStateException ignored) { // No-op. } finally { jtaTm.rollback(); //rolling back tx2 } jtaTm.resume(tx1); jtaTm.rollback(); cache.removeAll(); } }