javax.transaction.xa.Xid Java Examples

The following examples show how to use javax.transaction.xa.Xid. 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: GenericXaResource.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * @see javax.transaction.xa.XAResource#start(javax.transaction.xa.Xid xid, int flag)
 */
public void start(Xid xid, int flag) throws XAException {
    if (this.active) {
        if (this.xid != null && this.xid.equals(xid)) {
            throw new XAException(XAException.XAER_DUPID);
        }
        throw new XAException(XAException.XAER_PROTO);
    }
    if (this.xid != null && !this.xid.equals(xid)) {
        throw new XAException(XAException.XAER_NOTA);
    }

    this.setName("GenericXaResource-Thread");
    this.setDaemon(true);
    this.active = true;
    this.xid = xid;
    this.start();
}
 
Example #2
Source File: CompensableCleanupWork.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void forget(Xid xid, String resourceId) throws RuntimeException {
	try {
		String application = CommonUtils.getApplication(this.endpoint);
		String databaseName = application.replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_REMOVEDRESES);

		byte[] global = xid.getGlobalTransactionId();
		byte[] branch = xid.getBranchQualifier();

		Document document = new Document();
		document.append(CONSTANTS_FD_GLOBAL, ByteUtils.byteArrayToString(global));
		document.append(CONSTANTS_FD_BRANCH, ByteUtils.byteArrayToString(branch));
		document.append("resource_id", resourceId);
		document.append("created", this.endpoint);

		collection.insertOne(document);
	} catch (RuntimeException error) {
		logger.error("Error occurred while forgetting resource({}).", resourceId, error);
	}
}
 
Example #3
Source File: XAConnectionPoolingDataSource.java    From reladomo with Apache License 2.0 6 votes vote down vote up
@Override
public void commit(Xid xid, boolean b) throws XAException
{
    if(committed)
    {
        throw new XAException("Transaction is already committed");
    }
    try
    {
        if(connectionsInUse.size() != 0)
        {
            throw new XAException("Detected open jdbc connections. Change code to close all connection borrowed from the connection manager");
        }
        commitConnections(availableConnections);
        committed = true;
    }
    catch (SQLException e)
    {
        logger.error("Commit failed", e);
        rollbackConnections(availableConnections); // if commit fails, we must ensure we've already rolledback
        XAException xaException = new XAException("Commit Failed - "+e.getMessage());
        xaException.initCause(e);
        throw xaException;
    }
}
 
Example #4
Source File: ActiveMQServerControlImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public String[] listHeuristicRolledBackTransactions() {
   if (AuditLogger.isEnabled()) {
      AuditLogger.listHeuristicRolledBackTransactions(this.server);
   }
   checkStarted();

   clearIO();
   try {
      List<Xid> xids = resourceManager.getHeuristicRolledbackTransactions();
      String[] s = new String[xids.size()];
      int i = 0;
      for (Xid xid : xids) {
         s[i++] = XidImpl.toBase64String(xid);
      }
      return s;
   } finally {
      blockOnIO();
   }
}
 
Example #5
Source File: NetXAConnectionRequest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeXaRollback(NetConnection conn, Xid xid) throws SqlException {
    int xaFlags = XAResource.TMNOFLAGS;

    // create DSS command with no reply.
    createCommand();

    // save the length bytes for later update
    markLengthBytes(CodePoint.SYNCCTL);

    // SYNCTYPE
    writeSYNCType(CodePoint.SYNCTYPE, CodePoint.SYNCTYPE_ROLLBACK);

    if (xid.getFormatId() != -1) {
        writeXID(CodePoint.XID, xid);
    } else
    // write the null XID for local transaction on XA connection
    {
        writeNullXID(CodePoint.XID);
    }

    writeXAFlags(CodePoint.XAFLAGS, xaFlags);
    updateLengthBytes();
}
 
Example #6
Source File: CacheJtaResource.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void end(Xid xid, int flags) throws XAException {
    assert this.xid.equals(xid);

    if (log.isDebugEnabled())
        log.debug("XA resource end(...) [xid=" + xid + ", flags=<" + flags(flags) + ">]");

    if ((flags & TMFAIL) > 0)
        cacheTx.setRollbackOnly();
    else if ((flags & TMSUSPEND) == TMSUSPEND) {
        try {
            cacheTx.suspend();
        }
        catch (IgniteCheckedException e) {
            throwException("Failed to suspend cache transaction: " + e.getMessage(), e);
        }
    }
}
 
