Invoked for transaction inflow of work

@param work The work starting
@param xid The xid of the work
@throws WorkCompletedException With error code WorkException.TX_RECREATE_FAILED if it is unable
to recreate the transaction context
424815
public void startWork(Work work, Xid xid) throws WorkCompletedException
   {
      delegator.startWork(work, xid);
   }
512117
public function commit($xid)
    {
        if ($this->activeTransaction != $xid || $this->activeTransaction === false) {
            return;
        }

        $this->activeTransaction = false;

        if (!$this->connection->commit()) {
            throw new DbException("Commit failed");
        }

        $this->connection->autocommit(true);
    }
404164
public final void commit(final PersistentTransaction transaction) throws SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "commit", "Transaction=" + transaction);

        if (STATE_END_PRECOMMIT == _state)
        {
            // normal processing
        }
        else
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())  SibTr.exit(tc, "commit");
            throw new TaskListException(_state);
        }

        _state = STATE_BEGIN_COMMIT;

        Task task = _firstTask;
        while (null != task)
        {
            task.commitInternal(transaction);
            task = task._nextTask;
        }

        task = _firstTask;
        while (null != task)
        {
            task.commitExternal(transaction);
            task = task._nextTask;
        }

        _state = STATE_END_COMMIT;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())  SibTr.exit(tc, "commit");
    }
1279405
private final void complete(Transaction tx, boolean readOnly)
	{
		if (log.isTraceEnabled())
			log.trace("Complete " + tx);

		if (!readOnly)
			tx.commit();
		else
			tx.rollback();
	}
1206255
private void commitPrepared(Xid xid) throws XAException {
    try {
      // Check preconditions. The connection mustn't be used for another
      // other XA or local transaction, or the COMMIT PREPARED command
      // would mess it up.
      if (state != STATE_IDLE || conn.getTransaction().hasBufferedMutations()) {
        throw new CloudSpannerXAException(CloudSpannerXAException.TWO_PHASE_IDLE,
            Code.FAILED_PRECONDITION, XAException.XAER_RMERR);
      }

      String s = RecoveredXid.xidToString(xid);

      localAutoCommitMode = conn.getAutoCommit();
      conn.setAutoCommit(true);
      try {
        conn.commitPreparedTransaction(s);
      } finally {
        conn.setAutoCommit(localAutoCommitMode);
      }
    } catch (CloudSpannerSQLException ex) {
      throw new CloudSpannerXAException(CloudSpannerXAException.ERROR_COMMIT_PREPARED, ex,
          XAException.XAER_RMERR);
    } catch (SQLException ex) {
      throw new CloudSpannerXAException(CloudSpannerXAException.ERROR_COMMIT_PREPARED, ex,
          Code.UNKNOWN, XAException.XAER_RMERR);
    }
  }
253175
public synchronized void putXid(Xid xid)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "putXid", xid);

      putInt(xid.getFormatId());
      putInt(xid.getGlobalTransactionId().length);
      put(xid.getGlobalTransactionId());
      putInt(xid.getBranchQualifier().length);
      put(xid.getBranchQualifier());

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "putXid");
   }
929419
private void visitTxId() throws IOException {
    if (LayoutVersion.supports(Feature.STORED_TXIDS, editsVersion)) {
      v.visitLong(EditsElement.TRANSACTION_ID);
    }
  }
193991
private void completeTransaction(final String txId, String wsName) {
        getWorkspace().clear();
        // reset the ws cache to the shared (global one)
        setWorkspaceCache(sharedWorkspaceCache());
        // and clear some tx specific data
        COMPLETE_FUNCTION_BY_TX_AND_WS.compute(txId, (transactionId, funcsByWsName) -> {
            funcsByWsName.remove(wsName);
            if (funcsByWsName.isEmpty()) {
                // this is the last ws cache we are clearing for this tx so mark all the keys as unlocked
                LOCKED_KEYS_BY_TX_ID.remove(txId);
                // and remove the map 
                return null;                
            }
            // there are other ws caches which need clearing for this tx, so just return the updated map
            return funcsByWsName;
        });  
    }
1179163
public synchronized void addWork(WorkItem item) throws ProtocolException, TransactionException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "addWork", "WorkItem="+item);

        if (_currentTran != null)
        {
            _currentTran.addWork(item);
        }
        else
        {
            ProtocolException pe = new ProtocolException("TRAN_PROTOCOL_ERROR_SIMS1001");
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "No Xid currently associated with this XAResource!", pe);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "addWork");
            throw pe;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "addWork");
    }
