javax.transaction.xa.XAException Java Examples

The following examples show how to use javax.transaction.xa.XAException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RMXAConnectionResource.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSameRM(XAResource otherResource) throws XAException {
    log.entering(this.getClass().getName(), "isSameRM");
    boolean isSame = false;
    try {
        // Drive the method calls to each of the proxied XAResource instances,
        // and return the logically ANDed value received from those method calls.
        if (getProxiedXAResources() != null) {
            isSame = true;
            for (XAResource resource : getProxiedXAResources()) {
                isSame = isSame && resource.isSameRM(otherResource);
            }
        }
        return isSame;
    } finally {
        log.exiting(this.getClass().getName(), "isSameRM", new Object[] {
                "isSame", Boolean.toString(isSame)
        });
    }
}
 
Example #2
Source File: MysqlXAConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void start(Xid xid, int flags) throws XAException {
    StringBuilder commandBuf = new StringBuilder(MAX_COMMAND_LENGTH);
    commandBuf.append("XA START ");
    appendXid(commandBuf, xid);

    switch (flags) {
        case TMJOIN:
            commandBuf.append(" JOIN");
            break;
        case TMRESUME:
            commandBuf.append(" RESUME");
            break;
        case TMNOFLAGS:
            // no-op
            break;
        default:
            throw new XAException(XAException.XAER_INVAL);
    }

    dispatchCommand(commandBuf.toString());

    this.underlyingConnection.setInGlobalTx(true);
}
 
Example #3
Source File: TransactionInterceptorImpl.java    From ByteJTA with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void afterReceiveRequest(TransactionRequest request) throws IllegalStateException {
	TransactionContext srcTransactionContext = request.getTransactionContext();
	if (srcTransactionContext == null) {
		return;
	}

	TransactionParticipant coordinator = this.beanFactory.getNativeParticipant();

	TransactionContext transactionContext = srcTransactionContext.clone();
	transactionContext.setPropagatedBy(srcTransactionContext.getPropagatedBy());
	try {
		coordinator.start(transactionContext, XAResource.TMNOFLAGS);
	} catch (XAException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #4
Source File: ActiveMQSessionContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void xaEnd(Xid xid, int flags) throws XAException, ActiveMQException {
   Packet packet;
   if (flags == XAResource.TMSUSPEND) {
      packet = new PacketImpl(PacketImpl.SESS_XA_SUSPEND);
   } else if (flags == XAResource.TMSUCCESS) {
      packet = new SessionXAEndMessage(xid, false);
   } else if (flags == XAResource.TMFAIL) {
      packet = new SessionXAEndMessage(xid, true);
   } else {
      throw new XAException(XAException.XAER_INVAL);
   }

   SessionXAResponseMessage response = (SessionXAResponseMessage) sessionChannel.sendBlocking(packet, PacketImpl.SESS_XA_RESP);

   if (response.isError()) {
      throw new XAException(response.getResponseCode());
   }
}
 
Example #5
Source File: EhcacheXAResourceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeoutEndFail() throws Exception {
  EhcacheXAResource<Long, String> xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory);

  when(xaTransactionContextFactory.createTransactionContext(eq(new TransactionId(new TestXid(0, 0))), refEq(underlyingStore), refEq(journal), anyInt())).thenReturn(xaTransactionContext);

  xaResource.start(new TestXid(0, 0), XAResource.TMNOFLAGS);

  when(xaTransactionContext.hasTimedOut()).thenReturn(true);
  when(xaTransactionContextFactory.get(eq(new TransactionId(new TestXid(0, 0))))).thenReturn(xaTransactionContext);

  try {
    xaResource.end(new TestXid(0, 0), XAResource.TMFAIL);
    fail("expected XAException");
  } catch (XAException xae) {
    assertThat(xae.errorCode, is(XAException.XA_RBTIMEOUT));
  }

  verify(xaTransactionContextFactory, times(1)).destroy(eq(new TransactionId(new TestXid(0, 0))));
}
 
Example #6
Source File: EhcacheXAResourceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndWithoutStartFails() throws Exception {
  EhcacheXAResource<Long, String> xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory);

  try {
    xaResource.end(new TestXid(0, 0), XAResource.TMSUCCESS);
    fail("expected XAException");
  } catch (XAException xae) {
    assertThat(xae.errorCode, is(XAException.XAER_PROTO));
  }
}
 