Example #7
Source File: LocalXAConnectionFactory.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
/**
 * This method does nothing since the LocalXAConnection does not support two-phase-commit. This method will
 * return XAResource.XA_RDONLY if the connection isReadOnly(). This assumes that the physical connection is
 * wrapped with a proxy that prevents an application from changing the read-only flag while enrolled in a
 * transaction.
 *
 * @param xid
 *            the id of the transaction branch for this connection
 * @return XAResource.XA_RDONLY if the connection.isReadOnly(); XAResource.XA_OK otherwise
 */
@Override
public synchronized int prepare(final Xid xid) {
    // if the connection is read-only, then the resource is read-only
    // NOTE: this assumes that the outer proxy throws an exception when application code
    // attempts to set this in a transaction
    try {
        if (connection.isReadOnly()) {
            // update the auto commit flag
            connection.setAutoCommit(originalAutoCommit);

            // tell the transaction manager we are read only
            return XAResource.XA_RDONLY;
        }
    } catch (final SQLException ignored) {
        // no big deal
    }

    // this is a local (one phase) only connection, so we can't prepare
    return XAResource.XA_OK;
}
 
Example #8
Source File: XidWrapperImpl.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean equals(Object object)
{
   if (object == this)
      return true;

   if (object == null || !(object instanceof Xid))
      return false;  

   Xid other = (Xid)object;
   return
      (
         formatId == other.getFormatId() && 
         Arrays.equals(globalTransactionId, other.getGlobalTransactionId()) &&
         Arrays.equals(branchQualifier, other.getBranchQualifier())
      );
}
 
Example #9
Source File: XASupport.java    From jTDS with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Format an XA transaction ID into a 140 byte array.
 *
 * @param xid the XA transaction ID
 * @return the formatted ID as a <code>byte[]</code>
 */
private static byte[] toBytesXid(Xid xid) {
    byte[] buffer = new byte[12 +
            xid.getGlobalTransactionId().length +
            xid.getBranchQualifier().length];
    int fmt = xid.getFormatId();
    buffer[0] = (byte) fmt;
    buffer[1] = (byte) (fmt >> 8);
    buffer[2] = (byte) (fmt >> 16);
    buffer[3] = (byte) (fmt >> 24);
    buffer[4] = (byte) xid.getGlobalTransactionId().length;
    buffer[8] = (byte) xid.getBranchQualifier().length;
    System.arraycopy(xid.getGlobalTransactionId(), 0, buffer, 12, buffer[4]);
    System.arraycopy(xid.getBranchQualifier(), 0, buffer, 12 + buffer[4], buffer[8]);
    return buffer;
}
 
Example #10
Source File: MysqlXAConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void end(Xid xid, int flags) throws XAException {
    StringBuilder commandBuf = new StringBuilder(MAX_COMMAND_LENGTH);
    commandBuf.append("XA END ");
    appendXid(commandBuf, xid);

    switch (flags) {
        case TMSUCCESS:
            break; // no-op
        case TMSUSPEND:
            commandBuf.append(" SUSPEND");
            break;
        case TMFAIL:
            break; // no-op
        default:
            throw new XAException(XAException.XAER_INVAL);
    }

    dispatchCommand(commandBuf.toString());
}
 
Example #11
Source File: MysqlXAConnection.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example #12
Source File: NetXAConnectionRequest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void writeXaPrepare(NetConnection conn) throws SqlException {
    NetXACallInfo callInfo = conn.xares_.callInfoArray_[conn.currXACallInfoOffset_];
    Xid xid = callInfo.xid_;
    // don't forget that xars.prepare() does not have flags, assume TMNOFLAGS
    int xaFlags = XAResource.TMNOFLAGS;

    createCommand();

    // save the length bytes for later update
    markLengthBytes(CodePoint.SYNCCTL);

    // SYNCTYPE
    writeSYNCType(CodePoint.SYNCTYPE, CodePoint.SYNCTYPE_PREPARE);

    if (xid.getFormatId() != -1) {
        writeXID(CodePoint.XID, xid);
    } else
    // write the null XID for local transaction on XA connection
    {
        writeNullXID(CodePoint.XID);
    }

    writeXAFlags(CodePoint.XAFLAGS, xaFlags);
    updateLengthBytes();
}
 
