Java Examples for javax.transaction.xa.XAResource

The following java examples will help you to understand the usage of javax.transaction.xa.XAResource. These source code samples are taken from different open source projects.

Example 1
Project: activemq-master  File: XAConnectionPoolTest.java View source code
@Override
public Transaction getTransaction() throws SystemException {
    return new Transaction() {

        @Override
        public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
        }

        @Override
        public boolean delistResource(XAResource xaRes, int flag) throws IllegalStateException, SystemException {
            return false;
        }

        @Override
        public boolean enlistResource(XAResource xaRes) throws IllegalStateException, RollbackException, SystemException {
            return false;
        }

        @Override
        public int getStatus() throws SystemException {
            return 0;
        }

        @Override
        public void registerSynchronization(Synchronization synch) throws IllegalStateException, RollbackException, SystemException {
            syncs.add(synch);
        }

        @Override
        public void rollback() throws IllegalStateException, SystemException {
        }

        @Override
        public void setRollbackOnly() throws IllegalStateException, SystemException {
        }
    };
}
Example 2
Project: byteman-master  File: RuleConstructorTestCase.java View source code
@Test
public void basic() {
    String testRule = String.format("RULE basic rule%n" + "CLASS javax.transaction.xa.XAResource%n" + "METHOD commit%n" + "AT ENTRY%n" + "IF NOT flagged(\"commitFlag\")%n" + "DO throw new javax.transaction.xa.XAResource(100)%n" + "ENDRULE%n");
    String rule = RuleConstructor.createRule("basic rule").onClass("javax.transaction.xa.XAResource").inMethod("commit").atEntry().ifCondition("NOT flagged(\"commitFlag\")").doAction("throw new javax.transaction.xa.XAResource(100)").build();
    Assert.assertEquals("The rule does not match the built one", testRule, rule);
}
Example 3
Project: narayana-master  File: EnlistDelistEnlistImpl01.java View source code
public void begin_begin() throws InvocationException {
    boolean correct = true;
    try {
        XAConnection xaConnection = _xaDataSource.getXAConnection(_databaseUser, _databasePassword);
        XAResource xaResource = xaConnection.getXAResource();
        javax.transaction.TransactionManager tm = com.arjuna.ats.jta.TransactionManager.transactionManager();
        tm.begin();
        Transaction transaction = tm.getTransaction();
        correct = correct && transaction.enlistResource(xaResource);
        if (correct) {
            try {
                tm.begin();
                correct = false;
            } catch (NotSupportedException notSupportedException) {
            }
        }
        tm.rollback();
    } catch (Exception e) {
        e.printStackTrace();
        correct = false;
    }
    _isCorrect = _isCorrect && correct;
    return;
}
Example 4
Project: glassfish-main-master  File: TransactionManagerHelper.java View source code
/**
     * PreInvoke Transaction configuration for Servlet Container.
     * BaseContainer.preInvokeTx() handles all this for CMT EJB.
     *
     * Compensate that JavaEEInstanceListener.handleBeforeEvent(
     * BEFORE_SERVICE_EVENT)
     * gets called before WSIT WSTX Service pipe associates a JTA txn with 
     * incoming thread.
     *
     * Precondition: assumes JTA transaction already associated with current 
     * thread.
     */
public void preInvokeTx(boolean checkServletInvocation) {
    final ComponentInvocation inv = invocationManager.getCurrentInvocation();
    if (inv != null && (!checkServletInvocation || inv.getInvocationType() == ComponentInvocation.ComponentInvocationType.SERVLET_INVOCATION)) {
        try {
            // Required side effect: note that 
            // enlistComponentResources calls
            // ComponentInvocation.setTransaction(currentJTATxn).
            // If this is not correctly set, managed XAResource connections
            // are not auto enlisted when they are created.
            transactionManager.enlistComponentResources();
        } catch (java.rmi.RemoteException re) {
            throw new IllegalStateException(re);
        }
    }
}
Example 5
Project: glassfish-master  File: WorkDispatcher.java View source code
public void run() {
    debug("ENTER...");
    try {
        synchronized (Controls.readyLock) {
            debug("WAIT...");
            Controls.readyLock.wait();
            if (stop) {
                return;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    debug("Running...");
    //try 3 times to create endpoint (in case of failure)
    for (int i = 0; i < 3; i++) {
        try {
            Method onMessage = getOnMessageMethod();
            System.out.println("isDeliveryTransacted = " + factory.isDeliveryTransacted(onMessage));
            if (!factory.isDeliveryTransacted(onMessage)) {
            //MessageEndpoint ep = factory.createEndpoint(null);
            //DeliveryWork d = new DeliveryWork("NO_TX", ep); 
            //wm.doWork(d, 0, null, null);
            } else {
                //MessageEndpoint ep = factory.createEndpoint(null);
                MessageEndpoint ep = factory.createEndpoint(new FakeXAResource());
                int numOfMessages = 5;
                //importing transaction
                //write/commit
                ExecutionContext ec = startTx();
                debug("Start TX - " + ec.getXid());
                DeliveryWork w = new DeliveryWork(ep, numOfMessages, "WRITE");
                wm.doWork(w, 0, ec, null);
                xa.commit(ec.getXid(), true);
                debug("DONE WRITE TO DB");
                Controls.expectedResults = numOfMessages;
                notifyAndWait();
                //delete/rollback
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, numOfMessages, "DELETE");
                wm.doWork(w, 0, ec, null);
                xa.rollback(ec.getXid());
                debug("DONE ROLLBACK FROM DB");
                Controls.expectedResults = numOfMessages;
                notifyAndWait();
                //delete/commit
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, numOfMessages, "DELETE");
                wm.doWork(w, 0, ec, null);
                xa.commit(ec.getXid(), true);
                debug("DONE DELETE FROM DB");
                Controls.expectedResults = 0;
                notifyAndWait();
                //write/commit
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, numOfMessages, "WRITE");
                wm.doWork(w, 0, ec, null);
                xa.commit(ec.getXid(), true);
                debug("DONE WRITE TO DB");
                Controls.expectedResults = numOfMessages;
                notifyAndWait();
                //delete/commit
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, numOfMessages, "DELETE");
                wm.doWork(w, 0, ec, null);
                xa.commit(ec.getXid(), true);
                debug("DONE DELETE FROM DB");
                Controls.expectedResults = 0;
                notifyAndWait();
                //write multiple times using doWork/commit
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, 1, "WRITE", true);
                wm.doWork(w, 0, ec, null);
                wm.doWork(w, 0, ec, null);
                wm.doWork(w, 0, ec, null);
                xa.commit(ec.getXid(), true);
                debug("DONE WRITE TO DB");
                Controls.expectedResults = 3;
                notifyAndWait();
                //write multiple times using doWork/rollback
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, 1, "WRITE", true);
                wm.doWork(w, 0, ec, null);
                wm.doWork(w, 0, ec, null);
                wm.doWork(w, 0, ec, null);
                xa.rollback(ec.getXid());
                debug("DONE WRITE TO DB");
                Controls.expectedResults = 3;
                notifyAndWait();
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                //write multiple times using doWork/rollback
                w = new DeliveryWork(ep, 2, "WRITE", true);
                wm.doWork(w, 0, ec, null);
                wm.doWork(w, 0, ec, null);
                wm.doWork(w, 0, ec, null);
                if (XAResource.XA_OK == xa.prepare(ec.getXid())) {
                    xa.commit(ec.getXid(), false);
                    debug("XA PREPARE/COMMIT. DONE WRITE TO DB ");
                    Controls.expectedResults = 9;
                    notifyAndWait();
                } else {
                    xa.rollback(ec.getXid());
                    debug("XA PREPARE UNSUCCESSFUL. DONE ROLLBACK");
                    Controls.expectedResults = 3;
                    notifyAndWait();
                }
                //delete all.
                ec = startTx();
                debug("Start TX - " + ec.getXid());
                w = new DeliveryWork(ep, 1, "DELETE_ALL");
                wm.doWork(w, 0, ec, null);
                xa.commit(ec.getXid(), true);
                debug("DONE DELETE ALL FROM DB");
                Controls.expectedResults = 0;
                notifyAndWait();
                done();
            }
            break;
        } catch (UnavailableException ex) {
            System.out.println("WorkDispatcher[" + id + "] Endpoint Unavailable");
            try {
                Thread.currentThread().sleep(3 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (XAException ex) {
            ex.printStackTrace();
            System.out.println("ERROR CODE = " + ex.errorCode);
            done();
            break;
        } catch (Exception ex) {
            ex.printStackTrace();
            done();
            break;
        }
    }
    debug("LEAVE...");
}
Example 6
Project: Payara-master  File: TransactionManagerHelper.java View source code
/**
     * PreInvoke Transaction configuration for Servlet Container.
     * BaseContainer.preInvokeTx() handles all this for CMT EJB.
     *
     * Compensate that JavaEEInstanceListener.handleBeforeEvent(
     * BEFORE_SERVICE_EVENT)
     * gets called before WSIT WSTX Service pipe associates a JTA txn with 
     * incoming thread.
     *
     * Precondition: assumes JTA transaction already associated with current 
     * thread.
     */
public void preInvokeTx(boolean checkServletInvocation) {
    final ComponentInvocation inv = invocationManager.getCurrentInvocation();
    if (inv != null && (!checkServletInvocation || inv.getInvocationType() == ComponentInvocation.ComponentInvocationType.SERVLET_INVOCATION)) {
        try {
            // Required side effect: note that 
            // enlistComponentResources calls
            // ComponentInvocation.setTransaction(currentJTATxn).
            // If this is not correctly set, managed XAResource connections
            // are not auto enlisted when they are created.
            transactionManager.enlistComponentResources();
        } catch (java.rmi.RemoteException re) {
            throw new IllegalStateException(re);
        }
    }
}
Example 7
Project: geronimo-master  File: TransactionManagerImplTest.java View source code
public void testOneResourceCommit() throws Exception {
    assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
    tm.begin();
    Transaction tx = tm.getTransaction();
    tx.enlistResource(r1_1);
    tx.delistResource(r1_1, XAResource.TMSUCCESS);
    tx.commit();
    assertEquals(Status.STATUS_NO_TRANSACTION, tm.getStatus());
    assertTrue(r1_1.isCommitted());
    assertTrue(!r1_1.isPrepared());
    assertTrue(!r1_1.isRolledback());
}
Example 8
Project: MULE-master  File: XaTransaction.java View source code
/**
   * @param key Must be the provider of the resource object. i.e. for JDBC it's the XADataSource, for JMS is the
   *        XAConnectionFactory. It can be a wrapper in which case should be a
   *        {@link org.mule.runtime.core.util.xa.XaResourceFactoryHolder} to be able to determine correctly if there's already a
   *        resource for that {@link javax.transaction.xa.XAResource} provider.
   * @param resource the resource object. It must be an {@link javax.transaction.xa.XAResource} or a
   *        {@link MuleXaObject}
   * @throws TransactionException
   */
public synchronized void bindResource(Object key, Object resource) throws TransactionException {
    ResourceKey normalizedKey = getResourceEntry(key, resource);
    if (resources.containsKey(key)) {
        throw new IllegalTransactionStateException(CoreMessages.transactionResourceAlreadyListedForKey(key));
    }
    resources.put(normalizedKey, resource);
    if (key == null) {
        logger.error("Key for bound resource " + resource + " is null");
    }
    if (resource instanceof MuleXaObject) {
        MuleXaObject xaObject = (MuleXaObject) resource;
        xaObject.enlist();
    } else if (resource instanceof XAResource) {
        enlistResource((XAResource) resource);
    } else {
        logger.error("Bound resource " + resource + " is neither a MuleXaObject nor XAResource");
    }
}
Example 9
Project: activemq-artemis-master  File: NIOMultiThreadCompactorStressTest.java View source code
private void checkEmptyXID(final Xid xid) throws Exception {
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(true, false, false);
    Xid[] xids = session.recover(XAResource.TMSTARTRSCAN);
    Assert.assertEquals(1, xids.length);
    Assert.assertEquals(xid, xids[0]);
    session.rollback(xid);
    session.close();
    sf.close();
}
Example 10
Project: btm-master  File: DelistmentTest.java View source code
public void testDelistErrorOnCommit() throws Exception {
    btm.begin();
    Connection connection1 = poolingDataSource1.getConnection();
    PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1;
    XAConnection xaConnection1 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle1.getPooledConnection());
    MockXAResource xaResource1 = (MockXAResource) xaConnection1.getXAResource();
    // triggers enlistment
    connection1.createStatement();
    xaResource1.setEndException(new BitronixXAException("screw delistment", XAException.XAER_RMERR));
    xaResource1.setRollbackException(new BitronixXAException("delistment was screwed, cannot rollback", XAException.XAER_RMERR));
    Connection connection2 = poolingDataSource2.getConnection();
    PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2;
    XAConnection xaConnection2 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle2.getPooledConnection());
    MockXAResource xaResource2 = (MockXAResource) xaConnection2.getXAResource();
    // triggers enlistment
    connection2.createStatement();
    try {
        btm.commit();
        fail("expected RollbackException");
    } catch (RollbackException ex) {
        assertEquals("delistment error caused transaction rollback" + System.getProperty("line.separator") + "  resource(s) [pds1] could not be delisted", ex.getMessage());
    }
    // check flow
    List orderedEvents = EventRecorder.getOrderedEvents();
    log.info(EventRecorder.dumpToString());
    assertEquals(9, orderedEvents.size());
    int i = 0;
    assertEquals(Status.STATUS_ACTIVE, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(Status.STATUS_MARKED_ROLLBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(Status.STATUS_ROLLING_BACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertTrue(((XAResourceRollbackEvent) orderedEvents.get(i++)).getSource() == xaResource2);
    assertEquals(Status.STATUS_ROLLEDBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
}
Example 11
Project: clearpool-master  File: TransactionImpl.java View source code
/**
   * Try to prepared
   */
private boolean tryPrepared() {
    status = Status.STATUS_PREPARING;
    boolean preparedSuccess = true;
    for (ResourceCarry carry : resList) {
        try {
            int result = carry.xaRes.prepare(carry.xid);
            preparedSuccess &= result == XAResource.XA_OK;
        } catch (XAException e) {
            LOGGER.error("can't prepare XA: (error code = " + e.errorCode + "): ", e);
            preparedSuccess = false;
        }
    }
    status = Status.STATUS_PREPARED;
    return preparedSuccess;
}
Example 12
Project: genericconnector-master  File: AbstractTransactionAssistanceXAResource.java View source code
@Override
public int prepare(Xid xid) throws XAException {
    log.log(Level.INFO, "PREPARE " + XidImpl.asString(xid));
    if (!getUnderlyingConnection().wasExecuteSuccessful()) {
        //vote to rollback :o(
        throw new XAException(XAException.XA_RBROLLBACK);
    } else {
        //a successful execute is a guarantee that we can commit => therefore vote "OK to commit"
        return XAResource.XA_OK;
    }
}
Example 13
Project: infinispan-master  File: RehashTestBase.java View source code
@Override
public void run() {
    try {
        // start a transaction on c1.
        TransactionManager t1 = TestingUtil.getTransactionManager(c1);
        t1.begin();
        c1.put(keys.get(0), "transactionally_replaced");
        Transaction tx = t1.getTransaction();
        tx.enlistResource(new XAResourceAdapter() {

            public int prepare(Xid id) {
                // this would be called *after* the cache prepares.
                try {
                    log.debug("Unblocking commit");
                    l.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return XAResource.XA_OK;
            }
        });
        t1.commit();
    } catch (Exception e) {
        log.error("Error committing transaction", e);
        rollback.set(true);
        throw new RuntimeException(e);
    }
}
Example 14
Project: nuxeo-core-master  File: JDBCMapperConnector.java View source code
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (mapper.isConnected()) {
        return doInvoke(method, args);
    }
    // should not operate with tx mamagement (managed connection)
    String name = method.getName();
    if ("start".equals(name)) {
        return XAResource.XA_OK;
    }
    if ("end".equals(name)) {
        return null;
    }
    if ("prepare".equals(name)) {
        return XAResource.XA_OK;
    }
    if ("commit".equals(name)) {
        return null;
    }
    if ("rollback".equals(name)) {
        return null;
    }
    if ("close".equals(name)) {
        return null;
    }
    if ("clearCache".equals(name)) {
        return doInvoke(method, args);
    }
    if ("close".equals(name)) {
        return null;
    }
    mapper.connect();
    try {
        return doInvoke(method, args);
    } finally {
        if (mapper.isConnected()) {
            mapper.disconnect();
        }
    }
}
Example 15
Project: sef4j-master  File: SefXAResourceProxy.java View source code
public boolean isSameRM(XAResource xares) throws XAException {
    StackPopper toPop = LocalCallStack.meth(CNAME, "isSameRM").withParam("xares", xares).push();
    try {
        XAResource xaresUnwrapped = (xares instanceof SefXAResourceProxy) ? ((SefXAResourceProxy) xares).to : xares;
        boolean res = to.isSameRM(xaresUnwrapped);
        return toPop.returnValue(res);
    } catch (XAException ex) {
        throw toPop.returnException(ex);
    } finally {
        toPop.close();
    }
}
Example 16
Project: spring-modules-jcr-master  File: LocalTransactionManager.java View source code
protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) throws TransactionException {
    if (transactionDefinition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        throw new InvalidIsolationLevelException("JCR does not support an isolation level concept");
    }
    Session session = null;
    try {
        JcrTransactionObject txObject = (JcrTransactionObject) transaction;
        if (txObject.getSessionHolder() == null) {
            // get the new session
            Session newSession = sessionFactory.getSession();
            // make sure we have an XAResource
            if (!(newSession instanceof XAResource))
                throw new IllegalArgumentException("transactions are not supported by your Jcr Repository");
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new session [" + newSession + "] for JCR transaction");
            }
            txObject.setSessionHolder(new UserTxSessionHolder(newSession), true);
        }
        UserTxSessionHolder sessionHolder = txObject.getSessionHolder();
        sessionHolder.setSynchronizedWithTransaction(true);
        session = sessionHolder.getSession();
        /*
             * We have no notion of flushing inside a JCR session
             * 
            if (transactionDefinition.isReadOnly() && txObject.isNewSessionHolder()) {
                sessionHolder.setReadOnly(true);
            }

            if (!transactionDefinition.isReadOnly() && !txObject.isNewSessionHolder()) {
                if (sessionHolder.isReadOnly()) {
                    sessionHolder.setReadOnly(false);
                }
            }
            */
        // start the transaction
        sessionHolder.getTransaction().begin();
        // Register transaction timeout.
        if (transactionDefinition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getSessionHolder().setTimeoutInSeconds(transactionDefinition.getTimeout());
        }
        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);
        }
    } catch (Exception ex) {
        SessionFactoryUtils.releaseSession(session, getSessionFactory());
        throw new CannotCreateTransactionException("Could not open JCR session for transaction", ex);
    }
}
Example 17
Project: spring-modules-master  File: JackRabbitUserTransaction.java View source code
/**
     * @see javax.transaction.UserTransaction#begin
     */