373565
public void runCommit(boolean forceRollback) throws HeuristicMixedException, HeuristicRollbackException, RollbackException {
      if (trace) {
         log.tracef("runCommit(forceRollback=%b) invoked in transaction with Xid=%s", forceRollback, xid);
      }
      if (forceRollback) {
         markRollbackOnly(new RollbackException(FORCE_ROLLBACK_MESSAGE));
      }

      int notifyAfterStatus = 0;

      try {
         if (status == Status.STATUS_MARKED_ROLLBACK) {
            notifyAfterStatus = Status.STATUS_ROLLEDBACK;
            rollbackResources();
         } else {
            notifyAfterStatus = Status.STATUS_COMMITTED;
            commitResources();
         }
      } finally {
         notifyAfterCompletion(notifyAfterStatus);
         DummyBaseTransactionManager.setTransaction(null);
      }
      throwRollbackExceptionIfAny(forceRollback);
   }
745489
private void cleanupTransactions(boolean inCleanup) throws ResourceException 
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();

        //Send connection error event if in transtates: Global transaction, Local Transaction,
        // or Trans ending because cleanup should never be called from these states.  If it is,
        // we rollback and throw the exception

        switch (stateMgr.transtate) {

            case WSStateManager.GLOBAL_TRANSACTION_ACTIVE: {
                try {
                    ((WSRdbXaResourceImpl) xares).end();
                } catch (javax.transaction.xa.XAException xae) {
                    // No FFDC code needed; this is a normal case.
                    // Continue with the rollback if an exception is thrown on end. 
                }
                
                if (aborted) {
                    break;
                }

                try {
                    ((WSRdbXaResourceImpl) xares).rollback();
                } catch (javax.transaction.xa.XAException xae) {
                    FFDCFilter.processException(xae, "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions", "1200", this);

                    if (isTraceOn && tc.isEventEnabled())
                        Tr.event(this, tc, 
                                 "Failed to end or rollback XAResource during cleanup from failure " +
                                                 "state. Continuing with cleanup.",
                                 AdapterUtil.getXAExceptionCodeString(xae.errorCode));

                    throw new DataStoreAdapterException("DSA_ERROR", xae, getClass());
                }

                if (inCleanup && !aborted) 
                {
                    String message =
                                    "Cannot call 'cleanup' on a ManagedConnection while it is still in a " +
                                                    "transaction.";

                    ResourceException resX = new DataStoreAdapterException("DSA_ERROR", null, getClass(), message);

                    // Use FFDC to log the possible components list. 
                    FFDCFilter.processException(resX,
                                                "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                "1562", this, new Object[] { message, " Possible components: Connection Manager, Transactions" });

                    throw resX;
                }
                break; 
            }

            case WSStateManager.LOCAL_TRANSACTION_ACTIVE:
            case WSStateManager.TRANSACTION_ENDING:
            {
                // If no work was done during the transaction, the autoCommit value may still
                // be on.  In this case, just no-op, since some drivers like ConnectJDBC 3.1
                // don't allow commit/rollback when autoCommit is on.  

                if (aborted) {
                    break;
                }
                
                if (!currentAutoCommit)
                    try { // autoCommit is off
                        sqlConn.rollback();
                    } catch (SQLException se) {
                        FFDCFilter.processException(se, "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions", "1223", this);

                        if (isTraceOn && tc.isEventEnabled())
                            Tr.event(this, tc, 
                                     "Connection rollback failed. Continuing with cleanup.");

                        throw new DataStoreAdapterException("DSA_ERROR", se, getClass());
                    }

                if (inCleanup) 
                {
                    // Remove inaccurate statement & redundant information. 

                    String message =
                                    "Cannot call 'cleanup' on a ManagedConnection while it is still in a " +
                                                    "transaction.";

                    ResourceException resX = new DataStoreAdapterException("DSA_ERROR", null, getClass(), message);

                    // Use FFDC to log the possible components list. Comment out for now. 
                    FFDCFilter.processException(resX,
                                                "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                "1592", this, new Object[] { message, " Possible components: Connection Manager" });

                    throw resX;
                }

                break; 
            }

            case WSStateManager.RRS_GLOBAL_TRANSACTION_ACTIVE: 
            { 
              // this case is the same as the previous case except for the rollback, because commit/rollback is illegal during
              // an RRS controlled transaction
                if (inCleanup) 
                { 
                    String message = 
                    "Cannot call 'cleanup' on a ManagedConnection while it is still in an " + 
                                    "RRS managed transaction."; 

                    ResourceException resX = new DataStoreAdapterException("DSA_ERROR", null, getClass(), message);

                    // Use FFDC to log the possible components list. Comment out for now.                                      
                    FFDCFilter.processException(resX, 
                                                "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions", 
                                                "3340", this, new Object[] { message, " Possible components: Connection Manager" }); 

                    throw resX; 
                } 
                break;
            } 

                // case WSStateManager.RECOVERY_IN_PROGRESS)
                //     no-op; allow cleanup to set the state back to NO_TRANSACTION_ACTIVE 
        }

        CommitOrRollbackOnCleanup cleanupAction = dsConfig.get().commitOrRollbackOnCleanup; 

        if (!connectionErrorDetected) // do the checking only if the connection is not bad
        {
            if (cleanupAction != null) 
            {
                /*
                 * DSConfigurationHelper.COMMIT_OR_ROLLBACK_ON_CLEANUP was set on the DataSource, so we will honor
                 * that property
                 */
                if (mcf.supportsUOWDetection) {
                    String operation = "none";
                    try {
                        if (mcf.helper.isInDatabaseUnitOfWork(sqlConn)) {
                            /*
                             * If the DB supports UOW Detection and we are in a DB UOW we will commit or rollback per
                             * setting on the DataSource.
                             */
                            if (cleanupAction == CommitOrRollbackOnCleanup.commit) 
                            {
                                operation = "commit";
                                if (!mcf.loggedDbUowMessage) {
                                    Tr.info(tc, "RESOLVING_DB_IMPLICIT_TRANSACTIONS", operation);
                                    mcf.loggedDbUowMessage = true;
                                } else {
                                    if (isTraceOn && tc.isDebugEnabled())
                                        Tr.debug(this, tc, "committing implicit transaction");
                                }
                                try{
                                    sqlConn.commit();
                                } catch(SQLException e){
                                    String message = "Error resolving implicitly started transaction on ManagedConnection.";
                                    Tr.info(tc, "ERROR_RESOLVING_DB_IMPLICIT_TRANSACTIONS", operation, e);
                                    FFDCFilter.processException(e,
                                                                "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                                "3588", this, new Object[] { message });
                                    if (isTraceOn && tc.isDebugEnabled()) 
                                    {
                                        Tr.debug(this, tc, "Error resolving implicitly started transaction on ManagedConnection.  Exception is:", e);
                                    }
                                    
                                    LocalTransactionException lte = (LocalTransactionException) (new LocalTransactionException(e.getMessage()).initCause(e));
                                    
                                    throw lte;
                                }
                            } else if (cleanupAction == CommitOrRollbackOnCleanup.rollback) 
                            {
                                operation = "rollback";
                                if (!mcf.loggedDbUowMessage) {
                                    Tr.info(tc, "RESOLVING_DB_IMPLICIT_TRANSACTIONS", operation);
                                    mcf.loggedDbUowMessage = true;
                                } else {
                                    if (isTraceOn && tc.isDebugEnabled())
                                        Tr.debug(this, tc, "rolling back implicit transaction");
                                }
                                try{
                                    sqlConn.rollback();
                                } catch(SQLException e){
                                    String message = "Error resolving implicitly started transaction on ManagedConnection.";
                                    Tr.info(tc, "ERROR_RESOLVING_DB_IMPLICIT_TRANSACTIONS", operation, e);
                                    FFDCFilter.processException(e,
                                                                "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                                "3594", this, new Object[] { message });
                                    if (isTraceOn && tc.isDebugEnabled()) 
                                    {
                                        Tr.debug(this, tc, "Error resolving implicitly started transaction on ManagedConnection.  Exception is:", e);
                                    }
                                    
                                    LocalTransactionException lte = (LocalTransactionException) (new LocalTransactionException(e.getMessage()).initCause(e));
                                    
                                    throw lte; 
                                }
                            }
                        }
                    } catch (ResourceException e){
                        throw e;
                    } catch (SQLException e){
                        //This is from mcf.helper.isInDatabaseUnitOfWork(sqlConn), presumably
                        String message = "SQLException created in process of cleaning up implicitly started transaction on ManagedConnection.";
                        FFDCFilter.processException(e,
                                                    "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                    "3786", this, new Object[] { message });
                        ResourceException res = ((ResourceException) new ResourceException("Unable to complete connection cleanup; we shouldn't continue to use this connection.").initCause(e));
                        throw res;
                    } 
                } else // uow detection is not supported  
                {
                    /*
                     * The DB does not support UOW detection. The xxxOnCleanup action will be done automatically.
                     * No message is logged unless trace is enabled
                     */
                    try {
                        if (cleanupAction == CommitOrRollbackOnCleanup.commit) 
                        {
                            if (isTraceOn && tc.isDebugEnabled()) 
                            {
                                Tr.debug(this, tc, "Commit connection automatically per custom property " + DSConfig.COMMIT_OR_ROLLBACK_ON_CLEANUP);
                            }
                            // in the case were we dont' know if unit of wrk exists or not, we will only do the commit/rollback if AC = false
                            if (!currentAutoCommit) {
                                if (isTraceOn && tc.isDebugEnabled())
                                    Tr.debug(this, tc, "AC is false, so we will issue a commit in case there is an implicit tra.");

                                sqlConn.commit();
                            }
                        } else if (cleanupAction == CommitOrRollbackOnCleanup.rollback) 
                        {
                            if (isTraceOn && tc.isDebugEnabled()) 
                            {
                                Tr.debug(this, tc, "Rollback connection automatically per custom property " + DSConfig.COMMIT_OR_ROLLBACK_ON_CLEANUP);
                            }
                            if (!currentAutoCommit) {
                                if (isTraceOn && tc.isDebugEnabled())
                                    Tr.debug(this, tc, "AC is false, so we will issue a rollback in case there is an implicit tra.");

                                sqlConn.rollback();
                            }
                        }
                    } catch (Throwable t) {
                        String message = "Error resolving implicitly started transaction on ManagedConnection.";
                        FFDCFilter.processException(t,
                                                    "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                    "3622", this, new Object[] { message });
                        if (isTraceOn && tc.isDebugEnabled()) 
                        {
                            Tr.debug(this, tc, "Error resolving implicitly started transaction on ManagedConnection.  Exception is:", t);
                        }
                    }
                }
            } else // default behaviour, In this case, we only rollback if unit of work is detected.
            {
                /*
                 * DSConfigurationHelper.COMMIT_OR_ROLLBACK_ON_CLEANUP was not specified, so we check for any
                 * implicit transactions. If there is an implicit tran we will rollback. Otherwise we will do nothing.
                 */
                if (mcf.supportsUOWDetection) {
                    try {
                        if (mcf.helper.isInDatabaseUnitOfWork(sqlConn)) {

                            if (!mcf.loggedImmplicitTransactionFound) {
                                Tr.info(tc, "IMPLICIT_TRANSACTION_FOUND");
                                mcf.loggedImmplicitTransactionFound = true;
                            }
                            sqlConn.rollback();
                        }
                    } catch (Throwable t) {
                        String message = "Error while attempting to rollback database implicitly started transaction on ManagedConnection.";
                        // we are not issueing warnings here because this is the default adn we just need to log it in trace.
                        FFDCFilter.processException(t,
                                                    "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.cleanupTransactions",
                                                    "3761", this, new Object[] { message });

                        if (isTraceOn && tc.isDebugEnabled())
                            Tr.debug(this, tc, "Error while attempting to rollback database implicitly started transaction on ManagedConnection.", t);

                    }
                }
                // if the DB does not support UOW Detection do nothing.
                else {
                    if (!currentAutoCommit
                        && !isTransactional() 
                        && !mcf.warnedAboutNonTransactionalDataSource) {
                        // If AutoCommit=false there might be an unresolved transaction.
                        // We cannot ask the database because it doesn't support unit-of-work detection.
                        // We cannot rely on our internal transaction state because of transactional=false.
                        // CommitOrRollbackOnCleanup is not specified, so we will not be resolving,
                        // the transaction.

                        // Issue a warning that we might be leaving an unresolved transaction in
                        // the database.

                        Tr.warning(tc, "NONTRAN_DATASOURCE_WARNING",
                                   DataSourceDef.transactional.name() + "=false",
                                   DSConfig.COMMIT_OR_ROLLBACK_ON_CLEANUP
                        );
                        mcf.warnedAboutNonTransactionalDataSource = true;
                    }
                }
            }
        } //

    }
191259
public void begin() throws SIIncorrectCallException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "begin");

        // Are we currently in use? do we have work
        // we still need to commit?
        if (_state == TransactionState.STATE_ACTIVE && _workList != null)
        {
          SIIncorrectCallException ice = new SIIncorrectCallException(nls.getFormattedMessage("TRAN_PROTOCOL_ERROR_SIMS1001", null, "TRAN_PROTOCOL_ERROR_SIMS1001"));
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Cannot begin new LocalTran. Existing work needs completing first!", ice);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "begin");
            throw ice;
        }

        synchronized(this)
        {
          _ptid     = null;
        }
        _workList = null;
        _size     = 0;

        _callbacks.clear();

        _state = TransactionState.STATE_ACTIVE;


        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "begin");
    }
18243
public void resume(Transaction tx) {
		try {
			if ( tx != null ) {
				tm.resume( tx );
			}
		}
		catch (Exception e) {
			throw log.cannotResumeTx( e );
		}
	}
1356067
protected void eventPreUnlocked(SIMPMessage msg, TransactionCommon tran)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "eventPreUnlocked", new Object[]{ msg, tran});
    
    if ((msg.guessRedeliveredCount() + 1) >= _baseDestHandler.getMaxFailedDeliveries())
    {
      // Override the check of the threshold from the local case because we only
      // reroute to the exception destination if we are local to the queuepoint.
      // If the threshold is reached we remove the AIMessageItem and drive the expiry
      // code - which should flow the relevant redeliveryCount back to the DME
      // in a reject.
      
      boolean tranCreated = false;
      if (tran == null)
      {
        /* Create a new transaction under which to perform the reroute */
        tran = _tranManager.createLocalTransaction(false);
        tranCreated = true;
      }
      
      // Perform a forced expiry
      ((AIMessageItem)msg).setRejectTransactionID(tran.getPersistentTranId());
      // Increment the unlockCount
      _aih.incrementUnlockCount(msg.getMessage().getGuaranteedRemoteGetValueTick());
      
      // Remove msg
      try
      {
        if (msg.isInStore())
        {
          Transaction msTran = _messageProcessor.resolveAndEnlistMsgStoreTransaction(tran);
          msg.remove(msTran, msg.getLockID());
        }
        
        if (tranCreated)
          ((LocalTransaction)tran).commit();
        
        // If successful, make sure we dont try to unlock the msg
        msg.setRedeliveryCountReached();
      }
      catch (MessageStoreException e) 
      {
        // FFDC
        FFDCFilter.processException(
          e,
          "com.ibm.ws.sib.processor.impl.RemoteConsumerDispatcher.eventPreUnlocked",
          "1:1090:1.97.2.21",
          this);

        SibTr.exception(tc, e);
        // Any exception will mean we wait until expiry for a reject
      }
      catch (SIException e)
      {
        // FFDC
        FFDCFilter.processException(
          e,
          "com.ibm.ws.sib.processor.impl.RemoteConsumerDispatcher.eventPreUnlocked",
          "1:1102:1.97.2.21",
          this);

        SibTr.exception(tc, e);
        // Any exception will mean we wait until expiry for a reject
      }      
    }
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "eventPreUnlocked");
  }