Example #7
Source File: EhcacheXAResourceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCannotCommit1PcUnknownXid() throws Exception {
  EhcacheXAResource<Long, String> xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory);

  try {
    xaResource.commit(new TestXid(0, 0), true);
    fail("expected XAException");
  } catch (XAException xae) {
    assertThat(xae.errorCode, is(XAException.XAER_NOTA));
  }
}
 
Example #8
Source File: ActiveMQRAXAResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Recover
 *
 * @param flag One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS
 * @return Zero or more XIDs
 * @throws XAException An error has occurred
 */
@Override
public Xid[] recover(final int flag) throws XAException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("recover(" + flag + ")");
   }

   return xaResource.recover(flag);
}
 
Example #9
Source File: ActiveMQRAXAResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * End
 *
 * @param xid   A global transaction identifier
 * @param flags One of TMSUCCESS, TMFAIL, or TMSUSPEND.
 * @throws XAException An error has occurred
 */
@Override
public void end(final Xid xid, final int flags) throws XAException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("end(" + xid + ", " + flags + ")");
   }

   managedConnection.lock();
   try {
      xaResource.end(xid, flags);
   } finally {
      managedConnection.setInManagedTx(false);
      managedConnection.unlock();
   }
}
 
Example #10
Source File: MithraRemoteTransactionProxy.java    From reladomo with Apache License 2.0 5 votes vote down vote up
private void commitAllXaResources(boolean onePhase)
{
    try
    {
        for (Iterator iterator = this.enlistedResources.iterator(); iterator.hasNext();)
        {
            XAResource xaResource = (XAResource) iterator.next();
            xaResource.commit(this.xid, onePhase);
        }
    }
    catch (XAException e)
    {
        throw new MithraTransactionException("Could not delist resources", e);
    }
}
 
Example #11
Source File: OutgoingAsyncTopicTest.java    From reladomo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendSetsProperties() throws NamingException, JMSException, RollbackException, RestartTopicException, XAException
{
    mithraTransaction = topicResourcesWithTransactionXid.startTransaction();

    UnifiedMap<String, Object> msgProperties = UnifiedMap.<String, Object>newMap();
    msgProperties.put("Hello", "World");
    Future<Void> voidFuture = outTopic.asyncSendMessages(FastList.newListWith("msg1".getBytes()), msgProperties);
    topicResourcesWithTransactionXid.commit(mithraTransaction, FastList.<Future>newListWith(voidFuture), FastList.<JmsTopic>newList());

    Message messageRecvd = incomingTopic.receive(100);
    assertEquals("msg1", JmsUtil.getMessageBodyAsString(messageRecvd));
    assertEquals("World", messageRecvd.getStringProperty("Hello"));
}
 
Example #12
Source File: JtaXAResource.java    From hbase-secondary-index with GNU General Public License v3.0 5 votes vote down vote up
public void forget(final Xid xid) throws XAException {
    LOG.trace("forget [" + xid.toString() + "] ");
    threadLocalTransactionState.remove();
    TransactionState state = xidToTransactionState.remove(xid);
    if (state != null) {
        try {
            transactionManager.abort(state);
        } catch (IOException e) {
            XAException xae = new XAException(XAException.XAER_RMERR);
            xae.initCause(e);
            throw xae;
        }
    }
}
 
Example #13
Source File: TestLocalXaResource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommit() throws SQLException, XAException {
    final Xid xid = new TestXid();
    ((TestConnection) conn).closed = false;
    conn.setReadOnly(false);
    resource.start(xid, XAResource.TMNOFLAGS);
    resource.commit(xid, false);
    assertTrue(((TestConnection) conn).committed);
}
 
