Search in sources :

Example 26 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 27 with XAResource

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

the class TxDBServlet method insertIntoTransaction.

/**
	 * This method demonstrates how to enlist JDBC connection into Transaction according OSGi enterprise specification.
	 * 
	 * @param xads XADataSource
	 * @param tm TransactionManager
	 * @param value which will be inserted into table
	 * @param toCommit Specify if the transaction will be committed or rolledback
	 * @throws SQLException
	 * @throws GenericJTAException
	 */
private void insertIntoTransaction(XADataSource xads, TransactionManager tm, String value, boolean toCommit) throws SQLException, GenericJTAException {
    XAConnection xaConnection = xads.getXAConnection();
    Connection connection = xaConnection.getConnection();
    XAResource xaResource = xaConnection.getXAResource();
    try {
        tm.begin();
        Transaction transaction = tm.getTransaction();
        transaction.enlistResource(xaResource);
        PreparedStatement insertStatement = connection.prepareStatement(INSERT_INTO_TABLE);
        insertStatement.setString(1, value);
        insertStatement.executeUpdate();
        if (toCommit) {
            transaction.commit();
        } else {
            transaction.rollback();
        }
    } catch (RollbackException e) {
        throw new GenericJTAException(e);
    } catch (SecurityException e) {
        throw new GenericJTAException(e);
    } catch (IllegalStateException e) {
        throw new GenericJTAException(e);
    } catch (HeuristicMixedException e) {
        throw new GenericJTAException(e);
    } catch (HeuristicRollbackException e) {
        throw new GenericJTAException(e);
    } catch (SystemException e) {
        throw new GenericJTAException(e);
    } catch (NotSupportedException e) {
        throw new GenericJTAException(e);
    }
}
Also used : Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PreparedStatement(java.sql.PreparedStatement) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) RollbackException(javax.transaction.RollbackException) XAResource(javax.transaction.xa.XAResource) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) HeuristicMixedException(javax.transaction.HeuristicMixedException) NotSupportedException(javax.transaction.NotSupportedException) XAConnection(javax.sql.XAConnection)

Example 28 with XAResource

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

the class LogTest method testGeronimo.

@Test
@Ignore
public void testGeronimo() throws Exception {
    System.err.println("Geronimo");
    XidFactory xidFactory = new XidFactoryImpl("hi".getBytes());
    HOWLLog txLog = new HOWLLog("org.objectweb.howl.log.BlockLogBuffer", 4, true, true, 50, new File(".").getAbsolutePath(), "log", "geronimo", 512, 0, 2, 4, -1, true, xidFactory, null);
    txLog.doStart();
    GeronimoTransactionManager tm = new GeronimoTransactionManager(600, xidFactory, txLog);
    XAResource xar1 = new TestXAResource("res1");
    XAResource xar2 = new TestXAResource("res2");
    tm.registerNamedXAResourceFactory(new TestXAResourceFactory("res1"));
    tm.registerNamedXAResourceFactory(new TestXAResourceFactory("res2"));
    for (int i = minThreads; i <= maxThreads; i *= 10) {
        for (int j = minTxPerThread; j <= maxTxPerThread; j *= 10) {
            long ms = testThroughput(tm, xar1, xar2, i, j);
            System.err.println("TPS (" + i + " threads, " + j + " tx) = " + ((i * j) / (ms / 1000.0)));
        }
    }
    txLog.doStop();
    System.err.println();
    System.err.flush();
}
Also used : NamedXAResource(org.apache.geronimo.transaction.manager.NamedXAResource) XAResource(javax.transaction.xa.XAResource) HOWLLog(org.apache.geronimo.transaction.log.HOWLLog) GeronimoTransactionManager(org.apache.geronimo.transaction.manager.GeronimoTransactionManager) File(java.io.File) XidFactory(org.apache.geronimo.transaction.manager.XidFactory) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 29 with XAResource

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

the class TransactionLogTest method doRecoveryRequired.

public void doRecoveryRequired(BiConsumer<XAResource, XAResource> ordering, TransactionStatus expectedFinalState) throws Exception {
    //Register the recoverable resource
    ArgumentCaptor<ServiceListener> captor = ArgumentCaptor.forClass(ServiceListener.class);
    Mockito.verify(ctx).addServiceListener(captor.capture(), Mockito.anyString());
    Mockito.when(ctx.getService(serviceRef)).thenReturn(new TestRecoverableResource("foo", dataSource));
    captor.getValue().serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, serviceRef));
    XAConnection xaConn = dataSource.getXAConnection();
    AtomicReference<TransactionStatus> ref = new AtomicReference<TransactionStatus>();
    try {
        txControl.required(() -> {
            txControl.getCurrentContext().postCompletion(ref::set);
            Connection conn = xaConn.getConnection();
            // conn.setAutoCommit(false);
            XAResource dsResource = xaConn.getXAResource();
            XAResource poison = Mockito.mock(XAResource.class);
            Mockito.when(poison.prepare(Mockito.any())).thenAnswer(i -> {
                conn.createStatement().execute("shutdown immediately");
                Thread.sleep(1000);
                return XA_OK;
            });
            ordering.accept(dsResource, poison);
            return conn.createStatement().execute("Insert into TEST_TABLE values ( 'Hello World!' )");
        });
    } catch (TransactionException te) {
        assertEquals(expectedFinalState, ref.get());
        assertEquals(expectedFinalState == ROLLED_BACK, te instanceof TransactionRolledBackException);
    } finally {
        try {
            xaConn.close();
        } catch (SQLException sqle) {
        }
    }
    setupServerAndDataSource();
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) SQLException(java.sql.SQLException) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) TransactionStatus(org.osgi.service.transaction.control.TransactionStatus) AtomicReference(java.util.concurrent.atomic.AtomicReference) XAResource(javax.transaction.xa.XAResource) RecoverableXAResource(org.osgi.service.transaction.control.recovery.RecoverableXAResource) TransactionException(org.osgi.service.transaction.control.TransactionException) ServiceEvent(org.osgi.framework.ServiceEvent) TransactionRolledBackException(org.osgi.service.transaction.control.TransactionRolledBackException) XAConnection(javax.sql.XAConnection)

Example 30 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)

Aggregations

XAResource (javax.transaction.xa.XAResource)37 Xid (javax.transaction.xa.Xid)13 Test (org.junit.Test)13 SystemException (javax.transaction.SystemException)10 Transaction (javax.transaction.Transaction)10 XidImpl (org.neo4j.kernel.impl.transaction.XidImpl)9 XAException (javax.transaction.xa.XAException)8 RollbackException (javax.transaction.RollbackException)7 TransactionFailureException (org.neo4j.graphdb.TransactionFailureException)6 XaResource (org.neo4j.kernel.impl.transaction.xaframework.XaResource)6 HashMap (java.util.HashMap)5 RelationshipType (org.neo4j.graphdb.RelationshipType)5 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 LinkedList (java.util.LinkedList)4 ResourceException (javax.resource.ResourceException)4 ManagedConnection (javax.resource.spi.ManagedConnection)4 XAConnection (javax.sql.XAConnection)4 HazelcastXAResource (com.hazelcast.transaction.HazelcastXAResource)3 Iterator (java.util.Iterator)3