public void begin() throws NotSupportedException, SystemException {
    if (status != Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("Transaction already active");
    }
    try {
        xid = new XidImpl(counter++);
        xares.start(xid, XAResource.TMNOFLAGS);
        status = Status.STATUS_ACTIVE;
    } catch (XAException e) {
        throw new SystemException("Unable to begin transaction: " + "XA_ERR=" + e.errorCode);
    }
}
Example 18
Project: teiid-master  File: TestXAConnection.java View source code
@Test
public void testConnectionClose() throws Exception {
    final ConnectionImpl mmConn = TestConnection.getMMConnection();
    XAConnectionImpl xaConn = new XAConnectionImpl(mmConn);
    Connection conn = xaConn.getConnection();
    StatementImpl stmt = (StatementImpl) conn.createStatement();
    conn.setAutoCommit(false);
    conn.close();
    ServerConnection sc = xaConn.getConnectionImpl().getServerConnection();
    Mockito.verify(sc, VerificationModeFactory.times(1)).cleanUp();
    assertTrue(stmt.isClosed());
    assertTrue(conn.getAutoCommit());
    conn = xaConn.getConnection();
    stmt = (StatementImpl) conn.createStatement();
    XAResource resource = xaConn.getXAResource();
    resource.start(new XidImpl(1, new byte[0], new byte[0]), XAResource.TMNOFLAGS);
    conn.close();
    assertTrue(stmt.isClosed());
    assertTrue(conn.getAutoCommit());
}
Example 19
Project: transactions-essentials-master  File: XaResourceRecoveryManager.java View source code
public void recover(XAResource xaResource) {
    List<XID> xidsToRecover = retrievePreparedXidsFromXaResource(xaResource);
    Collection<XID> xidsToCommit;
    try {
        xidsToCommit = retrieveExpiredCommittingXidsFromLog();
        for (XID xid : xidsToRecover) {
            if (xidsToCommit.contains(xid)) {
                replayCommit(xid, xaResource);
            } else {
                attemptPresumedAbort(xid, xaResource);
            }
        }
    } catch (LogException couldNotRetrieveCommittingXids) {
        LOGGER.logWarning("Transient error while recovering - will retry later...", couldNotRetrieveCommittingXids);
    }
}
Example 20
Project: bitronix-hp-master  File: DelistmentTest.java View source code
public void testDelistErrorOnCommit() throws Exception {
    btm.begin();
    Connection connection1 = poolingDataSource1.getConnection();
    PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1;
    XAConnection xaConnection1 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle1.getPooledConnection());
    MockXAResource xaResource1 = (MockXAResource) xaConnection1.getXAResource();
    // triggers enlistment
    connection1.createStatement();
    xaResource1.setEndException(new BitronixXAException("screw delistment", XAException.XAER_RMERR));
    xaResource1.setRollbackException(new BitronixXAException("delistment was screwed, cannot rollback", XAException.XAER_RMERR));
    Connection connection2 = poolingDataSource2.getConnection();
    PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2;
    XAConnection xaConnection2 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle2.getPooledConnection());
    MockXAResource xaResource2 = (MockXAResource) xaConnection2.getXAResource();
    // triggers enlistment
    connection2.createStatement();
    try {
        btm.commit();
        fail("expected RollbackException");
    } catch (RollbackException ex) {
        assertEquals("delistment error caused transaction rollback" + System.getProperty("line.separator") + "  resource(s) [pds1] could not be delisted", ex.getMessage());
    }
    // check flow
    List orderedEvents = EventRecorder.getOrderedEvents();
    log.info(EventRecorder.dumpToString());
    assertEquals(9, orderedEvents.size());
    int i = 0;
    assertEquals(Status.STATUS_ACTIVE, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(Status.STATUS_MARKED_ROLLBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(Status.STATUS_ROLLING_BACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertTrue(((XAResourceRollbackEvent) orderedEvents.get(i++)).getSource() == xaResource2);
    assertEquals(Status.STATUS_ROLLEDBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
}
Example 21
Project: btm-fork-master  File: DelistmentTest.java View source code
public void testDelistErrorOnCommit() throws Exception {
    btm.begin();
    Connection connection1 = poolingDataSource1.getConnection();
    JdbcConnectionHandle handle1 = (JdbcConnectionHandle) Proxy.getInvocationHandler(connection1);
    XAConnection xaConnection1 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle1.getPooledConnection());
    MockXAResource xaResource1 = (MockXAResource) xaConnection1.getXAResource();
    // triggers enlistment
    connection1.createStatement();
    xaResource1.setEndException(new BitronixXAException("screw delistment", XAException.XAER_RMERR));
    xaResource1.setRollbackException(new BitronixXAException("delistment was screwed, cannot rollback", XAException.XAER_RMERR));
    Connection connection2 = poolingDataSource2.getConnection();
    JdbcConnectionHandle handle2 = (JdbcConnectionHandle) Proxy.getInvocationHandler(connection2);
    XAConnection xaConnection2 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle2.getPooledConnection());
    MockXAResource xaResource2 = (MockXAResource) xaConnection2.getXAResource();
    // triggers enlistment
    connection2.createStatement();
    try {
        btm.commit();
        fail("expected RollbackException");
    } catch (RollbackException ex) {
        assertEquals("delistment error caused transaction rollback" + System.getProperty("line.separator") + "  resource(s) [pds1] could not be delisted", ex.getMessage());
    }
    // check flow
    List orderedEvents = EventRecorder.getOrderedEvents();
    log.info(EventRecorder.dumpToString());
    assertEquals(9, orderedEvents.size());
    int i = 0;
    assertEquals(Status.STATUS_ACTIVE, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(Status.STATUS_MARKED_ROLLBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag());
    assertEquals(Status.STATUS_ROLLING_BACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
    assertTrue(((XAResourceRollbackEvent) orderedEvents.get(i++)).getSource() == xaResource2);
    assertEquals(Status.STATUS_ROLLEDBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus());
}
Example 22
Project: droolsjbpm-master  File: LrcXAResource.java View source code
public void start(Xid xid, int flag) throws XAException {
    if (flag != XAResource.TMNOFLAGS && flag != XAResource.TMJOIN)
        throw new BitronixXAException("unsupported start flag " + Decoder.decodeXAResourceFlag(flag), XAException.XAER_RMERR);
    if (xid == null)
        throw new BitronixXAException("XID cannot be null", XAException.XAER_INVAL);
    if (state == NO_TX) {
        if (this.xid != null)
            throw new BitronixXAException("resource already started on XID " + this.xid, XAException.XAER_PROTO);
        else {
            if (flag == XAResource.TMJOIN)
                throw new BitronixXAException("resource not yet started", XAException.XAER_PROTO);
            else {
                if (log.isDebugEnabled())
                    log.debug("OK to start, old state=" + xlatedState() + ", XID=" + xid + ", flag=" + Decoder.decodeXAResourceFlag(flag));
                this.xid = xid;
            }
        }
    } else if (state == STARTED) {
        throw new BitronixXAException("resource already started on XID " + this.xid, XAException.XAER_PROTO);
    } else if (state == ENDED) {
        if (flag == XAResource.TMNOFLAGS)
            throw new BitronixXAException("resource already registered XID " + this.xid, XAException.XAER_DUPID);
        else {
            if (xid.equals(this.xid)) {
                if (log.isDebugEnabled())
                    log.debug("OK to join, old state=" + xlatedState() + ", XID=" + xid + ", flag=" + Decoder.decodeXAResourceFlag(flag));
            } else
                throw new BitronixXAException("resource already started on XID " + this.xid + " - cannot start it on more than one XID at a time", XAException.XAER_RMERR);
        }
    } else if (state == PREPARED) {
        throw new BitronixXAException("resource already prepared on XID " + this.xid, XAException.XAER_PROTO);
    }
    this.state = STARTED;
}
Example 23
Project: zdal-master  File: TxConnectionManager.java View source code
public ConnectionListener createConnectionListener(ManagedConnection mc, Object context) throws ResourceException {
    XAResource xaResource = null;
    if (localTransactions) {
        xaResource = new LocalXAResource(log);
    //            if (log.isDebugEnabled() && xaResourceTimeout != 0) {
    //                log.debug("XAResource transaction timeout cannot be set for local transactions: "
    //                          + getName());
    //            }
    } else {
        throw new UnsupportedOperationException("Support local transactions only");
    //         xaResource = JcaXAResourceWrapperFactory.getResourceWrapper(mc.getXAResource(), isSameRMOverrideValue);
    //
    //         if (xaResourceTimeout != 0)
    //         {
    //            try
    //            {
    //               if (xaResource.setTransactionTimeout(xaResourceTimeout) == false)
    //                  log.debug("XAResource does not support transaction timeout configuration: " + getName());
    //            }
    //            catch (XAException e)
    //            {
    //               throw new JBossResourceException("Unable to set XAResource transaction timeout: " + getName(), e);
    //            }
    //         }
    }
    ConnectionListener cli = new TxConnectionEventListener(mc, poolingStrategy, context, log, xaResource);
    mc.addConnectionEventListener(cli);
    return cli;
}
Example 24
Project: cloudtm-data-platform-master  File: RehashTestBase.java View source code
@Override
public void run() {
    try {
        // start a transaction on c1.
        TransactionManager t1 = TestingUtil.getTransactionManager(c1);
        t1.begin();
        c1.put(keys.get(0), "transactionally_replaced");
        Transaction tx = t1.getTransaction();
        tx.enlistResource(new XAResourceAdapter() {

            public int prepare(Xid id) {
                // this would be called *after* the cache prepares.
                try {
                    l.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return XAResource.XA_OK;
            }
        });
        t1.commit();
    } catch (Exception e) {
        log.error("Error committing transaction", e);
        rollback.set(true);
        throw new RuntimeException(e);
    }
}
Example 25
Project: ehcache3-master  File: EhcacheXAResource.java View source code
@Override
public Xid[] recover(int flags) throws XAException {
    if (flags != XAResource.TMNOFLAGS && flags != XAResource.TMSTARTRSCAN && flags != XAResource.TMENDRSCAN && flags != (XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN)) {
        throw new EhcacheXAException("Recover flags not supported : " + xaResourceFlagsToString(flags), XAException.XAER_INVAL);
    }
    if ((flags & XAResource.TMSTARTRSCAN) == XAResource.TMSTARTRSCAN) {
        List<Xid> xids = new ArrayList<Xid>();
        Set<TransactionId> transactionIds = journal.recover().keySet();
        for (TransactionId transactionId : transactionIds) {
            // filter-out in-flight tx
            if (!transactionContextFactory.contains(transactionId)) {
                xids.add(transactionId.getSerializableXid());
            }
        }
        return xids.toArray(new Xid[xids.size()]);
    }
    return new Xid[0];
}
Example 26
Project: haze-master  File: ClientXATest.java View source code
@Test
public void testIsSame() throws Exception {
    HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
    HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
    XAResource resource1 = instance1.getXAResource();
    XAResource resource2 = instance2.getXAResource();
    HazelcastInstance client = HazelcastClient.newHazelcastClient();
    XAResource clientResource = client.getXAResource();
    assertTrue(clientResource.isSameRM(resource1));
    assertTrue(clientResource.isSameRM(resource2));
}
Example 27
Project: hazelcast-code-samples-master  File: XATransaction.java View source code
public static void main(String[] args) throws Exception {
    cleanAtomikosLogs();
    HazelcastInstance instance = Hazelcast.newHazelcastInstance();
    HazelcastXAResource xaResource = instance.getXAResource();
    UserTransactionManager tm = new UserTransactionManager();
    tm.begin();
    Transaction transaction = tm.getTransaction();
    transaction.enlistResource(xaResource);
    TransactionContext context = xaResource.getTransactionContext();
    TransactionalMap<Object, Object> map = context.getMap("map");
    map.put("key", "val");
    transaction.delistResource(xaResource, XAResource.TMSUCCESS);
    tm.commit();
    IMap<Object, Object> m = instance.getMap("map");
    Object val = m.get("key");
    System.out.println("value: " + val);
    cleanAtomikosLogs();
    Hazelcast.shutdownAll();
}
Example 28
Project: hazelcast-master  File: ClientXATest.java View source code
@Test
public void testIsSame() throws Exception {
    HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
    HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
    XAResource resource1 = instance1.getXAResource();
    XAResource resource2 = instance2.getXAResource();
    HazelcastInstance client = HazelcastClient.newHazelcastClient();
    XAResource clientResource = client.getXAResource();
    assertTrue(clientResource.isSameRM(resource1));
    assertTrue(clientResource.isSameRM(resource2));
}
Example 29
Project: jackrabbit-master  File: UserTransactionImpl.java View source code
/**
     * @see javax.transaction.UserTransaction#begin
     */
public void begin() throws NotSupportedException, SystemException {
    if (status != Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("Transaction already active");
    }
    try {
        for (Iterator it = xaResources.keySet().iterator(); it.hasNext(); ) {
            XAResource resource = (XAResource) it.next();
            XidImpl xid = (XidImpl) xaResources.get(resource);
            resource.start(xid, XAResource.TMNOFLAGS);
        }
        status = Status.STATUS_ACTIVE;
    } catch (XAException e) {
        throw new SystemException("Unable to begin transaction: " + "XA_ERR=" + e.errorCode);
    }
}
Example 30
Project: JBossAS51-master  File: XAResourceUnitTestCase.java View source code
public void testXAResourceSuspendWorkCommit() throws Exception {
    InitialContext context = getInitialContext();
    XATopicConnectionFactory factory = (XATopicConnectionFactory) context.lookup(XA_TOPIC_FACTORY);
    Topic topic = (Topic) context.lookup(TEST_TOPIC);
    XATopicConnection connection = factory.createXATopicConnection();
    try {
        // Set up
        XATopicSession xaSession = connection.createXATopicSession();
        TopicSession session = xaSession.getTopicSession();
        TopicPublisher publisher = session.createPublisher(topic);
        Message message = session.createTextMessage();
        // Add the xa resource to xid1
        MyXid xid1 = new MyXid();
        XAResource resource = xaSession.getXAResource();
        resource.start(xid1, XAResource.TMNOFLAGS);
        // Do some work
        publisher.publish(message);
        // Suspend the transaction
        resource.end(xid1, XAResource.TMSUSPEND);
        // Add the xa resource to xid2
        MyXid xid2 = new MyXid();
        resource.start(xid2, XAResource.TMNOFLAGS);
        // Do some work in the new transaction
        publisher.publish(message);
        // Commit the first transaction and end the branch
        resource.end(xid1, XAResource.TMSUCCESS);
        resource.commit(xid1, true);
        // Do some more work in the new transaction
        publisher.publish(message);
        // Commit the second transaction and end the branch
        resource.end(xid2, XAResource.TMSUCCESS);
        resource.commit(xid2, true);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        connection.close();
    }
}
Example 31
Project: JBossAS_5_1_EDG-master  File: XAResourceUnitTestCase.java View source code
public void testXAResourceSuspendWorkCommit() throws Exception {
    InitialContext context = getInitialContext();
    XATopicConnectionFactory factory = (XATopicConnectionFactory) context.lookup(XA_TOPIC_FACTORY);
    Topic topic = (Topic) context.lookup(TEST_TOPIC);
    XATopicConnection connection = factory.createXATopicConnection();
    try {
        // Set up
        XATopicSession xaSession = connection.createXATopicSession();
        TopicSession session = xaSession.getTopicSession();
        TopicPublisher publisher = session.createPublisher(topic);
        Message message = session.createTextMessage();
        // Add the xa resource to xid1
        MyXid xid1 = new MyXid();
        XAResource resource = xaSession.getXAResource();
        resource.start(xid1, XAResource.TMNOFLAGS);
        // Do some work
        publisher.publish(message);
        // Suspend the transaction
        resource.end(xid1, XAResource.TMSUSPEND);
        // Add the xa resource to xid2
        MyXid xid2 = new MyXid();
        resource.start(xid2, XAResource.TMNOFLAGS);
        // Do some work in the new transaction
        publisher.publish(message);
        // Commit the first transaction and end the branch
        resource.end(xid1, XAResource.TMSUCCESS);
        resource.commit(xid1, true);
        // Do some more work in the new transaction
        publisher.publish(message);
        // Commit the second transaction and end the branch
        resource.end(xid2, XAResource.TMSUCCESS);
        resource.commit(xid2, true);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        connection.close();
    }
}
Example 32
Project: jcr-springextension-master  File: JackRabbitUserTransaction.java View source code
/**
     * @see javax.transaction.UserTransaction#begin
     */
public void begin() throws NotSupportedException, SystemException {
    if (status != Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("Transaction already active");
    }
    try {
        xid = new XidImpl(counter++);
        xares.start(xid, XAResource.TMNOFLAGS);
        status = Status.STATUS_ACTIVE;
    } catch (XAException e) {
        final SystemException systemException = new SystemException("Unable to commit transaction: " + "XA_ERR=" + e.errorCode);
        systemException.initCause(e);
        throw systemException;
    }
}
Example 33
Project: Metamorphosis-master  File: TransactionProcessorUnitTest.java View source code
@Test
public void testHandlePrepare() throws Exception {
    final String sessionId = "test";
    final LocalTransactionId transactionId = new LocalTransactionId(sessionId, 1);
    final TransactionInfo info = new TransactionInfo(transactionId, sessionId, TransactionType.PREPARE);
    final TransactionCommand tc = new TransactionCommand(info, 1);
    EasyMock.expect(this.commandProcessor.prepareTransaction(new SessionContextImpl(sessionId, this.conn), transactionId)).andReturn(XAResource.XA_OK);
    this.conn.response(new BooleanCommand(HttpStatus.Success, String.valueOf(XAResource.XA_OK), 1));
    this.mockSessionContext(sessionId, sessionId);
    this.replay();
    this.transactionProcessor.handleRequest(tc, this.conn);
}
Example 34
Project: pentaho-platform-master  File: PentahoTransactionManagerTest.java View source code
@Test
public void getTransactionDefinition() throws Exception {
    PentahoTransactionManager transactionManager = new PentahoTransactionManager();
    SessionFactory sessionFactory = mock(SessionFactory.class);
    XASession xaSession = mock(XASession.class);
    when(xaSession.getXAResource()).thenReturn(mock(XAResource.class));
    transactionManager.setSessionFactory(sessionFactory);
    TransactionDefinition transactionDefinition = mock(TransactionDefinition.class);
    when(transactionDefinition.getIsolationLevel()).thenReturn(-1);
    // Main assertion. While doBegin is being called, the transactionDefinition can be reached.
    AtomicBoolean wasAvailable = new AtomicBoolean(false);
    when(sessionFactory.getSession()).then( invocation -> {
        assertEquals(transactionDefinition, transactionManager.getTransactionDefinition());
        wasAvailable.set(true);
        return xaSession;
    });
    transactionManager.getTransaction(transactionDefinition);
    assertTrue(wasAvailable.get());
    // after life of doBegin call the definition is not available
    assertNull(transactionManager.getTransactionDefinition());
}
Example 35
Project: wunderboss-master  File: JMSXAContext.java View source code
@Override
public boolean enlist() throws Exception {
    if (TransactionUtil.tm.getTransaction() == null) {
        return super.isXAEnabled();
    } else if (!WunderBoss.inContainer() || isRemote()) {
        XAResource resource = ((XASession) jmsSession()).getXAResource();
        return TransactionUtil.tm.getTransaction().enlistResource(resource);
    } else {
        return true;
    }
}
Example 36
Project: akubra-master  File: ServerTransactionListener.java View source code
public boolean delistResource(XAResource xaRes, int flags) throws IllegalStateException, SystemException {
    ServerXAResource xa = xas.get(xaRes);
    if (xa == null)
        return false;
    boolean ret;
    try {
        ret = executeOnClient(new DelistXAResource(xa, flags));
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof SystemException)
            throw (SystemException) cause;
        if (cause instanceof RuntimeException)
            throw (RuntimeException) cause;
        throw new RuntimeException("Error reported by server", cause);
    }
    if (ret)
        xas.remove(xaRes);
    return ret;
}
Example 37
Project: aries-master  File: TransactionControlImpl.java View source code
@Override
public NamedXAResource getNamedXAResource() throws SystemException {
    try {
        XAResource xaResource = resource.getXAResource();
        if (xaResource == null) {
            throw new IllegalStateException("The recoverable resource " + resource.getId() + " is currently unavailable");
        }
        return new NamedXAResourceImpl(resource.getId(), xaResource, transactionManager, false);
    } catch (Exception e) {
        throw new SystemException("Unable to get recoverable resource " + resource.getId() + ": " + e.getMessage());
    }
}
Example 38
Project: camel-trade-master  File: DumpTransaction.java View source code
/**
	 * Logs current transaction data
	 * @param exchange An optional exchange
	 */
public static void dumpTx(Exchange exchange) {
    StringBuilder b = new StringBuilder("\nTransaction Dump:");
    if (exchange != null) {
        b.append("\n\tExchange ID:").append(exchange.getExchangeId());
        if (exchange.getFromRouteId() != null)
            b.append("\n\tFrom Route:").append(exchange.getFromRouteId());
    }
    b.append("\n\tThread:").append(Thread.currentThread().toString());
    b.append("\n\tTX Status:").append(TransactionHelper.getTransactionState());
    b.append("\n\tTX UID:").append(TransactionHelper.getTransactionUID());
    b.append("\n\tXA Resources:");
    for (XAResource xar : TransactionHelper.getTransactionResources().keySet()) {
        b.append("\n\t\t[").append(xar.getClass().getName()).append("]:").append(xar);
    }
    b.append("\n===================");
    log.info(b);
}
Example 39
Project: graphdb-traversal-context-master  File: PersistenceManager.java View source code
void delistResourcesForTransaction() throws NotInTransactionException {
    Transaction tx = this.getCurrentTransaction();
    if (tx == null) {
        throw new NotInTransactionException();
    }
    ResourceConnection con = txConnectionMap.get(tx);
    if (con != null) {
        try {
            tx.delistResource(con.getXAResource(), XAResource.TMSUCCESS);
        } catch (SystemException e) {
            throw new TransactionFailureException("Failed to delist resource '" + con + "' from current transaction.", e);
        }
    }
}
Example 40
Project: GraphDHT-master  File: PersistenceManager.java View source code
void delistResourcesForTransaction() throws NotInTransactionException {
    Transaction tx = this.getCurrentTransaction();
    ResourceConnection con = txConnectionMap.get(tx);
    if (con != null) {
        try {
            tx.delistResource(con.getXAResource(), XAResource.TMSUCCESS);
        } catch (SystemException e) {
            throw new TransactionFailureException("Failed to delist resource '" + con + "' from current transaction.", e);
        }
    }
}
Example 41
Project: h2-bitmap-master  File: TestDataSource.java View source code
private void testXAConnection(boolean userInDataSource) throws Exception {
    deleteDb("dataSource");
    JdbcDataSource ds = new JdbcDataSource();
    String url = getURL("dataSource", true);
    String user = getUser();
    ds.setURL(url);
    if (userInDataSource) {
        ds.setUser(user);
        ds.setPassword(getPassword());
    }
    if (userInDataSource) {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=" + user, ds.toString());
    } else {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=", ds.toString());
    }
    XAConnection xaConn;
    if (userInDataSource) {
        xaConn = ds.getXAConnection();
    } else {
        xaConn = ds.getXAConnection(user, getPassword());
    }
    int traceId = ((JdbcXAConnection) xaConn).getTraceId();
    assertTrue(xaConn.toString().startsWith("xads" + traceId + ": conn"));
    xaConn.addConnectionEventListener(new ConnectionEventListener() {

        public void connectionClosed(ConnectionEvent event) {
        // nothing to do
        }

        public void connectionErrorOccurred(ConnectionEvent event) {
        // nothing to do
        }
    });
    XAResource res = xaConn.getXAResource();
    assertFalse(res.setTransactionTimeout(1));
    assertEquals(0, res.getTransactionTimeout());
    assertTrue(res.isSameRM(res));
    assertFalse(res.isSameRM(null));
    Connection conn = xaConn.getConnection();
    assertEquals(user.toUpperCase(), conn.getMetaData().getUserName());
    Xid[] list = res.recover(XAResource.TMSTARTRSCAN);
    assertEquals(0, list.length);
    Statement stat = conn.createStatement();
    stat.execute("SELECT * FROM DUAL");
    conn.close();
    xaConn.close();
}
Example 42
Project: H2-Mirror-master  File: TestDataSource.java View source code
private void testXAConnection(boolean userInDataSource) throws Exception {
    deleteDb("dataSource");
    JdbcDataSource ds = new JdbcDataSource();
    String url = getURL("dataSource", true);
    String user = getUser();
    ds.setURL(url);
    if (userInDataSource) {
        ds.setUser(user);
        ds.setPassword(getPassword());
    }
    if (userInDataSource) {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=" + user, ds.toString());
    } else {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=", ds.toString());
    }
    XAConnection xaConn;
    if (userInDataSource) {
        xaConn = ds.getXAConnection();
    } else {
        xaConn = ds.getXAConnection(user, getPassword());
    }
    int traceId = ((JdbcXAConnection) xaConn).getTraceId();
    assertTrue(xaConn.toString().startsWith("xads" + traceId + ": conn"));
    xaConn.addConnectionEventListener(new ConnectionEventListener() {

        @Override
        public void connectionClosed(ConnectionEvent event) {
        // nothing to do
        }

        @Override
        public void connectionErrorOccurred(ConnectionEvent event) {
        // nothing to do
        }
    });
    XAResource res = xaConn.getXAResource();
    assertFalse(res.setTransactionTimeout(1));
    assertEquals(0, res.getTransactionTimeout());
    assertTrue(res.isSameRM(res));
    assertFalse(res.isSameRM(null));
    Connection conn = xaConn.getConnection();
    assertEquals(user.toUpperCase(), conn.getMetaData().getUserName());
    Xid[] list = res.recover(XAResource.TMSTARTRSCAN);
    assertEquals(0, list.length);
    Statement stat = conn.createStatement();
    stat.execute("SELECT * FROM DUAL");
    conn.close();
    xaConn.close();
}
Example 43
Project: H2-Research-master  File: TestDataSource.java View source code
private void testXAConnection(boolean userInDataSource) throws Exception {
    deleteDb("dataSource");
    JdbcDataSource ds = new JdbcDataSource();
    String url = getURL("dataSource", true);
    String user = getUser();
    ds.setURL(url);
    if (userInDataSource) {
        ds.setUser(user);
        ds.setPassword(getPassword());
    }
    if (userInDataSource) {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=" + user, ds.toString());
    } else {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=", ds.toString());
    }
    XAConnection xaConn;
    if (userInDataSource) {
        xaConn = ds.getXAConnection();
    } else {
        xaConn = ds.getXAConnection(user, getPassword());
    }
    int traceId = ((JdbcXAConnection) xaConn).getTraceId();
    assertTrue(xaConn.toString().startsWith("xads" + traceId + ": conn"));
    xaConn.addConnectionEventListener(new ConnectionEventListener() {

        @Override
        public void connectionClosed(ConnectionEvent event) {
        // nothing to do
        }

        @Override
        public void connectionErrorOccurred(ConnectionEvent event) {
        // nothing to do
        }
    });
    XAResource res = xaConn.getXAResource();
    assertFalse(res.setTransactionTimeout(1));
    assertEquals(0, res.getTransactionTimeout());
    assertTrue(res.isSameRM(res));
    assertFalse(res.isSameRM(null));
    Connection conn = xaConn.getConnection();
    assertEquals(user.toUpperCase(), conn.getMetaData().getUserName());
    Xid[] list = res.recover(XAResource.TMSTARTRSCAN);
    assertEquals(0, list.length);
    Statement stat = conn.createStatement();
    stat.execute("SELECT * FROM DUAL");
    conn.close();
    xaConn.close();
}
Example 44
Project: h2database-master  File: TestDataSource.java View source code
private void testXAConnection(boolean userInDataSource) throws Exception {
    deleteDb("dataSource");
    JdbcDataSource ds = new JdbcDataSource();
    String url = getURL("dataSource", true);
    String user = getUser();
    ds.setURL(url);
    if (userInDataSource) {
        ds.setUser(user);
        ds.setPassword(getPassword());
    }
    if (userInDataSource) {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=" + user, ds.toString());
    } else {
        assertEquals("ds" + ds.getTraceId() + ": url=" + url + " user=", ds.toString());
    }
    XAConnection xaConn;
    if (userInDataSource) {
        xaConn = ds.getXAConnection();
    } else {
        xaConn = ds.getXAConnection(user, getPassword());
    }
    int traceId = ((JdbcXAConnection) xaConn).getTraceId();
    assertTrue(xaConn.toString().startsWith("xads" + traceId + ": conn"));
    xaConn.addConnectionEventListener(new ConnectionEventListener() {

        @Override
        public void connectionClosed(ConnectionEvent event) {
        // nothing to do
        }

        @Override
        public void connectionErrorOccurred(ConnectionEvent event) {
        // nothing to do
        }
    });
    XAResource res = xaConn.getXAResource();
    assertFalse(res.setTransactionTimeout(1));
    assertEquals(0, res.getTransactionTimeout());
    assertTrue(res.isSameRM(res));
    assertFalse(res.isSameRM(null));
    Connection conn = xaConn.getConnection();
    assertEquals(user.toUpperCase(), conn.getMetaData().getUserName());
    Xid[] list = res.recover(XAResource.TMSTARTRSCAN);
    assertEquals(0, list.length);
    Statement stat = conn.createStatement();
    stat.execute("SELECT * FROM DUAL");
    conn.close();
    xaConn.close();
}
Example 45
Project: ironjacamar-master  File: McCodeGen.java View source code
/**
    * Output class import
    *
    * @param def definition
    * @param out Writer
    * @throws IOException ioException
    */
@Override
public void writeImport(Definition def, Writer out) throws IOException {
    out.write("package " + def.getRaPackage() + ";\n\n");
    if (def.isSupportEis()) {
        out.write("import java.io.IOException;\n");
    }
    out.write("import java.io.PrintWriter;\n");
    if (def.isSupportEis()) {
        out.write("import java.net.Socket;\n");
    }
    out.write("import java.util.ArrayList;\n");
    out.write("import java.util.Collections;\n");
    out.write("import java.util.HashSet;\n");
    out.write("import java.util.List;\n");
    out.write("import java.util.Set;\n");
    importLogging(def, out);
    out.write("import javax.resource.NotSupportedException;\n");
    out.write("import javax.resource.ResourceException;\n");
    out.write("import javax.resource.spi.ConnectionEvent;\n");
    out.write("import javax.resource.spi.ConnectionEventListener;\n");
    out.write("import javax.resource.spi.ConnectionRequestInfo;\n");
    out.write("import javax.resource.spi.LocalTransaction;\n");
    out.write("import javax.resource.spi.ManagedConnection;\n");
    out.write("import javax.resource.spi.ManagedConnectionMetaData;\n\n");
    out.write("import javax.security.auth.Subject;\n");
    out.write("import javax.transaction.xa.XAResource;\n\n");
}
Example 46
Project: jboss-messaging-master  File: MessagingXAResourceWrapper.java View source code
/**
    * Get the connectionFactory XAResource
    * 
    * @return the connectionFactory
    * @throws XAException for any problem
    */
public XAResource getDelegate() throws XAException {
    XAResource result = null;
    Exception error = null;
    try {
        result = connect();
    } catch (Exception e) {
        log.error("********************************Failed to connect to server", e);
        error = e;
    }
    if (result == null) {
        XAException xae = new XAException("Error trying to connect to provider " + providerName);
        xae.errorCode = XAException.XAER_RMERR;
        if (error != null)
            xae.initCause(error);
        log.debug("Cannot get connectionFactory XAResource", xae);
        throw xae;
    }
    return result;
}
Example 47
Project: mssql-jdbc-master  File: SQLServerXAConnection.java View source code
/**
     * Closes the physical connection that this PooledConnection object represents.
     */
public void close() throws SQLException {
    synchronized (this) {
        if (XAResource != null) {
            XAResource.close();
            XAResource = null;
        }
        if (null != physicalControlConnection) {
            physicalControlConnection.close();
            physicalControlConnection = null;
        }
    }
    super.close();
}
Example 48
Project: neo4j-components-svn-master  File: PersistenceManager.java View source code
void delistResourcesForTransaction() throws NotInTransactionException {
    Transaction tx = this.getCurrentTransaction();
    if (tx == null) {
        throw new NotInTransactionException();
    }
    ResourceConnection con = txConnectionMap.get(tx);
    if (con != null) {
        try {
            tx.delistResource(con.getXAResource(), XAResource.TMSUCCESS);
        } catch (SystemException e) {
            throw new TransactionFailureException("Failed to delist resource '" + con + "' from current transaction.", e);
        }
    }
}
Example 49
Project: neo4j-mobile-android-master  File: XaDataSourceManager.java View source code
synchronized byte[] getBranchId(XAResource xaResource) {
    if (xaResource instanceof XaResource) {
        byte branchId[] = ((XaResource) xaResource).getBranchId();
        if (branchId != null) {
            return branchId;
        }
    }
    Iterator<Map.Entry<String, XaDataSource>> itr = dataSources.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, XaDataSource> entry = itr.next();
        XaDataSource dataSource = entry.getValue();
        XAResource resource = dataSource.getXaConnection().getXaResource();
        try {
            if (resource.isSameRM(xaResource)) {
                String name = entry.getKey();
                return sourceIdMapping.get(name);
            }
        } catch (XAException e) {
            throw new TransactionFailureException("Unable to check is same resource", e);
        }
    }
    throw new TransactionFailureException("Unable to find mapping for XAResource[" + xaResource + "]");
}
Example 50
Project: openknowledge-cdi-extensions-master  File: TransactionImpl.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    status = Status.STATUS_COMMITTING;
    try {
        for (XAResource res : resources) {
            res.prepare(xid);
        }
        for (XAResource res : resources) {
            res.commit(xid, false);
        }
    } catch (XAException e) {
        throw new SystemException(e.toString());
    }
    status = Status.STATUS_COMMITTED;
}
Example 51
Project: orientdb-jca-master  File: OrientDBTransactionXA.java View source code
public void start(final Xid xid, final int flags) throws XAException {
    boolean tmJoin = (flags & XAResource.TMJOIN) != 0;
    boolean tmResume = (flags & XAResource.TMRESUME) != 0;
    /* Check flags - only one of TMNOFLAGS, TMJOIN, or TMRESUME. */
    if (xid == null || (tmJoin && tmResume) || (!tmJoin && !tmResume && flags != XAResource.TMNOFLAGS)) {
        throw new XAException(XAException.XAER_INVAL);
    }
    database.begin();
    logger.info("xa begin");
}
Example 52
Project: pinus4j-master  File: GlobalJdbcUpdateImpl.java View source code
@Override
public PKValue[] saveBatch(List<? extends Object> entities, String clusterName, boolean autoGeneratedKeys) {
    Class<?> clazz = entities.get(0).getClass();
    String tableName = entityMetaManager.getTableName(clazz);
    List<PKValue> pks = new ArrayList<PKValue>();
    Transaction tx = null;
    IDBResource dbResource = null;
    try {
        tx = txManager.getTransaction();
        dbResource = this.dbCluster.getMasterGlobalDBResource(clusterName, entityMetaManager.getTableName(clazz));
        Connection conn = dbResource.getConnection();
        int insertCount = 0;
        if (autoGeneratedKeys) {
            pks = _saveBatchWithAutoGeneratedKeys(conn, entities, -1);
            insertCount = pks.size();
        } else {
            insertCount = _saveBatchWithoutAutoGeneratedKeys(conn, entities, -1);
        }
        if (tx != null) {
            tx.enlistResource((XAResource) dbResource);
        } else {
            dbResource.commit();
        }
        if (isCacheAvailable(clazz) && insertCount > 0) {
            primaryCache.incrCountGlobal(clusterName, tableName, insertCount);
        }
        if (isSecondCacheAvailable(clazz) && insertCount > 0) {
            secondCache.removeGlobal(clusterName, tableName);
        }
    } catch (Exception e1) {
        if (tx == null && dbResource != null)
            dbResource.rollback();
        throw new DBOperationException(e1);
    } finally {
        if (tx == null && dbResource != null) {
            dbResource.close();
        }
    }
    return pks.toArray(new PKValue[pks.size()]);
}
Example 53
Project: resin-master  File: SpyXAResource.java View source code
/**
   * Returns true if the underlying RM is the same.
   */
@Override
public boolean isSameRM(XAResource resource) throws XAException {
    long start = start();
    try {
        if (resource instanceof SpyXAResource)
            resource = ((SpyXAResource) resource).getXAResource();
        boolean same = _xaResource.isSameRM(resource);
        if (log.isLoggable(Level.FINE))
            log(start, "is-same-rm(resource=" + resource + ")->" + same);
        return same;
    } catch (XAException e) {
        log.log(Level.FINE, e.toString(), e);
        throw e;
    } catch (RuntimeException e) {
        log.log(Level.FINE, e.toString(), e);
        throw e;
    }
}
Example 54
Project: s2util-master  File: TransactionUtil.java View source code
/**
     * トランザクション��加���。
     * 
     * @param tx
     *            トランザクション。{@literal null}���������ん
     * @param xaResource
     *            XAリソース。{@literal null}���������ん
     */
public static void enlistResource(final Transaction tx, final XAResource xaResource) {
    assertArgumentNotNull("tx", tx);
    assertArgumentNotNull("xaResource", xaResource);
    try {
        tx.enlistResource(xaResource);
    } catch (final SystemException e) {
        throw new SystemRuntimeException(e);
    } catch (final RollbackException e) {
        throw new RollbackRuntimeException(e);
    }
}
Example 55
Project: h-store-master  File: JDBCXAResource.java View source code
/**
     * @throws XAException if the given Xid is the not the Xid of the
     *                     current transaction for this XAResource object.
     */
private void validateXid(Xid xid) throws XAException {
    if (xid == null) {
        throw new XAException("Null Xid");
    }
    if (this.xid == null) {
        throw new XAException("There is no live transaction for this XAResource");
    }
    if (!xid.equals(this.xid)) {
        throw new XAException("Given Xid is not that associated with this XAResource object");
    }
}
Example 56
Project: mut4j-master  File: JDBCXAResource.java View source code
/**
     * @throws XAException if the given Xid is the not the Xid of the
     *                     current transaction for this XAResource object.
     */
private void validateXid(Xid xid) throws XAException {
    if (xid == null) {
        throw new XAException("Null Xid");
    }
    if (this.xid == null) {
        throw new XAException("There is no live transaction for this XAResource");
    }
    if (!xid.equals(this.xid)) {
        throw new XAException("Given Xid is not that associated with this XAResource object");
    }
}
Example 57
Project: StoryBear-master  File: JDBCXAResource.java View source code
/**
     *
     * @throws XAException if the given Xid is the not the Xid of the current
     *   transaction for this XAResource object.
     * @param xid Xid
     */
private void validateXid(Xid xid) throws XAException {
    if (xid == null) {
        throw new XAException("Null Xid");
    }
    if (this.xid == null) {
        throw new XAException("There is no live transaction for this XAResource");
    }
    if (!xid.equals(this.xid)) {
        throw new XAException("Given Xid is not that associated with this XAResource object");
    }
}
Example 58
Project: voltdb-master  File: JDBCXAResource.java View source code
/**
     * @throws XAException if the given Xid is the not the Xid of the
     *                     current transaction for this XAResource object.
     */
private void validateXid(Xid xid) throws XAException {
    if (xid == null) {
        throw new XAException("Null Xid");
    }
    if (this.xid == null) {
        throw new XAException("There is no live transaction for this XAResource");
    }
    if (!xid.equals(this.xid)) {
        throw new XAException("Given Xid is not that associated with this XAResource object");
    }
}
Example 59
Project: bboss-master  File: TransactionContext.java View source code
/**
     * Sets the shared connection for this transaction.  The shared connection is enlisted
     * in the transaction.
     *
     * @param sharedConnection the shared connection
     * @throws SQLException if a shared connection is already set, if XAResource for the connection
     * could not be found in the transaction registry, or if there was a problem enlisting the
     * connection in the transaction
     */
public void setSharedConnection(Connection sharedConnection) throws SQLException {
    if (this.sharedConnection != null) {
        throw new IllegalStateException("A shared connection is already set");
    }
    // This is the first use of the connection in this transaction, so we must
    // enlist it in the transaction
    Transaction transaction = getTransaction();
    try {
        XAResource xaResource = transactionRegistry.getXAResource(sharedConnection);
        if (!transaction.enlistResource(xaResource)) {
            throw new SQLException("Unable to enlist connection in transaction: enlistResource returns 'false'.");
        }
    } catch (RollbackException e) {
    } catch (SystemException e) {
        throw new SQLException("Unable to enlist connection the transaction", e);
    }
    this.sharedConnection = sharedConnection;
}
Example 60
Project: ByteTCC-master  File: SpringCloudCoordinator.java View source code
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Class<?> clazz = method.getDeclaringClass();
    String methodName = method.getName();
    if (Object.class.equals(clazz)) {
        return method.invoke(this, args);
    } else if (RemoteCoordinator.class.equals(clazz)) {
        if ("getIdentifier".equals(methodName)) {
            return this.identifier;
        } else {
            throw new XAException(XAException.XAER_RMFAIL);
        }
    } else if (XAResource.class.equals(clazz)) {
        if ("prepare".equals(methodName)) {
            return this.invokePostCoordinator(proxy, method, args);
        } else if ("commit".equals(methodName)) {
            return this.invokePostCoordinator(proxy, method, args);
        } else if ("rollback".equals(methodName)) {
            return this.invokePostCoordinator(proxy, method, args);
        } else if ("recover".equals(methodName)) {
            return this.invokeGetCoordinator(proxy, method, args);
        } else if ("forget".equals(methodName)) {
            return this.invokePostCoordinator(proxy, method, args);
        } else {
            throw new XAException(XAException.XAER_RMFAIL);
        }
    } else {
        throw new IllegalAccessException();
    }
}
Example 61
Project: commons-dbcp-optivo-master  File: TransactionContext.java View source code
/**
     * Sets the shared connection for this transaction.  The shared connection is enlisted
     * in the transaction.
     *
     * @param sharedConnection the shared connection
     * @throws SQLException if a shared connection is already set, if XAResource for the connection
     * could not be found in the transaction registry, or if there was a problem enlisting the
     * connection in the transaction
     */