Example #14
Source File: EmbedXAResource.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if currently associated connection is active
 * throws exception if not
 */
private void checkXAActive() throws XAException {    
    try {
        con.checkActive();
    } catch (SQLException sqle) {
        throw wrapInXAException(sqle);
    }
}
 
Example #15
Source File: RMXAConnectionResource.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Override
public int prepare(Xid xid) throws XAException {
    log.entering(this.getClass().getName(), "prepare");
    // log.fine(FHIRUtilities.getCurrentStacktrace());
    int vote = XAResource.XA_OK;
    try {
        // Retrieve the XAResource(s) associated with this Xid.
        List<XAResource> resources = getXAResourcesForXid(xid);
        if (resources == null) {
            throw new XAException("prepare: Unknown Xid");
        }

        String xidString = displayXid(xid);
        log.info("Initiating recovery 'prepare' processing for Xid:\n" + xidString);
        
        // Make sure our artificial failures are not triggered during recovery processing :)
        setBypassFailures(Boolean.TRUE);

        // Drive the method calls to each of the XAResource instances.
        for (XAResource resource : resources) {
            int resourceVote = resource.prepare(xid);
            if (resourceVote > vote) {
                vote = resourceVote;
            }
        }
        
        log.info("Finished recovery 'prepare' processing for Xid:\n" + xidString);
        return vote;
    } finally {
        setBypassFailures(Boolean.FALSE);
        log.exiting(this.getClass().getName(), "prepare", new Object[] {
                "vote", vote
        });
    }
}
 
Example #16
Source File: RMXAConnectionResource.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Xid xid, int flag) throws XAException {
    log.entering(this.getClass().getName(), "start");
    // log.fine(FHIRUtilities.getCurrentStacktrace());
    try {
        // Retrieve the XAResource(s) associated with this Xid.
        List<XAResource> resources = getXAResourcesForXid(xid);
        if (resources == null) {
            throw new XAException("start: Unknown Xid");
        }

        String xidString = displayXid(xid);
        log.info("Initiating recovery 'start' processing for Xid:\n" + xidString);
        
        // Make sure our artificial failures are not triggered during recovery processing :)
        setBypassFailures(Boolean.TRUE);

        // Drive the method calls to each of the XAResource instances.
        for (XAResource resource : resources) {
            resource.start(xid, flag);
        }
        
        log.info("Finished recovery 'start' processing for Xid:\n" + xidString);
    } finally {
        setBypassFailures(Boolean.FALSE);
        log.exiting(this.getClass().getName(), "start");
    }
}
 
Example #17
Source File: FBManagedConnection.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Associates a JDBC connection with a global transaction. We assume that
 * end will be called followed by prepare, commit, or rollback. If start is
 * called after end but before commit or rollback, there is no way to
 * distinguish work done by different transactions on the same connection).
 * If start is called more than once before end, either it's a duplicate
 * transaction ID or illegal transaction ID (since you can't have two
 * transactions associated with one DB connection).
 *
 * @param id
 *         A global transaction identifier to be associated with the resource
 * @param flags
 *         One of TMNOFLAGS, TMJOIN, or TMRESUME
 * @throws XAException
 *         Occurs when the state was not correct (start called twice), the transaction ID is wrong, or the instance
 *         has already been closed.
 */
private void start(Xid id, int flags) throws XAException {
    if (flags != XAResource.TMNOFLAGS && flags != XAResource.TMJOIN && flags != XAResource.TMRESUME) {
        throw new FBXAException("flag not allowed in this context: " + flags + ", valid flags are TMNOFLAGS, TMJOIN, TMRESUME", XAException.XAER_PROTO);
    }
    if (flags == XAResource.TMJOIN) {
        throw new FBXAException("Joining two transactions is not supported", XAException.XAER_RMFAIL);
    }

    try {
        // reset the transaction parameters for the managed scenario
        setTransactionIsolation(mcf.getDefaultTransactionIsolation());

        internalStart(id, flags);

        mcf.notifyStart(this, id);

        inDistributedTransaction = true;

        // This will reset the managed environment of the associated connections and set the transaction coordinator to managed
        // TODO This is a bit of a hack; need to find a better way
        setManagedEnvironment(isManagedEnvironment());

    } catch (SQLException e) {
        throw new FBXAException(XAException.XAER_RMERR, e);
    }
}
 