Example #13
Source File: ResourceManagerImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public List<Xid> getInDoubtTransactions() {
   List<Xid> xids = new LinkedList<>();

   xids.addAll(getPreparedTransactions());
   xids.addAll(getHeuristicCommittedTransactions());
   xids.addAll(getHeuristicRolledbackTransactions());

   return xids;
}
 
Example #14
Source File: ClientSessionImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void end(final Xid xid, final int flags) throws XAException {
   if (logger.isTraceEnabled()) {
      logger.trace("Calling end:: " + convert(xid) + ", flags=" + convertTXFlag(flags));
   }

   checkXA();

   try {
      if (rollbackOnly) {
         try {
            rollback(false, false);
         } catch (Throwable ignored) {
            logger.debug("Error on rollback during end call!", ignored);
         }
         throw new XAException(XAException.XAER_RMFAIL);
      }

      try {
         flushAcks();

         startCall();
         try {
            sessionContext.xaEnd(xid, flags);
         } finally {
            endCall();
         }
      } catch (XAException xae) {
         throw xae;
      } catch (Throwable t) {
         ActiveMQClientLogger.LOGGER.errorCallingEnd(t);
         // This could occur if the TM interrupts the thread
         XAException xaException = new XAException(XAException.XAER_RMFAIL);
         xaException.initCause(t);
         throw xaException;
      }
   } finally {
      currentXID = null;
   }
}
 
Example #15
Source File: XAResourceArchive.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void forgetQuietly(Xid ignore) {
	try {
		descriptor.forget(xid);
	} catch (XAException ex) {
		logger.warn("Error occurred while forgeting xa-resource.", xid);
	}
}
 
Example #16
Source File: LocalXAResource.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void forget(final Xid xid) {
    checkLock();
    if (xid != null && currentXid.equals(xid)) {
        currentXid = null;
    }
}
 
Example #17
Source File: NetXAConnection.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public int getPort(Xid xid) {
    NetIndoubtTransaction indoubtTxn = (NetIndoubtTransaction) netCon.indoubtTransactions_.get(xid);
    if (indoubtTxn == null) {
        return -1;
    }
    return indoubtTxn.getPort();
}
 
Example #18
Source File: Registry.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
public void setTimeout(Xid xid, long timeout, TimeUnit timeUnit) throws ValidationException {
    Branch branch = branchMap.get(xid);
    if (Objects.isNull(branch)) {
        throw new ValidationException(UNKNOWN_XID_ERROR_MSG + xid);
    }

    if (timeout == 0) {
        return;
    }

    ScheduledFuture<?> future = branchTimeoutExecutorService.schedule(() -> {

        LOGGER.debug("timing out dtx task with xid {}", xid);
        synchronized (branch) {
            if (branch.isPrepared()) {
                LOGGER.debug("Branch already prepared. Won't be timed out. Xid {}", xid);
                return;
            }
            try {
                rollback(xid);
                branch.setState(Branch.State.TIMED_OUT);
            } catch (ValidationException | BrokerException e) {
                LOGGER.error("Error occurred while rolling back timed out branch with Xid " + xid, e);
            }
        }

    }, timeout, timeUnit);
    branch.setTimeoutTaskFuture(future);
}
 
Example #19
Source File: PerfManagedConnection.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void commit(Xid xid, boolean onePhase) throws XAException
{
   if (txCommitDuration > 0)
   {
      try
      {
         Thread.sleep(txCommitDuration);
      }
      catch (Exception e)
      {
         // Ignore
      }
   }
}
 
Example #20
Source File: ServiceXaWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.transaction.xa.XAResource#rollback(javax.transaction.xa.Xid xid)
 */
@Override
public void rollback(Xid xid) throws XAException {
    if (Debug.verboseOn()) Debug.logVerbose("ServiceXaWrapper#rollback() : " + xid.toString(), module);
    // the rollback listener
    if (this.active) {
        Debug.logWarning("rollback() called without end()", module);
    }
    if (this.xid == null || !this.xid.equals(xid)) {
        throw new XAException(XAException.XAER_NOTA);
    }

    final String service = rollbackService;
    final Map<String, ? extends Object> context = rollbackContext;
    final boolean persist = rollbackAsyncPersist;
    final boolean async = rollbackAsync;

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                runService(service, context, persist, (async ? MODE_ASYNC : MODE_SYNC), TYPE_ROLLBACK);
            } catch (XAException e) {
                Debug.logError(e, module);
            }
        }
    };
    thread.start();

    this.xid = null;
    this.active = false;
}
 