963232
public static TransactionException closingFailed(TransactionOLTP tx, Exception e) {
        return new TransactionException(CLOSE_FAILURE.getMessage(tx.keyspace()), e);
    }
1004295
public void rollback(Xid xid) throws XAException
    {
        if (tc.isEntryEnabled()) Tr.entry(tc, "rollback", xid);

		final JCATranWrapper txWrapper;
		
		try
		{
			validateXid(xid);

			// Get the wrapper adding an association in the process
			txWrapper = getTxWrapper(xid, true);
		}
		catch (XAException e)
		{
			if (tc.isEntryEnabled()) Tr.exit(tc, "rollback", "caught XAException: " + XAReturnCodeHelper.convertXACode(e.errorCode));
			throw e;
		}

		try
		{
			txWrapper.rollback();
		}
		catch (XAException e)
		{
			TxExecutionContextHandler.removeAssociation(txWrapper);

			if (tc.isEntryEnabled()) Tr.exit(tc, "rollback", "rethrowing XAException: " + XAReturnCodeHelper.convertXACode(e.errorCode));
			throw e;
		}

		TxExecutionContextHandler.removeAssociation(txWrapper);

        if (tc.isEntryEnabled()) Tr.exit(tc, "rollback");
    }
277100
public final void commitExternal(final PersistentTransaction transaction) throws SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "commitExternal", transaction);

        // I did not expect that - the xaCommit for all Add task
        // must be called *after* all internalCommitAdd() calls
        // on the same transaction.  So we move the xaCommit call
        // to the 'external' commit phase.
        getLink().commitAdd(transaction);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "commitExternal");
    }