Example #18
Source File: ActiveMQMessageHandlerXATest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void afterDelivery() throws ResourceException {
   try {
      xaResource.end(xid, XAResource.TMSUCCESS);
   } catch (XAException e) {
      throw new ResourceException(e.getMessage(), e);
   }

   super.afterDelivery();
}
 
Example #19
Source File: AbstractLuceneIndexerAndSearcherFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Xid[] recover(int arg0) throws XAException
{
    // We can not rely on being able to recover at the moment
    // Avoiding for performance benefits at the moment
    // Assume roll back and no recovery - in the worst case we get an unused
    // delta
    // This should be there to avoid recovery of partial commits.
    // It is difficult to see how we can mandate the same conditions.
    return new Xid[0];
}
 
Example #20
Source File: CloudSpannerXAConnectionTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testEnd() throws SQLException, XAException {
  CloudSpannerXAConnection subject = createSubject();
  Xid xid = createXid();
  subject.start(xid, XAResource.TMNOFLAGS);
  subject.end(xid, XAResource.TMSUCCESS);
}
 
Example #21
Source File: LocalXAResourceImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void rollback(Xid xid) throws XAException
{
   try
   {
      cl.getManagedConnection().getLocalTransaction().rollback();
   }
   catch (ResourceException re)
   {
      connectionManager.returnManagedConnection(cl, true);
      throw new LocalXAException("rollback", XAException.XAER_RMERR, re);
   }
}
 
Example #22
Source File: XATransactionState.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This function is called from the timer task when the transaction
 * times out.
 *
 * @see CancelXATransactionTask
 */
synchronized void cancel(String messageId) throws XAException {
    // Check performTimeoutRollback just to be sure that
    // the cancellation task was not started
    // just before the xa_commit/rollback
    // obtained this object's monitor.
    if (performTimeoutRollback) {

        // Log the message about the transaction cancelled
        if (messageId != null)
            Monitor.logTextMessage(messageId, xid.toString());

        // Check whether the transaction is associated
        // with any EmbedXAResource instance.
        if (associationState == XATransactionState.T1_ASSOCIATED) {
            conn.cancelRunningStatement();
            EmbedXAResource assocRes = associatedResource;
            end(assocRes, XAResource.TMFAIL, true);
        }

        // Rollback the global transaction
        try {
            conn.xa_rollback();
        } catch (SQLException sqle) {
            XAException ex = new XAException(XAException.XAER_RMERR);
            ex.initCause(sqle);
            throw ex;
        }

        // Do the cleanup on the resource
        creatingResource.returnConnectionToResource(this, xid);
    }
}
 
Example #23
Source File: XATransactionState.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void cleanupOnError(Throwable t) {

		if (t instanceof StandardException) {

			StandardException se = (StandardException) t;
            
            if (se.getSeverity() >= ExceptionSeverity.SESSION_SEVERITY) {
                popMe();
                return;
            }

			if (se.getSeverity() == ExceptionSeverity.TRANSACTION_SEVERITY) {

				synchronized (this) {
					// disable use of the connection until it is cleaned up.
					conn.setApplicationConnection(null);
					notifyAll();
					associationState = TRO_FAIL;
					if (SQLState.DEADLOCK.equals(se.getMessageId()))
						rollbackOnlyCode = XAException.XA_RBDEADLOCK;
					else if (SQLState.LOCK_TIMEOUT.equals(se.getMessageId()))
						rollbackOnlyCode = XAException.XA_RBTIMEOUT;					
					else
						rollbackOnlyCode = XAException.XA_RBOTHER;
				}
			}
		}
	}
 