public void setSharedConnection(Connection sharedConnection) throws SQLException {
    if (this.sharedConnection != null) {
        throw new IllegalStateException("A shared connection is alredy set");
    }
    // This is the first use of the connection in this transaction, so we must
    // enlist it in the transaction
    Transaction transaction = getTransaction();
    try {
        XAResource xaResource = transactionRegistry.getXAResource(sharedConnection);
        transaction.enlistResource(xaResource);
    } catch (RollbackException e) {
    } catch (SystemException e) {
        throw (SQLException) new SQLException("Unable to enlist connection the transaction").initCause(e);
    }
    this.sharedConnection = sharedConnection;
}
Example 62
Project: etk-component-master  File: TransactionServiceJotmImpl.java View source code
/**
    * {@inheritDoc}
    */
public void enlistResource(ExoResource exores) throws RollbackException, SystemException {
    XAResource xares = exores.getXAResource();
    ResourceEntry entry = new ResourceEntry(exores);
    exores.setPayload(entry);
    Transaction tx = getTransactionManager().getTransaction();
    if (tx != null) {
        current.getTransaction().enlistResource(xares);
    } else if (trackWithoutTransaction) {
        current.connectionOpened(entry);
        // actual only if current.connectionOpened(entry);
        // otherwise NPE inside the JOTM's Current 
        entry.jotmResourceList = popThreadLocalRMEventList();
        pushThreadLocalRMEventList(entry.jotmResourceList);
    }
}
Example 63
Project: hb-kg-master  File: JtaXAResource.java View source code
public int prepare(Xid xid) throws XAException {
    LOG.trace("prepare [" + xid.toString() + "] ");
    TransactionState state = xidToTransactionState.get(xid);
    int status;
    try {
        status = this.transactionManager.prepareCommit(state);
    } catch (CommitUnsuccessfulException e) {
        XAException xae = new XAException(XAException.XA_HEURRB);
        xae.initCause(e);
        throw xae;
    } catch (IOException e) {
        XAException xae = new XAException(XAException.XAER_RMERR);
        xae.initCause(e);
        throw xae;
    }
    switch(status) {
        case TransactionalRegionInterface.COMMIT_OK:
            return XAResource.XA_OK;
        case TransactionalRegionInterface.COMMIT_OK_READ_ONLY:
            return XAResource.XA_RDONLY;
        default:
            throw new XAException(XAException.XA_RBPROTO);
    }
}
Example 64
Project: hbase-secondary-index-master  File: JtaXAResource.java View source code
public int prepare(final Xid xid) throws XAException {
    LOG.trace("prepare [" + xid.toString() + "] ");
    TransactionState state = xidToTransactionState.get(xid);
    int status;
    try {
        status = this.transactionManager.prepareCommit(state);
    } catch (CommitUnsuccessfulException e) {
        XAException xae = new XAException(XAException.XA_HEURRB);
        xae.initCause(e);
        throw xae;
    } catch (IOException e) {
        XAException xae = new XAException(XAException.XAER_RMERR);
        xae.initCause(e);
        throw xae;
    }
    switch(status) {
        case TransactionalRegionInterface.COMMIT_OK:
            return XAResource.XA_OK;
        case TransactionalRegionInterface.COMMIT_OK_READ_ONLY:
            return XAResource.XA_RDONLY;
        default:
            throw new XAException(XAException.XA_RBPROTO);
    }
}
Example 65
Project: hbase-transactional-tableindexed-master  File: JtaXAResource.java View source code
public int prepare(final Xid xid) throws XAException {
    LOG.trace("prepare [" + xid.toString() + "] ");
    TransactionState state = xidToTransactionState.get(xid);
    int status;
    try {
        status = this.transactionManager.prepareCommit(state);
    } catch (CommitUnsuccessfulException e) {
        XAException xae = new XAException(XAException.XA_HEURRB);
        xae.initCause(e);
        throw xae;
    } catch (IOException e) {
        XAException xae = new XAException(XAException.XAER_RMERR);
        xae.initCause(e);
        throw xae;
    }
    switch(status) {
        case TransactionalRegionInterface.COMMIT_OK:
            return XAResource.XA_OK;
        case TransactionalRegionInterface.COMMIT_OK_READ_ONLY:
            return XAResource.XA_RDONLY;
        default:
            throw new XAException(XAException.XA_RBPROTO);
    }
}
Example 66
Project: jeplayer-master  File: JEPLJTAConnectionXAPoolImpl.java View source code
public void fixXAPool() throws SQLException {
    // http://stackoverflow.com/questions/6927561/standardxaconnectionhandlepreparestatement-should-not-be-used-outside-an-ejbser
    // http://www.java2s.com/Open-Source/Java-Document/Database-JDBC-Connection-Pool/xapool/org/enhydra/jdbc/standard/StandardXAConnectionHandle.java.htm
    // http://websvn.ow2.org/filedetails.php?repname=xapool&path=%2Ftrunk%2Fxapool%2Fsrc%2Forg%2Fenhydra%2Fjdbc%2Fstandard%2FStandardXAConnectionHandle.java
    Connection con = getConnection();
    // Usando reflection evitamos dependencias con JOTM
    try {
        if (// jotmCon.tx == null
        field_tx.get(con) == null) {
            // TransactionManager txnMgr = jotmCon.transactionManager;
            TransactionManager txnMgr = (TransactionManager) field_transactionManager.get(con);
            Transaction tx = txnMgr.getTransaction();
            if (tx != null) {
                // jotmCon.tx = tx;
                field_tx.set(con, tx);
                // boolean autoCommit = jotmCon.getAutoCommit();
                boolean autoCommit = (Boolean) method_getAutoCommit.invoke(con, (Object[]) null);
                // StandardXAConnection xacon = jotmCon.xacon;
                Object xacon = field_xacon.get(con);
                // xacon.thisAutoCommit = autoCommit;
                field_xacon_thisAutoCommit.set(xacon, autoCommit);
                if (autoCommit)
                    // jotmCon.setAutoCommit(false);
                    method_setAutoCommit.invoke(con, false);
                // tx.enlistResource(xacon.getXAResource());
                tx.enlistResource((XAResource) method_xacon_getXAResource.invoke(xacon, (Object[]) null));
            }
        }
    } catch (RollbackException ex1) {
        throw new JEPLException(ex1);
    } catch (IllegalStateException ex1) {
        throw new JEPLException(ex1);
    } catch (SystemException ex1) {
        throw new JEPLException(ex1);
    } catch (IllegalAccessException ex1) {
        throw new JEPLException(ex1);
    } catch (InvocationTargetException ex1) {
        throw new JEPLException(ex1);
    }
}
Example 67
Project: JOTMServiceProvider-master  File: JOTMServiceImpl.java View source code
/**
     * Starts the registry and binds a JOTM instance to it. Registers the
     * resource adapters declared by the neo data source manager to get ready
     * for possible recovery.
     */