Example #21
Source File: JdbcTransactionRepository.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
protected Transaction doFindOne(Xid xid) {
	
	LOG.debug("==>doFindOne xid:" + xid.getGlobalTransactionId());

    List<Transaction> transactions = doFind(Arrays.asList(xid));

    if (!CollectionUtils.isEmpty(transactions)) {
        return transactions.get(0);
    }
    return null;
}
 
Example #22
Source File: TestLocalXaResource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartNoFlagResumeEndDifferentXid() throws XAException {
    final Xid xid = new TestXid();
    resource.start(xid, XAResource.TMNOFLAGS);
    resource.start(xid, XAResource.TMRESUME);
    // flag is never used in the end
    assertThrows(XAException.class, () -> resource.end(new TestXid(), 0));
}
 
Example #23
Source File: EhcacheXAResourceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoverReportsAbortedTx() throws Exception {
  EhcacheXAResource<Long, String> xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory);

  when(journal.recover()).thenReturn(Collections.singletonMap(new TransactionId(new TestXid(0, 0)), (Collection<Long>) Arrays.asList(1L, 2L, 3L)));

  Xid[] recovered = xaResource.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
  assertThat(recovered.length, is(1));
  assertThat(new SerializableXid(recovered[0]), Matchers.<Xid>equalTo(new SerializableXid(new TestXid(0, 0))));
}
 
Example #24
Source File: PerfManagedConnection.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void start(Xid xid, int flags) throws XAException
{
   if (txBeginDuration > 0)
   {
      try
      {
         Thread.sleep(txBeginDuration);
      }
      catch (Exception e)
      {
         // Ignore
      }
   }
}
 
Example #25
Source File: ActiveMQRAXAResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Commit
 *
 * @param xid      A global transaction identifier
 * @param onePhase If true, the resource manager should use a one-phase commit protocol to commit the work done on behalf of xid.
 * @throws XAException An error has occurred
 */
@Override
public void commit(final Xid xid, final boolean onePhase) throws XAException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("commit(" + xid + ", " + onePhase + ")");
   }

   xaResource.commit(xid, onePhase);
}
 
Example #26
Source File: TestLocalXaResource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartNoFlagResumeEndMissingXid() throws XAException {
    final Xid xid = new TestXid();
    resource.start(xid, XAResource.TMNOFLAGS);
    resource.start(xid, XAResource.TMRESUME);
    // flag is never used in the end
    assertThrows(NullPointerException.class, () -> resource.end(null, 0));
}
 
Example #27
Source File: JDBCXAResource.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * Per the JDBC 3.0 spec, this rolls back the transaction for the specified
 * Xid, not necessarily for the transaction associated with this XAResource
 * object.
 *
 * @param xid Xid
 * @throws XAException
 */
public void rollback(Xid xid) throws XAException {

    JDBCXAResource resource = xaDataSource.getResource(xid);

    if (resource == null) {
        throw new XAException(
            "The XADataSource has no such Xid in prepared state:  " + xid);
    }

    resource.rollbackThis();
}
 
Example #28
Source File: FBManagedConnectionFactory.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
int notifyPrepare(FBManagedConnection mc, Xid xid) throws XAException {
    FBManagedConnection targetMc = xidMap.get(xid);

    if (targetMc == null) {
        throw new FBXAException("Commit called with unknown transaction", XAException.XAER_NOTA);
    }

    return targetMc.internalPrepare(xid);
}
 
Example #29
Source File: XidWrapperImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new XidWrapperImpl instance.
 * @param xid The Xid instances
 * @param pad Should the branch qualifier be padded
 * @param jndiName The JNDI name
 */
public XidWrapperImpl(Xid xid, boolean pad, String jndiName)
{
   this.branchQualifier = pad ? new byte[Xid.MAXBQUALSIZE] : new byte[xid.getBranchQualifier().length];      
   System.arraycopy(xid.getBranchQualifier(), 0, branchQualifier, 0, xid.getBranchQualifier().length);      

   this.globalTransactionId = xid.getGlobalTransactionId();
   this.formatId = xid.getFormatId();
   this.jndiName = jndiName;
}
 
Example #30
Source File: JDBCXADataSource.java    From evosql with Apache License 2.0 5 votes vote down vote up
public void addResource(Xid xid, JDBCXAResource xaResource) {
    lock.writeLock().lock();

    try {
        resources.put(xid, xaResource);
    } finally {
        lock.writeLock().unlock();
    }
}