Example #24
Source File: ActiveMQXAResourceWrapper.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void commit(final Xid xid, final boolean onePhase) throws XAException {
   XAResource xaResource = getDelegate(true);
   if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) {
      ActiveMQXARecoveryLogger.LOGGER.debug("Commit " + xaResource + " xid " + " onePhase=" + onePhase);
   }
   try {
      xaResource.commit(xid, onePhase);
   } catch (XAException e) {
      throw check(e);
   }
}
 
Example #25
Source File: XAXactId.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
   * Construct an Xid using an external Xid.
   * <p>
   * @exception XAException invalid external xid
   */
  public XAXactId(Xid xid) throws XAException
  {
if (xid == null)
	throw new XAException(XAException.XAER_NOTA);
	
      copy_init_xid(
			  xid.getFormatId(),
			  xid.getGlobalTransactionId(),
			  xid.getBranchQualifier());
  }
 
Example #26
Source File: XATransactionState.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void cleanupOnError(Throwable t) {

		if (t instanceof StandardException) {

			StandardException se = (StandardException) t;
            
            if (se.getSeverity() >= ExceptionSeverity.SESSION_SEVERITY) {
                popMe();
                return;
            }

			if (se.getSeverity() == ExceptionSeverity.TRANSACTION_SEVERITY) {

				synchronized (this) {
					// disable use of the connection until it is cleaned up.
					conn.setApplicationConnection(null);
					notifyAll();
					associationState = TRO_FAIL;
					if (SQLState.DEADLOCK.equals(se.getMessageId()))
						rollbackOnlyCode = XAException.XA_RBDEADLOCK;
					else if (SQLState.LOCK_TIMEOUT.equals(se.getMessageId()))
						rollbackOnlyCode = XAException.XA_RBTIMEOUT;					
					else
						rollbackOnlyCode = XAException.XA_RBOTHER;
				}
			}
		}
	}
 
Example #27
Source File: XATestUtil.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Dump an unexpected XAException.
 * @param tag Useful info to print
 * @param xae The exception
 */
public static void dumpXAException(String tag, XAException xae) {

    System.out.println(tag + " : XAException - " + xae.getMessage()
            + " errorCode " + errorCode(xae));
    xae.printStackTrace(System.out);
}
 
Example #28
Source File: JDBCXAResource.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * Stub. See implementation comment in the method for why this is not
 * implemented yet.
 *
 * @return false.
 * @param xares XAResource
 * @throws XAException
 */
public boolean isSameRM(XAResource xares) throws XAException {

    if (!(xares instanceof JDBCXAResource)) {
        return false;
    }

    return xaDataSource == ((JDBCXAResource) xares).getXADataSource();
}
 
Example #29
Source File: MysqlXAConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public int prepare(Xid xid) throws XAException {
    StringBuilder commandBuf = new StringBuilder(MAX_COMMAND_LENGTH);
    commandBuf.append("XA PREPARE ");
    appendXid(commandBuf, xid);

    dispatchCommand(commandBuf.toString());

    return XA_OK; // TODO: Check for read-only
}
 
Example #30
Source File: OutgoingAsyncTopicTest.java    From reladomo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloneSendPreservesNullProperties() throws NamingException, JMSException, RollbackException, RestartTopicException, XAException
{
    mithraTransaction = topicResourcesWithTransactionXid.startTransaction();

    InMemoryBytesMessage messageToSend = new InMemoryBytesMessage();
    messageToSend.writeBytes("msg1".getBytes());

    Future<Void> voidFuture = outTopic.sendSyncMessageClones(FastList.<Message>newListWith(messageToSend));
    topicResourcesWithTransactionXid.commit(mithraTransaction, FastList.<Future>newListWith(voidFuture), FastList.<JmsTopic>newList());

    Message messageRecvd = incomingTopic.receive(100);
    assertNull(messageRecvd.getStringProperty("Hello"));
}