Search in sources :

Example 31 with XAResource

use of javax.transaction.xa.XAResource in project neo4j-mobile-android by neo4j-contrib.

the class TxManager method recover.

private void recover(Iterator<List<TxLog.Record>> danglingRecordList) {
    msgLog.logMessage("TM non resolved transactions found in " + txLog.getName(), true);
    try {
        // contains NonCompletedTransaction that needs to be committed
        List<NonCompletedTransaction> commitList = new ArrayList<NonCompletedTransaction>();
        // contains Xids that should be rolledback
        List<Xid> rollbackList = new LinkedList<Xid>();
        // key = Resource(branchId) value = XAResource
        Map<Resource, XAResource> resourceMap = new HashMap<Resource, XAResource>();
        buildRecoveryInfo(commitList, rollbackList, resourceMap, danglingRecordList);
        // invoke recover on all xa resources found
        Iterator<Resource> resourceItr = resourceMap.keySet().iterator();
        List<Xid> recoveredXidsList = new LinkedList<Xid>();
        while (resourceItr.hasNext()) {
            XAResource xaRes = resourceMap.get(resourceItr.next());
            Xid[] xids = xaRes.recover(XAResource.TMNOFLAGS);
            for (int i = 0; i < xids.length; i++) {
                if (XidImpl.isThisTm(xids[i].getGlobalTransactionId())) {
                    // linear search
                    if (rollbackList.contains(xids[i])) {
                        log.fine("Found pre commit " + xids[i] + " rolling back ... ");
                        msgLog.logMessage("TM: Found pre commit " + xids[i] + " rolling back ... ", true);
                        rollbackList.remove(xids[i]);
                        xaRes.rollback(xids[i]);
                    } else {
                        recoveredXidsList.add(xids[i]);
                    }
                } else {
                    log.warning("Unknown xid: " + xids[i]);
                }
            }
        }
        // sort the commit list after sequence number
        Collections.sort(commitList, new Comparator<NonCompletedTransaction>() {

            public int compare(NonCompletedTransaction r1, NonCompletedTransaction r2) {
                return r1.getSequenceNumber() - r2.getSequenceNumber();
            }
        });
        // go through and commit
        Iterator<NonCompletedTransaction> commitItr = commitList.iterator();
        while (commitItr.hasNext()) {
            NonCompletedTransaction nct = commitItr.next();
            int seq = nct.getSequenceNumber();
            Xid[] xids = nct.getXids();
            log.fine("Marked as commit tx-seq[" + seq + "] branch length: " + xids.length);
            for (Xid xid : xids) {
                if (!recoveredXidsList.contains(xid)) {
                    log.fine("Tx-seq[" + seq + "][" + xid + "] not found in recovered xid list, " + "assuming already committed");
                    continue;
                }
                recoveredXidsList.remove(xid);
                Resource resource = new Resource(xid.getBranchQualifier());
                if (!resourceMap.containsKey(resource)) {
                    final TransactionFailureException ex = new TransactionFailureException("Couldn't find XAResource for " + xid);
                    throw logAndReturn("TM: recovery error", ex);
                }
                log.fine("Commiting tx seq[" + seq + "][" + xid + "] ... ");
                msgLog.logMessage("TM: Committing tx " + xid, true);
                resourceMap.get(resource).commit(xid, false);
            }
        }
        // rollback the rest
        Iterator<Xid> rollbackItr = recoveredXidsList.iterator();
        while (rollbackItr.hasNext()) {
            Xid xid = rollbackItr.next();
            Resource resource = new Resource(xid.getBranchQualifier());
            if (!resourceMap.containsKey(resource)) {
                final TransactionFailureException ex = new TransactionFailureException("Couldn't find XAResource for " + xid);
                throw logAndReturn("TM: recovery error", ex);
            }
            log.fine("Rollback " + xid + " ... ");
            msgLog.logMessage("TM: no match found for " + xid + " removing", true);
            resourceMap.get(resource).rollback(xid);
        }
        if (rollbackList.size() > 0) {
            log.fine("TxLog contained unresolved " + "xids that needed rollback. They couldn't be matched to " + "any of the XAResources recover list. " + "Assuming " + rollbackList.size() + " transactions already rolled back.");
            msgLog.logMessage("TM: no match found for in total " + rollbackList.size() + " transaction that should have been rolled back", true);
        }
        // doesn't get lost.
        for (XAResource participant : MapUtil.reverse(resourceMap).keySet()) {
            xaResourceToDataSource(participant).rotateLogicalLog();
        }
    } catch (IOException e) {
        throw logAndReturn("TM: recovery failed", new TransactionFailureException("Recovery failed.", e));
    } catch (XAException e) {
        throw logAndReturn("TM: recovery failed", new TransactionFailureException("Recovery failed.", e));
    }
}
Also used : XAException(javax.transaction.xa.XAException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) XAResource(javax.transaction.xa.XAResource) XaResource(org.neo4j.kernel.impl.transaction.xaframework.XaResource) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Xid(javax.transaction.xa.Xid) XAResource(javax.transaction.xa.XAResource) TransactionFailureException(org.neo4j.graphdb.TransactionFailureException)

