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));
}
}
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);
}
}
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();
}
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();
}
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);
}
}
}
}
Aggregations