Java Code Examples for javax.transaction.TransactionManager#commit()

The following examples show how to use javax.transaction.TransactionManager#commit() . 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 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 2
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 3
Source File: EditorUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
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: TransactionalInterceptorBase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
protected void endTransaction(TransactionManager tm, Transaction tx, RunnableWithException afterEndTransaction)
        throws Exception {
    if (tx != tm.getTransaction()) {
        throw new RuntimeException(jtaLogger.i18NLogger.get_wrong_tx_on_thread());
    }

    if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
        tm.rollback();
    } else {
        tm.commit();
    }

    afterEndTransaction.run();
}
 
Example 5
Source File: InfinispanTx.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
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 6
Source File: JdbcConfigTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
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 7
Source File: StatefulContainerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
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: StatefulContainerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void testBusinessLocalInterfaceInTx() throws Exception {
    final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
    transactionManager.begin();
    try {
        testBusinessLocalInterface(inTxExpectedLifecycle);
    } finally {
        transactionManager.commit();
    }
}
 
Example 9
Source File: StatefulContainerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void testBusinessLocalBeanInterfaceInTx() throws Exception {
    final List localbeanExpectedLifecycle = new ArrayList(inTxExpectedLifecycle);

    // WAS can't avoid the extra constructor call
    // NOW it was rewritten to avoid it
    // localbeanExpectedLifecycle.add(3, Lifecycle.CONSTRUCTOR);

    final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
    transactionManager.begin();
    try {
        testBusinessLocalBeanInterface(localbeanExpectedLifecycle);
    } finally {
        transactionManager.commit();
    }
}
 
Example 10
Source File: EditorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception {
    TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
    EntityManager entityManager;

    transactionManager.begin();
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.persist(editor);
    entityManager.close();
    transactionManager.commit();
}
 
Example 11
Source File: InfinispanRemoteTx.java    From infinispan-simple-tutorials with Apache License 2.0 4 votes vote down vote up
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 12
Source File: TestJtaTxServlet.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@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 13
Source File: UpdateUserBoardTask.java    From hibernate-demos with Apache License 2.0 4 votes vote down vote up
/**
 * 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 14
Source File: GridJtaTransactionManagerSelfTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * 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();
    }
}