Example 32 with XAResource

use of javax.transaction.xa.XAResource in project geode by apache.

the class AbstractPoolCacheJUnitTest method testEffectOfBlockingTimeoutOnXAConnection.

/**
   * Tests if an XAresource obtained from an XAConnection which is already closed , can return null
   * or not.
   */
@Ignore("TODO: test used to eat its own exception and it fails")
@Test
public void testEffectOfBlockingTimeoutOnXAConnection() throws Exception {
    Map map = new HashMap();
    map.put("init-pool-size", "2");
    map.put("jndi-name", "TestXAPooledDataSource");
    map.put("max-pool-size", "7");
    map.put("idle-timeout-seconds", "20");
    map.put("blocking-timeout-seconds", "2");
    map.put("login-timeout-seconds", "5");
    // map.put("xa-datasource-class","org.apache.derby.jdbc.EmbeddedXADataSource");
    map.put("jdbc-driver-class", "org.apache.derby.jdbc.EmbeddedDriver");
    map.put("user-name", "mitul");
    map.put("password", "83f0069202c571faf1ae6c42b4ad46030e4e31c17409e19a");
    map.put("connection-url", "jdbc:derby:newDB;create=true");
    List props = new ArrayList();
    props.add(new ConfigProperty("databaseName", "newDB", "java.lang.String"));
    GemFireBasicDataSource gbds = (GemFireBasicDataSource) DataSourceFactory.getSimpleDataSource(map, props);
    map.put("xa-datasource-class", "org.apache.derby.jdbc.EmbeddedXADataSource");
    map.put("connection-url", "jdbc:derby:newDB;create=true");
    GemFireTransactionDataSource gtds = (GemFireTransactionDataSource) DataSourceFactory.getTranxDataSource(map, props);
    XAConnection xaconn = (XAConnection) gtds.provider.borrowConnection();
    try {
        Thread.sleep(4);
    } catch (InterruptedException e) {
        fail("interrupted");
    }
    for (int i = 0; i < 1000; ++i) {
        XAResource xar = xaconn.getXAResource();
        System.out.println("XAResource=" + xar);
        assertNotNull(xar);
    }
}
Also used : XAResource(javax.transaction.xa.XAResource) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) XAConnection(javax.sql.XAConnection) Ignore(org.junit.Ignore) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 33 with XAResource

use of javax.transaction.xa.XAResource in project jackrabbit by apache.

the class ConnectionFactoryTest method testTransactionSupport.

/**
     * Test if the session supports transactions
     */