@Override
public void init(XaDataSourceManager xaDsManager) {
    TransactionResourceManager trm = new TransactionResourceManager() {

        public void returnXAResource(String rmName, XAResource rmXares) {
            return;
        }
    };
    try {
        for (XaDataSource xaDs : xaDsManager.getAllRegisteredDataSources()) {
            System.out.println("Registering another xa resource named: " + xaDs.getName());
            Current.getTransactionRecovery().registerResourceManager(xaDs.getName(), xaDs.getXaConnection().getXaResource(), xaDs.getName(), trm);
        }
        Current.getTransactionRecovery().startResourceManagerRecovery();
    } catch (XAException e) {
        throw new Error("Error registering xa datasource", e);
    }
}
Example 68
Project: mariadb-connector-j-master  File: DistributedTransaction.java View source code
/**
     * 2 phase commit , with either commit or rollback at the end.
     *
     * @param doCommit must commit
     * @throws Exception exception
     */
void test2PhaseCommit(boolean doCommit) throws Exception {
    int connectionNumber = 1;
    Xid parentXid = newXid();
    Connection[] connections = new Connection[connectionNumber];
    XAConnection[] xaConnections = new XAConnection[connectionNumber];
    XAResource[] xaResources = new XAResource[connectionNumber];
    Xid[] xids = new Xid[connectionNumber];
    try {
        for (int i = 0; i < connectionNumber; i++) {
            xaConnections[i] = dataSource.getXAConnection();
            connections[i] = xaConnections[i].getConnection();
            xaResources[i] = xaConnections[i].getXAResource();
            xids[i] = newXid(parentXid);
        }
        startAllResources(connectionNumber, xaResources, xids);
        insertDatas(connectionNumber, connections);
        endAllResources(connectionNumber, xaResources, xids);
        prepareAllResources(connectionNumber, xaResources, xids);
        for (int i = 0; i < connectionNumber; i++) {
            if (doCommit) {
                xaResources[i].commit(xids[i], false);
            } else {
                xaResources[i].rollback(xids[i]);
            }
        }
        // check the completion
        try (ResultSet rs = sharedConnection.createStatement().executeQuery("SELECT * from xatable order by i")) {
            if (doCommit) {
                for (int i = 0; i < connectionNumber; i++) {
                    rs.next();
                    assertEquals(rs.getInt(1), i);
                }
            } else {
                assertFalse(rs.next());
            }
        }
    } finally {
        for (int i = 0; i < connectionNumber; i++) {
            try {
                if (xaConnections[i] != null) {
                    xaConnections[i].close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Example 69
Project: mulgara-master  File: DummyXAResource.java View source code
/**
   * Format bitmasks defined by {@link XAResource}.
   *
   * @param flags  a bitmask composed from the constants defined in {@link XAResource}
   * @return a formatted representation of the <var>flags</var>
   */
protected static final String formatFlags(int flags) {
    // Short-circuit evaluation if we've been explicitly passed no flags
    if (flags == XAResource.TMNOFLAGS) {
        return "TMNOFLAGS";
    }
    StringBuilder buffer = new StringBuilder();
    // Add any flags that are present
    for (Map.Entry<Integer, String> entry : flagMap.entrySet()) {
        int entryFlag = entry.getKey().intValue();
        // from the bitmask
        if ((entryFlag & flags) == entryFlag) {
            if (buffer.length() > 0) {
                buffer.append(",");
            }
            buffer.append(entry.getValue());
            flags &= ~entryFlag;
        }
    }
    // If there's some unknown flag we've missed, format it as hexadecimal
    if (flags != 0) {
        if (buffer.length() > 0) {
            buffer.append(",");
        }
        buffer.append("0x").append(Integer.toHexString(flags));
    }
    return buffer.toString();
}
Example 70
Project: mycontainer-master  File: MyTransaction.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    if (status != Status.STATUS_ACTIVE) {
        throw new IllegalStateException("tx is not active: " + status);
    }
    try {
        beforeCompletion();
        status = Status.STATUS_COMMITTING;
        for (XAResource xa : getXas()) {
            xa.commit(null, true);
        }
        status = Status.STATUS_COMMITTED;
    } catch (XAException e) {
        throw new KernelRuntimeException(e);
    }
    afterCompletion(status);
}
Example 71
Project: nuxeo-master  File: WorkManagerTXTest.java View source code
@Override
public void work() {
    runs++;
    if (--throwCount >= 0) {
        if (!throwDuringXAResourceEnd) {
            throw new ConcurrentUpdateException("run " + runs);
        } else {
            XAResource xaRes = new XAResource() {

                @Override
                public void commit(Xid xid, boolean onePhase) throws XAException {
                }

                @Override
                public void start(Xid xid, int flags) throws XAException {
                }

                @Override
                public void end(Xid xid, int flags) throws XAException {
                    // similar code to what we have in SessionImpl#end to deal with ConcurrentUpdateException
                    Exception e = new ConcurrentUpdateException("end run " + runs);
                    TransactionHelper.noteSuppressedException(e);
                    TransactionHelper.setTransactionRollbackOnly();
                }

                @Override
                public void forget(Xid xid) throws XAException {
                }

                @Override
                public int getTransactionTimeout() throws XAException {
                    return 0;
                }

                @Override
                public boolean isSameRM(XAResource xares) throws XAException {
                    return false;
                }

                @Override
                public int prepare(Xid xid) throws XAException {
                    return 0;
                }

                @Override
                public Xid[] recover(int flag) throws XAException {
                    return null;
                }

                @Override
                public void rollback(Xid xid) throws XAException {
                }

                @Override
                public boolean setTransactionTimeout(int seconds) throws XAException {
                    return true;
                }
            };
            Transaction transaction;
            try {
                transaction = TransactionHelper.lookupTransactionManager().getTransaction();
                transaction.enlistResource(xaRes);
            } catch (SystemExceptionNamingException | RollbackException |  e) {
                throw new RuntimeException(e);
            }
        }
    }
}
Example 72
Project: org.ops4j.pax.jdbc-master  File: DbcpXAPooledDataSourceFactory.java View source code
@Override
public DataSource create(DataSourceFactory dsf, Properties props) throws SQLException {
    try {
        final XADataSource ds = dsf.createXADataSource(getNonPoolProps(props));
        DataSourceXAConnectionFactory connFactory = new DataSourceXAConnectionFactory(tm, (XADataSource) ds);
        PoolableManagedConnectionFactory pcf = new PoolableManagedConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        TransactionRegistry transactionRegistry = connFactory.getTransactionRegistry();
        final ServiceRegistration<XAResourceRecovery> registration = bundleContext.registerService(XAResourceRecovery.class, new XAResourceRecovery() {

            @Override
            public XAResource[] getXAResources() {
                try {
                    return new XAResource[] { new Wrapper(ds.getXAConnection()) };
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }, null);
        ManagedDataSource<PoolableConnection> mds = new ManagedDataSource<PoolableConnection>(pool, transactionRegistry) {

            @Override
            public void close() throws Exception {
                registration.unregister();
                super.close();
            }
        };
        return mds;
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
Example 73
Project: quercus-master  File: TransactionSynchronizationRegistryImpl.java View source code
// TODO This seems like a strange signature for a transaction resource.
// Besides XAResource what other resource type could be used in Resin?
@Override
public void putResource(Object key, Object value) {
    if (!(value instanceof XAResource)) {
        throw new IllegalArgumentException(L.l("{0} is not an XA resource.", value));
    }
    TransactionImpl transaction = _transactionManager.getTransaction();
    if (transaction != null) {
        try {
            transaction.putResource(key, (XAResource) value);
        } catch (RollbackException e) {
            log.log(Level.WARNING, L.l("Error adding resoure to transaction: {0}", e.getMessage()), e);
        } catch (SystemException e) {
            log.log(Level.WARNING, L.l("Error adding resoure to transaction: {0}", e.getMessage()), e);
        }
    } else {
        throw new IllegalStateException(L.l("No active transaction."));
    }
}
Example 74
Project: seasar2-master  File: DefaultXAResourceTest.java View source code
/**
     * @throws Exception
     */
public void testStart() throws Exception {
    DefaultXAResource xaRes = new DefaultXAResource();
    Xid xid = new XidImpl();
    xaRes.start(xid, XAResource.TMNOFLAGS);
    assertEquals("1", xid, xaRes.getCurrentXid());
    assertEquals("2", DefaultXAResource.RS_ACTIVE, xaRes.getStatus());
    try {
        xaRes.start(xid, XAResource.TMNOFLAGS);
        fail("3");
    } catch (XAException ex) {
        System.out.println(ex);
    }
    DefaultXAResource xaRes2 = new DefaultXAResource();
    Xid xid2 = new XidImpl();
    xaRes2.start(xid2, XAResource.TMNOFLAGS);
    xaRes2.end(xid2, XAResource.TMSUSPEND);
    xaRes2.start(xid2, XAResource.TMRESUME);
    assertEquals("4", xid2, xaRes2.getCurrentXid());
    assertEquals("5", DefaultXAResource.RS_ACTIVE, xaRes2.getStatus());
    try {
        xaRes2.start(xid, XAResource.TMRESUME);
        fail("6");
    } catch (XAException ex) {
        System.out.println(ex);
    }
    DefaultXAResource xaRes3 = new DefaultXAResource();
    try {
        xaRes3.start(xid, XAResource.TMJOIN);
        fail("7");
    } catch (XAException ex) {
        System.out.println(ex);
    }
    DefaultXAResource xaRes4 = new DefaultXAResource();
    try {
        xaRes4.start(xid, -1);
        fail("8");
    } catch (XAException ex) {
        System.out.println(ex);
    }
}
Example 75
Project: spring-boot-master  File: DataSourceXAResourceRecoveryHelperTests.java View source code
@Before
public void before() throws SQLException {
    this.xaDataSource = mock(XADataSource.class);
    this.xaConnection = mock(XAConnection.class);
    this.xaResource = mock(XAResource.class);
    this.recoveryHelper = new DataSourceXAResourceRecoveryHelper(this.xaDataSource);
    given(this.xaDataSource.getXAConnection()).willReturn(this.xaConnection);
    given(this.xaConnection.getXAResource()).willReturn(this.xaResource);
}
Example 76
Project: spring-framework-2.5.x-master  File: GenericMessageEndpointFactory.java View source code
/**
	 * Wrap each concrete endpoint instance with an AOP proxy,
	 * exposing the message listener's interfaces as well as the
	 * endpoint SPI through an AOP introduction.
	 */
public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException {
    GenericMessageEndpoint endpoint = (GenericMessageEndpoint) super.createEndpoint(xaResource);
    ProxyFactory proxyFactory = new ProxyFactory(this.messageListener);
    DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(endpoint);
    introduction.suppressInterface(MethodInterceptor.class);
    proxyFactory.addAdvice(introduction);
    return (MessageEndpoint) proxyFactory.getProxy();
}
Example 77
Project: spring-framework-master  File: GenericMessageEndpointFactory.java View source code
/**
	 * Wrap each concrete endpoint instance with an AOP proxy,
	 * exposing the message listener's interfaces as well as the
	 * endpoint SPI through an AOP introduction.
	 */
@Override
public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException {
    GenericMessageEndpoint endpoint = (GenericMessageEndpoint) super.createEndpoint(xaResource);
    ProxyFactory proxyFactory = new ProxyFactory(this.messageListener);
    DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(endpoint);
    introduction.suppressInterface(MethodInterceptor.class);
    proxyFactory.addAdvice(introduction);
    return (MessageEndpoint) proxyFactory.getProxy();
}
Example 78
Project: stomple-master  File: XAwithJTAExample.java View source code
@Override
public boolean runExample() throws Exception {
    XAConnection connection = null;
    InitialContext initialContext = null;
    try {
        // Step 1. Create an initial context to perform the JNDI lookup.
        initialContext = getContext(0);
        // Step 2. Lookup on the queue
        Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
        // Step 3. Perform a lookup on the XA Connection Factory
        XAConnectionFactory cf = (XAConnectionFactory) initialContext.lookup("/XAConnectionFactory");
        // Step 4.Create a JMS XAConnection
        connection = cf.createXAConnection();
        // Step 5. Start the connection
        connection.start();
        // Step 6. Create a JMS XASession
        XASession xaSession = connection.createXASession();
        // Step 7. Create a normal session
        Session normalSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Step 8. Create a normal Message Producer
        MessageProducer normalProducer = normalSession.createProducer(queue);
        // Step 9. Get the JMS Session
        Session session = xaSession.getSession();
        // Step 10. Create a message consumer
        MessageConsumer xaConsumer = session.createConsumer(queue);
        // Step 11. Create two Text Messages
        TextMessage helloMessage = session.createTextMessage("hello");
        TextMessage worldMessage = session.createTextMessage("world");
        // Step 12. Get the Transaction Manager
        javax.transaction.TransactionManager txMgr = TransactionManager.transactionManager();
        // Step 13. Start a transaction
        txMgr.begin();
        // Step 14. Get the JMS XAResource
        XAResource xaRes = xaSession.getXAResource();
        // Step 15. enlist the resource in the Transaction work
        Transaction transaction = txMgr.getTransaction();
        transaction.enlistResource(new DummyXAResource());
        transaction.enlistResource(xaRes);
        // Step 16. Send two messages.
        normalProducer.send(helloMessage);
        normalProducer.send(worldMessage);
        // Step 17. Receive the message
        TextMessage rm1 = (TextMessage) xaConsumer.receive();
        System.out.println("Message received: " + rm1.getText());
        TextMessage rm2 = (TextMessage) xaConsumer.receive();
        System.out.println("Message received: " + rm2.getText());
        // Step 18. Roll back the transaction
        txMgr.rollback();
        // Step 19. Create another transaction
        txMgr.begin();
        transaction = txMgr.getTransaction();
        // Step 20. Enlist the resources to start the transaction work
        transaction.enlistResource(new DummyXAResource());
        transaction.enlistResource(xaRes);
        // Step 21. receive those messages again
        rm1 = (TextMessage) xaConsumer.receive();
        System.out.println("Message received again: " + rm1.getText());
        rm2 = (TextMessage) xaConsumer.receive();
        System.out.println("Message received again: " + rm2.getText());
        // Step 22. Commit!
        txMgr.commit();
        // Step 23. Check no more messages are received.
        TextMessage rm3 = (TextMessage) xaConsumer.receive(2000);
        if (rm3 == null) {
            System.out.println("No message received after commit.");
        } else {
            result = false;
        }
        return result;
    } finally {
        // Step 24. Be sure to close our JMS resources!
        if (initialContext != null) {
            initialContext.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}
Example 79
Project: threads-with-transaction-master  File: AtomikosDAO.java View source code
public Integer call() throws Exception {
    if (falhar) {
        throw new RuntimeException("Falhou inesperadamente!");
    }
    //enlist xa connection
    XAConnection xac = AtomikosDataSource.getDS().getXaDataSource().getXAConnection();
    synchronized (transaction) {
        transaction.enlistResource(xac.getXAResource());
    }
    //normal execution, update row with OK
    Connection c = xac.getConnection();
    Statement s = c.createStatement();
    s.executeUpdate("update teste set processado = 'ok' where id = " + id);
    s.close();
    c.close();
    //delist xa connection
    synchronized (transaction) {
        transaction.delistResource(xac.getXAResource(), XAResource.TMSUCCESS);
    }
    return id;
}
Example 80
Project: tomee-master  File: GetterConnectorTest.java View source code
@Override
public ManagedConnection createManagedConnection(final Subject subject, final ConnectionRequestInfo cxRequestInfo) throws ResourceException {
    return new ManagedConnection() {

        @Override
        public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
            connections.add(this);
            return this;
        }

        @Override
        public void destroy() throws ResourceException {
            connections.remove(this);
            destroyed.set(true);
        }

        @Override
        public void cleanup() throws ResourceException {
        // no-op
        }

        @Override
        public void associateConnection(Object connection) throws ResourceException {
        // no-op
        }

        @Override
        public void addConnectionEventListener(ConnectionEventListener listener) {
        // no-op
        }

        @Override
        public void removeConnectionEventListener(ConnectionEventListener listener) {
        // no-op
        }

        @Override
        public XAResource getXAResource() throws ResourceException {
            return null;
        }

        @Override
        public LocalTransaction getLocalTransaction() throws ResourceException {
            return new LocalTransaction() {

                @Override
                public void begin() throws ResourceException {
                }

                @Override
                public void commit() throws ResourceException {
                }

                @Override
                public void rollback() throws ResourceException {
                }
            };
        }

        @Override
        public ManagedConnectionMetaData getMetaData() throws ResourceException {
            return null;
        }

        @Override
        public void setLogWriter(PrintWriter out) throws ResourceException {
        // no-op
        }

        @Override
        public PrintWriter getLogWriter() throws ResourceException {
            return null;
        }
    };
}
Example 81
Project: tuscany-sca-2.x-master  File: TransactionManagerHelperTestCaseOFF.java View source code
public void testHelper() throws Exception {
    TransactionManagerWrapper activator = new TransactionManagerWrapper();
    activator.start();
    TransactionManager tm = activator.getTransactionManager();
    // GeronimoUserTransaction tx = new GeronimoUserTransaction(tm);
    TransactionManagerHelper helper = new TransactionManagerHelper(tm);
    // No TX yet
    assertNull(tm.getTransaction());
    Transaction t1 = helper.managedGlobalTransactionPreInvoke();
    // Should create T1
    assertNotNull(t1);
    // The current TX should be T1
    assertSame(t1, tm.getTransaction());
    XAResource res1 = new MockXAResource("Derby", "001");
    XAResource res2 = new MockXAResource("DB2", "002");
    tm.getTransaction().enlistResource(res1);
    tm.getTransaction().enlistResource(res2);
    Transaction suspended = helper.suspendsTransactionPreInvoke();
    suspended.delistResource(res1, XAResource.TMSUSPEND);
    suspended.delistResource(res2, XAResource.TMSUSPEND);
    // T1 is suspended
    assertSame(t1, suspended);
    // No more active TX
    assertNull(tm.getTransaction());
    Transaction t2 = helper.managedGlobalTransactionPreInvoke();
    assertNotNull(t2);
    // The current TX should be T2
    assertSame(t2, tm.getTransaction());
    XAResource res3 = new MockXAResource("Oracle", "003");
    tm.getTransaction().enlistResource(res3);
    tm.getTransaction().delistResource(res3, XAResource.TMSUCCESS);
    tm.rollback();
    // Skip post
    // helper.managedGlobalTransactionPostInvoke(t2);
    helper.suspendsTransactionPostInvoke(suspended);
    suspended.enlistResource(res1);
    suspended.enlistResource(res2);
    // T1 is now resumed
    assertSame(t1, tm.getTransaction());
    helper.managedGlobalTransactionPostInvoke(t1, false);
    assertNotNull(tm.getTransaction());
    assertEquals(6, t1.getStatus());
    activator.stop();
}
Example 82
Project: wildfly-master  File: TestXAResource.java View source code
@Override
public int prepare(Xid xid) throws XAException {
    LOG.debugf("prepare xid: [%s]", xid);
    switch(prepareOp) {
        case THROW_KNOWN_XA_EXCEPTION:
            throw new XAException(XAException.XAER_RMERR);
        case THROW_UNKNOWN_XA_EXCEPTION:
            throw RM_SPECIFIC_EXCEPTION;
        case NONE:
        default:
            return XAResource.XA_OK;
    }
}
Example 83
Project: geode-master  File: AbstractPoolCacheJUnitTest.java View source code
/**
   * 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);
    }
}
Example 84
Project: clinic-softacad-master  File: JtaAwareConnectionProviderImpl.java View source code
@Override
public void closeConnection(Connection conn) throws SQLException {
    if (conn == null) {
        return;
    }
    if (nonEnlistedConnections.contains(conn)) {
        nonEnlistedConnections.remove(conn);
        delegate.closeConnection(conn);
    } else {
    // do nothing.  part of the enlistment contract here is that the XAResource wrapper
    // takes that responsibility.
    }
}
Example 85
Project: easybeans-master  File: MDBCMTRequiredTransactionInterceptor.java View source code
/**
     * Execute transaction as specified with the REQUIRED attribute.
     * @param invocationContext
     *            context with useful attributes on the current invocation
     * @return result of the next invocation (to chain interceptors)
     * @throws Exception
     *             if interceptor fails
     * @see <a href="http://www.jcp.org/en/jsr/detail?id=220">EJB 3.0
     *      specification ?12.6.2.2</a>
     */
@Override
public Object intercept(final EasyBeansInvocationContext invocationContext) throws Exception {
    this.logger.debug("Calling Required TX interceptor");
    // Get current transaction
    Transaction transaction;
    try {
        transaction = getTransactionManager().getTransaction();
    } catch (SystemException se) {
        throw new EJBException("Cannot get the current transaction on transaction manager.", se);
    }
    this.logger.debug("Transaction found = {0}", transaction);
    /*
         * If the client invokes the enterprise bean's method while the client
         * is not associated with a transaction context, the container
         * automatically starts a new transaction before delegating a method
         * call to the enterprise bean business method.
         */
    boolean startedTransaction = false;
    if (transaction == null) {
        try {
            getTransactionManager().begin();
            startedTransaction = true;
        } catch (NotSupportedException nse) {
            throw new EJBException("Transaction Manager implementation does not support nested transactions.", nse);
        } catch (SystemException se) {
            throw new EJBException("Cannot call begin() on the transaction manager.", se);
        }
    }
    // Get XA Resource
    Object target = invocationContext.getTarget();
    EasyBeansMDB mdbInstance = null;
    XAResource xaResource = null;
    if (target instanceof EasyBeansMDB) {
        mdbInstance = (EasyBeansMDB) target;
        if (mdbInstance != null) {
            xaResource = mdbInstance.getXaResource();
        }
    }
    // Enlist XA Resource
    if (xaResource != null) {
        getTransactionManager().getTransaction().enlistResource(xaResource);
    }
    // else
    /*
         * If a client invokes the enterprise bean's method while the client is
         * associated with a transaction context, the container invokes the
         * enterprise bean's method in the client's transaction context.
         */
    boolean gotBusinessException = false;
    try {
        return invocationContext.proceed();
    } catch (Exception e) {
        gotBusinessException = true;
        if (!startedTransaction) {
            handleContextClientTransaction(invocationContext, e);
        } else {
            handleContextContainerTransaction(invocationContext, e);
        }
        return null;
    } finally {
        if (!gotBusinessException) {
            // invoking the method.
            if (startedTransaction) {
                // sanity check.
                Transaction transactionAfter = null;
                try {
                    transactionAfter = getTransactionManager().getTransaction();
                } catch (SystemException se) {
                    throw new EJBException("Cannot get the current transaction on transaction manager.", se);
                }
                if (transactionAfter == null) {
                    throw new RuntimeException("Transaction disappeared.");
                }
                /*
                     * The container attempts to commit the transaction when the
                     * business method has completed. The container performs the
                     * commit protocol before the method result is sent to the
                     * client.
                     */
                try {
                    switch(getTransactionManager().getStatus()) {
                        case STATUS_ACTIVE:
                            // Delist XA Resource
                            if (xaResource != null) {
                                transactionAfter.delistResource(xaResource, XAResource.TMSUCCESS);
                            }
                            getTransactionManager().commit();
                            break;
                        case STATUS_MARKED_ROLLBACK:
                            // Delist XA Resource
                            if (xaResource != null) {
                                transactionAfter.delistResource(xaResource, XAResource.TMFAIL);
                            }
                            getTransactionManager().rollback();
                            break;
                        default:
                            throw new RuntimeException("Unexpected transaction status" + getTransactionManager().getStatus());
                    }
                } catch (RollbackException e) {
                    throw new TransactionRolledbackLocalException("Could not commit transaction", e);
                } catch (Exception e) {
                    throw new EJBException("Container exception", e);
                }
            }
        }
    }
}
Example 86
Project: featurehouse_fstcomp_examples-master  File: XAEnvironment.java View source code
/** 
 * Javadoc for this public method is generated via
 * the doc templates in the doc_src directory.
 */
public void end(Xid xid, int flags) throws XAException {
    if (DEBUG) {
        System.out.println("*** end called " + xid + "/" + flags);
    }
    boolean tmFail = (flags & XAResource.TMFAIL) != 0;
    boolean tmSuccess = (flags & XAResource.TMSUCCESS) != 0;
    boolean tmSuspend = (flags & XAResource.TMSUSPEND) != 0;
    if ((tmFail && tmSuccess) || ((tmFail || tmSuccess) && tmSuspend)) {
        throw new XAException(XAException.XAER_INVAL);
    }
    try {
        if (DEBUG) {
            System.out.println("Transaction for " + Thread.currentThread() + " is " + environmentImpl.getTxnManager().getTxnForThread());
        }
        Transaction txn = environmentImpl.getTxnManager().unsetTxnForThread();
        if (txn == null) {
            txn = getXATransaction(xid);
            boolean isSuspended = (txn != null) && txn.getTxn().isSuspended();
            if (!isSuspended) {
                throw new XAException(XAException.XAER_NOTA);
            }
        }
        if (tmFail) {
            txn.getTxn().setOnlyAbortable();
        }
        if (tmSuspend) {
            txn.getTxn().setSuspended(true);
        }
    } catch (DatabaseException DE) {
        throwNewXAException(DE);
    }
}
Example 87
Project: ha-jdbc-master  File: XAResourceInvocationHandler.java View source code
/**
	 * @see net.sf.hajdbc.sql.AbstractInvocationHandler#getInvocationStrategy(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
	 */
@Override
protected InvocationStrategy getInvocationStrategy(XAResource resource, Method method, Object... parameters) throws XAException {
    if (driverReadMethodSet.contains(method)) {
        return InvocationStrategies.INVOKE_ON_ANY;
    }
    if (databaseWriteMethodSet.contains(method)) {
        return InvocationStrategies.INVOKE_ON_ALL;
    }
    boolean start = method.equals(startMethod);
    boolean end = endTransactionMethodSet.contains(method);
    if (start || end || intraTransactionMethodSet.contains(method)) {
        final InvocationStrategy strategy = end ? InvocationStrategies.END_TRANSACTION_INVOKE_ON_ALL : InvocationStrategies.TRANSACTION_INVOKE_ON_ALL;
        Xid xid = (Xid) parameters[0];
        DatabaseCluster<XADataSource, XADataSourceDatabase> cluster = this.getProxyFactory().getDatabaseCluster();
        if (start) {
            final Lock lock = cluster.getLockManager().readLock(null);
            // Lock may already exist if we're resuming a suspended transaction
            if (lockMap.putIfAbsent(xid, lock) == null) {
                return new InvocationStrategy() {

                    @Override
                    public <Z, D extends Database<Z>, T, R, E extends Exception> SortedMap<D, R> invoke(ProxyFactory<Z, D, T, E> proxy, Invoker<Z, D, T, R, E> invoker) throws E {
                        lock.lock();
                        try {
                            return strategy.invoke(proxy, invoker);
                        } catch (Exception e) {
                            lock.unlock();
                            throw proxy.getExceptionFactory().createException(e);
                        }
                    }
                };
            }
        }
        Durability.Phase phase = phaseRegistry.get(method);
        if (phase != null) {
            final InvocationStrategy durabilityStrategy = cluster.getDurability().getInvocationStrategy(strategy, phase, xid);
            if (endTransactionMethodSet.contains(method)) {
                final Lock lock = lockMap.remove(xid);
                return new InvocationStrategy() {

                    @Override
                    public <Z, D extends Database<Z>, T, R, E extends Exception> SortedMap<D, R> invoke(ProxyFactory<Z, D, T, E> proxy, Invoker<Z, D, T, R, E> invoker) throws E {
                        try {
                            return durabilityStrategy.invoke(proxy, invoker);
                        } finally {
                            if (lock != null) {
                                lock.unlock();
                            }
                        }
                    }
                };
            }
            return durabilityStrategy;
        }
        return strategy;
    }
    return super.getInvocationStrategy(resource, method, parameters);
}
Example 88
Project: hibernate-core-ogm-master  File: XaTransactionImpl.java View source code
private boolean runXaResourcePrepare() throws SystemException {
    Collection<XAResource> resources = getEnlistedResources();
    for (XAResource res : resources) {
        try {
            res.prepare(xid);
        } catch (XAException e) {
            log.trace("The resource wants to rollback!", e);
            return false;
        } catch (Throwable th) {
            log.error("Unexpected error from resource manager!", th);
            throw new SystemException(th.getMessage());
        }
    }
    return true;
}
Example 89
Project: hibernate-orm-master  File: JtaAwareConnectionProviderImpl.java View source code
@Override
public void closeConnection(Connection conn) throws SQLException {
    if (conn == null) {
        return;
    }
    if (nonEnlistedConnections.contains(conn)) {
        nonEnlistedConnections.remove(conn);
        delegate.closeConnection(conn);
    } else {
    // do nothing.  part of the enlistment contract here is that the XAResource wrapper
    // takes that responsibility.
    }
}
Example 90
Project: ignite-master  File: WebSphereTmFactory.java View source code
@SuppressWarnings("SimplifiableIfStatement")
@Override
public boolean enlistResource(final XAResource xaRes) throws RollbackException, IllegalStateException, SystemException {
    if (xaRes == null)
        return false;
    //            final XAResource res = new IgniteOnePhaseXAResource(xaRes);
    Object ibmProxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { onePhaseXAResourceCls }, new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method mtd, Object[] args) throws Throwable {
            return mtd.invoke(xaRes, args);
        }
    });
    return tx.enlistResource((XAResource) ibmProxy);
}
Example 91
Project: metamorphosis-example-master  File: XATransactionTemplate.java View source code
private Transaction beginTx(final XAMessageProducer producer, final XAConnection conn) throws SystemException, MetaClientException, SQLException, RollbackException, NotSupportedException {
    this.transactionManager.begin();
    final Transaction tx = this.transactionManager.getTransaction();
    if (tx == null) {
        throw new IllegalStateException("Could not get transaction from tm");
    }
    final XAResource metaXares = producer.getXAResource();
    final XAResource jdbcXares = conn.getXAResource();
    tx.enlistResource(metaXares);
    tx.enlistResource(jdbcXares);
    return tx;
}
Example 92
Project: Phynixx-master  File: XATransactionalBranch.java View source code
int prepare() throws XAException {
    // must find connection for this transaction
    if (// must
    !this.isProgressStateIn(XAResourceProgressState.ACTIVE)) {
        // have
        // had
        // start()
        // called
        LOG.error("XAResource " + this + " must have start() called ");
        throw new XAException(XAException.XAER_PROTO);
    }
    if (this.progressState == XAResourceProgressState.PREPARED) {
        if (this.isReadOnly()) {
            return (XAResource.XA_RDONLY);
        } else {
            return XAResource.XA_OK;
        }
    }
    // check if resource is READONLY -> no prepare is required
    if (this.isReadOnly()) {
        this.setProgressState(XAResourceProgressState.PREPARED);
        return (XAResource.XA_RDONLY);
    }
    if (this.progressState == XAResourceProgressState.PREPARING) {
        throw new IllegalStateException("XAResource already preparing");
    }
    if (!checkTXRequirements()) {
        throw new SampleTransactionalException("State not transactional " + this);
    }
    if (this.hasHeuristicOutcome()) {
        throw new XAException(this.heuristicState);
    }
    this.checkRollback();
    this.setProgressState(XAResourceProgressState.PREPARING);
    try {
        this.getManagedConnection().prepare();
    } catch (Exception e) {
        throwXAException(XAException.XAER_PROTO, e);
    }
    this.setProgressState(XAResourceProgressState.PREPARED);
    // anything to commit?
    if (this.isReadOnly()) {
        return (XAResource.XA_RDONLY);
    } else {
        return XAResource.XA_OK;
    }
}
Example 93
Project: agile4techos-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 94
Project: Airscribe-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 95
Project: aramis-build-toolkit-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 96
Project: Banc-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 97
Project: Bescrewed-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 98
Project: castor-master  File: XAResourceImpl.java View source code
public synchronized void start(final Xid xid, final int flags) throws XAException {
    // General checks.
    if (xid == null) {
        throw new XAException(XAException.XAER_INVAL);
    }
    switch(flags) {
        case TMNOFLAGS:
            TransactionContext tx1;
            // for a given Xid
            synchronized (_engine.getXATransactions()) {
                tx1 = _engine.getXATransactions().get(xid);
                if (tx1 == null) {
                    tx1 = _xaSource.createTransactionContext(xid);
                    _engine.getXATransactions().put(xid, tx1);
                }
            }
            // Associate XAResource with transaction
            _xaSource.setTransactionContext(tx1);
            break;
        case TMJOIN:
        case TMRESUME:
            TransactionContext tx2 = _engine.getXATransactions().get(xid);
            if ((tx2 == null) || !tx2.isOpen()) {
                throw new XAException(XAException.XAER_NOTA);
            }
            // Associate XAResource with transaction
            _xaSource.setTransactionContext(tx2);
            break;
        default:
            // No other flags supported in start().
            throw new XAException(XAException.XAER_INVAL);
    }
}
Example 99
Project: cloudera-cli-scripts-master  File: XATest.java View source code
/**
     * Tests that simple distributed transaction processing works as expected.
     * 
     * @throws Exception
     *             if the test fails.
     */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 100
Project: GestionBibliotheque-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 101
Project: gestion_autoecole_xelais-master  File: XATest.java View source code
/**
	 * Tests that simple distributed transaction processing works as expected.
	 * 
	 * @throws Exception
	 *             if the test fails.
	 */
public void testCoordination() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");
    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();
        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));
        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));
        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");
        //
        // Now test rollback
        //
        xid1 = createXid();
        xid2 = createXid(xid1);
        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);
        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);
        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);
        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");
        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }
        if (conn2 != null) {
            conn2.close();
        }
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}