public void testTransactionSupport() throws Exception {
    // Create the connection factory
    Object cf = mcf.createConnectionFactory();
    assertTrue(cf instanceof JCARepositoryHandle);
    Repository repository = (Repository) cf;
    // Open a session
    Session session = repository.login(JCR_SUPERUSER);
    assertTrue(session instanceof XAResource);
    session.logout();
}
Also used : Repository(javax.jcr.Repository) XAResource(javax.transaction.xa.XAResource) JCARepositoryHandle(org.apache.jackrabbit.jca.JCARepositoryHandle) Session(javax.jcr.Session)

Example 34 with XAResource

use of javax.transaction.xa.XAResource in project geode by apache.

the class GemFireTransactionDataSource method connectionClosed.

/**
   * Implementation of call back function from ConnectionEventListener interface. This callback will
   * be invoked on connection close event.
   * 
   * @param event Connection event object
   */
public void connectionClosed(ConnectionEvent event) {
    if (isActive) {
        try {
            XAConnection conn = (XAConnection) event.getSource();
            XAResource xar = (XAResource) xaResourcesMap.get(conn);
            xaResourcesMap.remove(conn);
            Transaction txn = transManager.getTransaction();
            if (txn != null && xar != null)
                txn.delistResource(xar, XAResource.TMSUCCESS);
            provider.returnConnection(conn);
        } catch (Exception e) {
            String exception = "GemFireTransactionDataSource::connectionClosed: Exception occurred due to " + e;
            if (logger.isDebugEnabled()) {
                logger.debug(exception, e);
            }
        }
    }
}
Also used : XAResource(javax.transaction.xa.XAResource) Transaction(javax.transaction.Transaction) SQLException(java.sql.SQLException) XAConnection(javax.sql.XAConnection)

Example 35 with XAResource

use of javax.transaction.xa.XAResource in project geode by apache.

the class GemFireTransactionDataSource method registerTranxConnection.

/**
   *  
   */
void registerTranxConnection(XAConnection xaConn) throws Exception {
    try {
        synchronized (this) {
            if (transManager == null) {
                transManager = JNDIInvoker.getTransactionManager();
            }
        }
        Transaction txn = transManager.getTransaction();
        if (txn != null) {
            XAResource xar = xaConn.getXAResource();
            txn.enlistResource(xar);
            // Add in the Map after successful registration of XAResource
            this.xaResourcesMap.put(xaConn, xar);
        }
    } catch (Exception ex) {
        Exception e = new Exception(LocalizedStrings.GemFireTransactionDataSource_GEMFIRETRANSACTIONDATASOURCEREGISTERTRANXCONNECTION_EXCEPTION_IN_REGISTERING_THE_XARESOURCE_WITH_THE_TRANSACTIONEXCEPTION_OCCURRED_0.toLocalizedString(ex));
        e.initCause(ex);
        throw e;
    }
}
Also used : XAResource(javax.transaction.xa.XAResource) Transaction(javax.transaction.Transaction) SQLException(java.sql.SQLException)

Aggregations

XAResource (javax.transaction.xa.XAResource)49 Xid (javax.transaction.xa.Xid)14 Test (org.junit.Test)13 SystemException (javax.transaction.SystemException)12 Transaction (javax.transaction.Transaction)11 ResourceException (javax.resource.ResourceException)9 XAException (javax.transaction.xa.XAException)9 XidImpl (org.neo4j.kernel.impl.transaction.XidImpl)9 RollbackException (javax.transaction.RollbackException)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 ManagedConnection (javax.resource.spi.ManagedConnection)6 TransactionFailureException (org.neo4j.graphdb.TransactionFailureException)6 XaResource (org.neo4j.kernel.impl.transaction.xaframework.XaResource)6 SQLException (java.sql.SQLException)5 RelationshipType (org.neo4j.graphdb.RelationshipType)5 Map (java.util.Map)4 XAConnection (javax.sql.XAConnection)4 HazelcastXAResource (com.hazelcast.transaction.HazelcastXAResource)3 PoolingException (com.sun.appserv.connectors.internal.api.PoolingException)3