/*
Find the Transactional annotation being processed
178079
protected Transactional getTransactionalAnnotation(InvocationContext context, String txLabel) throws Exception {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "getTransactionalAnnotation", new Object[] { context, this });

        // Check for method annotation
        Transactional interceptor = findTransactionalInterceptor(context.getMethod());

        if (interceptor == null) {
            // Check for class annotation
            // Getting the class of the target only gives us a WELD proxy that won't have the annotations
            // if they're not defined as @Inherited, so we need to go a level higher in the class hierarchy.
            interceptor = findTransactionalInterceptor(context.getTarget().getClass().getSuperclass());
        }

        if (interceptor == null) {
            // We can't find the annotation we're processing so bail out
            throw new Exception("Can't find @Transactional annotation in AroundInvoke for TxType." + txLabel);
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "getTransactionalAnnotation", interceptor);
        return interceptor;
    }
192019
private Transaction onBegin()
    {
        Transaction tx;
        if (((StatelessSessionImpl) s).getTransactionCoordinator().isTransactionActive())
        {
            tx = ((StatelessSessionImpl) s).getTransaction();
        }
        else
        {
            tx = s.beginTransaction();
        }
        return tx;
    }
1024664
public void processLocalTransactionCommittedEvent(Object handle) throws ResourceException {
        // A application level local transaction has been committed.

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();

        if (isTraceOn) 
        {
            if (tc.isEntryEnabled()) 
                Tr.entry(this, tc, "processLocalTransactionCommittedEvent", handle);

            if (tc.isDebugEnabled()) 
            { 
                String cId = null;
                try {
                    cId = mcf.getCorrelator(this); 
                } catch (SQLException x) {
                    // will just log the exception here and ignore it since its in trace
                    Tr.debug(this, tc, "got an exception trying to get the correlator in commit, exception is: ", x);
                }

                if (cId != null) {
                    StringBuffer stbuf = new StringBuffer(200);
                    stbuf.append("Correlator: DB2, ID: ");
                    stbuf.append(cId);
                    if (xares != null) {
                        stbuf.append(" Transaction : ");
                        stbuf.append(xares);
                    }
                    stbuf.append(" COMMIT");
                    Tr.debug(this, tc, stbuf.toString());
                }
            } 
        }

        ResourceException re = stateMgr.isValid(WSStateManager.LT_COMMIT);
        if (re == null) {
            // 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 (!currentAutoCommit)
                try { // autoCommit is off
                    sqlConn.commit();
                } catch (SQLException se) {
                    FFDCFilter.processException(se, "com.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl.processLocalTransactionCommittedEvent", "554", this);
                    throw AdapterUtil.translateSQLException(se, this, true, getClass());
                }

            //Set the state only after the commit has succeeded.  Else, we change the
            // state but it has not yet been committed. - a real mess

            // Already validated the state so just set it. 
            stateMgr.transtate = WSStateManager.NO_TRANSACTION_ACTIVE;
        } else {
            throw re;
        }

        // Fill in the ConnectionEvent only if needed. 
        connEvent.recycle(ConnectionEvent.LOCAL_TRANSACTION_COMMITTED, null, handle);

        if (isTraceOn && tc.isEventEnabled())
            Tr.event(this, tc, 
                     "Firing LOCAL TRANSACTION COMMITTED event for: " + handle,
                     this);

        // loop through the listeners
        for (int i = 0; i < numListeners; i++) {
            // send Local Transaction Committed event to the current listener
            ivEventListeners[i].localTransactionCommitted(connEvent); 
        }

        // Reset the indicator so lazy enlistment will be signaled if we end up in a
        // Global Transaction. 
        wasLazilyEnlistedInGlobalTran = false;

        // Replace ConnectionEvent caching with a single reusable instance per
        // ManagedConnection. 

        if (isTraceOn && tc.isEntryEnabled()) 
        {
            Tr.exit(this, tc, "processLocalTransactionCommittedEvent");
        }
    }
809576
public static boolean isCommittedProcessed(byte[] stateBytes, Transaction tx) {
    long writePointer = Bytes.toLong(stateBytes, 0, Longs.BYTES);
    if (!tx.isVisible(writePointer)) {
      return false;
    }
    byte state = stateBytes[Longs.BYTES + Ints.BYTES];
    return state == ConsumerEntryState.PROCESSED.getState();
  }
1054569
@Override
    public CompletableFuture<Void> completeCommittingTransactions(VersionedMetadata<CommittingTransactionsRecord> record) {
        // create all transaction entries in committing txn list. 
        // remove all entries from active txn in epoch. 
        // reset CommittingTxnRecord
        long time = System.currentTimeMillis();

        Map<String, byte[]> completedRecords = record.getObject().getTransactionsToCommit().stream()
                                                               .collect(Collectors.toMap(UUID::toString, 
                                                                       x -> new CompletedTxnRecord(time, TxnStatus.COMMITTED).toBytes()));
        CompletableFuture<Void> future;
        if (record.getObject().getTransactionsToCommit().size() == 0) {
            future = CompletableFuture.completedFuture(null);
        } else {
            future = createCompletedTxEntries(completedRecords)
                    .thenCompose(x -> getTransactionsInEpochTable(record.getObject().getEpoch())
                            .thenCompose(table -> storeHelper.removeEntries(table, completedRecords.keySet())))
                    .thenCompose(x -> tryRemoveOlderTransactionsInEpochTables(epoch -> epoch < record.getObject().getEpoch()));
        }
        return future
                .thenCompose(x -> Futures.toVoid(updateCommittingTxnRecord(new VersionedMetadata<>(CommittingTransactionsRecord.EMPTY,
                        record.getVersion()))));
    }
755950
private Long findTransactionBeginPosition(ErosaConnection mysqlConnection, final EntryPosition entryPosition)
                                                                                                                 throws IOException {
        // 针对开始的第一条为非Begin记录，需要从该binlog扫描
        final java.util.concurrent.atomic.AtomicLong preTransactionStartPosition = new java.util.concurrent.atomic.AtomicLong(0L);
        mysqlConnection.reconnect();
        mysqlConnection.seek(entryPosition.getJournalName(), 4L, entryPosition.getGtid(), new SinkFunction<LogEvent>() {

            private LogPosition lastPosition;

            public boolean sink(LogEvent event) {
                try {
                    CanalEntry.Entry entry = parseAndProfilingIfNecessary(event, true);
                    if (entry == null) {
                        return true;
                    }

                    // 直接查询第一条业务数据，确认是否为事务Begin
                    // 记录一下transaction begin position
                    if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
                        && entry.getHeader().getLogfileOffset() < entryPosition.getPosition()) {
                        preTransactionStartPosition.set(entry.getHeader().getLogfileOffset());
                    }

                    if (entry.getHeader().getLogfileOffset() >= entryPosition.getPosition()) {
                        return false;// 退出
                    }

                    lastPosition = buildLastPosition(entry);
                } catch (Exception e) {
                    processSinkError(e, lastPosition, entryPosition.getJournalName(), entryPosition.getPosition());
                    return false;
                }

                return running;
            }
        });

        // 判断一下找到的最接近position的事务头的位置
        if (preTransactionStartPosition.get() > entryPosition.getPosition()) {
            logger.error("preTransactionEndPosition greater than startPosition from zk or localconf, maybe lost data");
            throw new CanalParseException("preTransactionStartPosition greater than startPosition from zk or localconf, maybe lost data");
        }
        return preTransactionStartPosition.get();
    }
1133873
public static void process(@NonNull Document textDocument, AnnotatableType... annotationTypes) {
      if (annotationTypes == null || annotationTypes.length == 0) {
         return;
      }

      for (AnnotatableType annotationType : annotationTypes) {
         if (annotationType == null) {
            continue;
         }

         if (textDocument.getAnnotationSet().isCompleted(annotationType)) {
            continue;
         }

         if (log.isLoggable(Level.FINEST)) {
            log.finest("Annotating for {0}", annotationType);
         }

         Annotator annotator = AnnotatorCache.getInstance().get(annotationType, textDocument.getLanguage());

         if (annotator == null) {
            throw new IllegalStateException("Could not get annotator for " + annotationType);
         }

         if (!annotator.satisfies().contains(annotationType)) {
            throw new IllegalStateException(annotator.getClass().getName() + " does not satisfy " + annotationType);
         }

         //Get the requirements out of the way
         for (AnnotatableType prereq : annotator.requires()) {
            process(textDocument, prereq);
         }

         annotator.annotate(textDocument);
         for (AnnotatableType type : annotator.satisfies()) {
            textDocument
               .getAnnotationSet()
               .setIsCompleted(type, true, annotator.getClass().getName() + "::" + annotator.getVersion());
         }

      }
   }
813613
@Override
    public void localTransactionStarted(ConnectionEvent event) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "localTransactionStarted");
        }

        if (event.getId() == ConnectionEvent.LOCAL_TRANSACTION_STARTED) {

            //
            // The LocalTransactionStarted event for local transaction connections is analogous to the
            //  InteractionPending event for xa transaction connections.  JMS's usage of ManagedSessions
            //  is very dependent on the ability to use these two events for properly enlisting their
            //  unshared connections.  When a ManagedSession is first created, it is done under an LTC.
            //  When that LTC ends, some partial cleanup is done on the MCWrapper, but it is not put
            //  back into the pool because the unshared connection handle is still active.  One of the
            //  items that gets cleaned up is the coordinator within the MCWrapper.  This makes sense
            //  since the LTC has ended.  But, when it is determined by JMS that it's time to get
            //  enlisted in the current transaction, a null coordinator causes all kinds of problems
            //  (reference the string of defects that have attempted to correct this situation).  The
            //  solution determined seems to be the right one.  In both localTransactionStarted
            //  and interactionPending methods, we need to check if the MCWrapper coordinator is null and
            //  if it is null, then go out to the TM and get it updated.
            //
            // Note that this special null coordinator processing is due to the SmartHandle support
            //  utilized by JMS and RRA.  Without smart handles, the coordinator would have gotten
            //  re-initialized during the handle re-association logic.
            //
            // In addition, we have determined that the check for involvedInTransaction() is not necessary
            //  (and causes problems for the scenario described just previous).  Since the getCurrentTranWrapper()
            //  already checks for a valid state setting before returning, we can just rely on that method to
            //  do the proper checking instead of calling the involvedInTransaction() method.
            //
            UOWCoordinator uowCoordinator = mcWrapper.getUOWCoordinator();

            if (uowCoordinator == null) {
                uowCoordinator = mcWrapper.updateUOWCoordinator();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "uowCoord was null, updating it to current coordinator");
                }
            }

            // if the coordinator is still null, then we are running with NO transaction
            //  context on the thread.  This case currently needs to be supported because
            //  servlets can spin their own threads which would not have context.
            // Note: it is very rare that users do this.  All other occurances are
            //  considered to be an error.
            if (uowCoordinator == null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                    Tr.exit(this, tc, "localTransactionStarted", "no transaction context, return without enlisting");
                }
                return;
            }

            /*
             * We know we are in a transaction but we need to verify that it is not a global transaction
             * before continuing.
             */
            if (tc.isDebugEnabled() && uowCoordinator.isGlobal()) {
                IllegalStateException ise = new IllegalStateException("Illegal attempt to start a local transaction within a global (user) transaction");
                Tr.debug(this, tc, "ILLEGAL_USE_OF_LOCAL_TRANSACTION_J2CA0295", ise);
            }

            /*
             * The ManagedConnection should be associated with a transaction. And, if it's not,
             * the getCurrentTranWrapper() method will detect the situation and throw an
             * exception.
             *
             * enlist() the ManagedConnection from the transaction.
             */

            try {
                mcWrapper.getCurrentTranWrapper().enlist();
            } catch (ResourceException e) {
                /*
                 * // Can't enlist, something went wrong.
                 * // Destroy the connection(s) so it can't cause any future problems.
                 * try {
                 * mcWrapper.markStale();
                 * mcWrapper.releaseToPoolManager();
                 * }
                 * catch (Exception ex) {
                 * // Nothing to do here. PoolManager has already logged it.
                 * // Since we are in cleanup mode, we will not surface a Runtime exception to the ResourceAdapter
                 * FFDCFilter.processException(ex, "com.ibm.ejs.j2c.ConnectionEventListener.localTransactionStarted", "473", this);
                 * if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                 * Tr.debug(this, tc, "localTransactionStarted: Error when trying to enlist " + mcWrapper.getPoolManager().getPmiName() +
                 * " caught exception, but will continue processing: ", ex);
                 * }
                 * }
                 */

                FFDCFilter.processException(e, "com.ibm.ejs.j2c.ConnectionEventListener.localTransactionStarted", "481", this);
                // add datasource name to message
                Tr.error(tc, "ENLIST_FAILED_J2CA0074", "localTransactionStarted", e, mcWrapper.gConfigProps.cfName);
                // Moved event.getSource() inside of catch block for performance reasons
                ManagedConnection mc = null;
                try {
                    mc = (ManagedConnection) event.getSource();
                } catch (ClassCastException cce) {
                    Tr.error(tc, "GET_SOURCE_CLASS_CAST_EXCP_J2CA0098", cce);
                    throw new IllegalStateException("ClassCastException occurred attempting to cast event.getSource to ManagedConnection");
                }
                ConnectionEvent errorEvent = new ConnectionEvent(mc, ConnectionEvent.CONNECTION_ERROR_OCCURRED);
                this.connectionErrorOccurred(errorEvent);

                RuntimeException rte = new IllegalStateException(e.getMessage());
                throw rte;
            }
        } else {
            // Connection Event passed in doesn't match the method called.
            // This should never happen unless there is an error in the ResourceAdapter.
            processBadEvent("localTransactionStarted", ConnectionEvent.LOCAL_TRANSACTION_STARTED, event);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "localTransactionStarted");
        }
        return;
    }
585347
function (options) {
      if (!this.isCommitted()) {
        if (!this.isCancelled() && hasChanges(this)) {
          var effectiveOptions = options || {};
          var binding = this._binding;
          var metaBinding = binding.meta();

          var previousBackingValue = null, previousBackingMeta = null;
          if (effectiveOptions.notify !== false) {
            previousBackingValue = getBackingValue(binding);
            previousBackingMeta = getBackingValue(metaBinding);
          }

          this._finishedUpdates = commitSilently(this);
          var affectedPaths = this._finishedUpdates.map(function (update) { return update.affectedPath; });

          if (effectiveOptions.notify !== false) {
            var filteredPaths = filterRedundantPaths(affectedPaths);

            var stateTransition = mkStateTransition(
              getBackingValue(binding), previousBackingValue, getBackingValue(metaBinding), previousBackingMeta
            );

            notifyGlobalListeners(binding, filteredPaths[0], stateTransition);
            filteredPaths.forEach(function (path) {
              notifyNonGlobalListeners(binding, path, stateTransition);
            });
          }
        }

        return this;
      } else {
        throw new Error('Morearty: transaction already committed');
      }
    }
1328815
protected boolean isExistingTransaction(Object transaction) {
        ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction;

        return super.isExistingTransaction(actualTransactionObject
                .getHibernateTransactionObject());
    }
1024555
public TransactionImpl getTransaction()
    {
        TxBuffer buf = (TxBuffer) txRepository.get();
        return buf != null ? buf.getInternTx() : null;
    }
1150804
@Override
	public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
		for (TypeElement dataSource : dataSets) {
			SQLiteDatabaseSchema currentSchema = createDataSource(dataSource);

			// Analyze beans BEFORE daos, because beans are needed for DAO
			// definition
			for (String daoName : currentSchema.getDaoNameSet()) {
				// check dao into bean definition
				createSQLEntityFromDao(currentSchema, dataSource, daoName);

			} // end foreach bean

			// sort table by its name, BEFORE inject generated tables and entities
			Collections.sort(currentSchema.getCollection(), new Comparator<SQLiteDaoDefinition>() {
				@Override
				public int compare(SQLiteDaoDefinition o1, SQLiteDaoDefinition o2) {
					return o1.getTableName().compareTo(o2.getTableName());
				}
			});

			// DAO analysis
			// Get all generated dao definitions
			for (String generatedDaoItem : currentSchema.getDaoNameSet()) {
				createSQLDaoDefinition(currentSchema, globalBeanElements, globalDaoElements, generatedDaoItem);
			}

			analyzeForeignKey(currentSchema);

			// Relation must be done AFTER foreign key building!!!
			analyzeRelations(currentSchema);

			// Analyze custom bean
			analyzeCustomBeanForSelect(currentSchema);
			
			if (currentSchema.getCollection().size() == 0) {
				AssertKripton.fail("DataSource class %s with @%s annotation has no defined DAOs",
						currentSchema.getElement().getSimpleName().toString(),
						BindDataSource.class.getSimpleName(),
						BindDao.class.getSimpleName()
						);
				// info(msg);				
				return true;
			}

			// for each dao definition, we define its uid
			int uid = 0;
			for (SQLiteDaoDefinition daoDefinition : currentSchema.getCollection()) {
				String daoFieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, daoDefinition.getName())
						+ "_UID";

				daoDefinition.daoUidName = daoFieldName;
				daoDefinition.daoUidValue = uid;

				uid++;
			}

			schemas.add(currentSchema);
		} // end foreach dataSource

		return true;
	}
1063637
function (internalInstance, transaction, updateBatchNumber) {
    if (internalInstance._updateBatchNumber !== updateBatchNumber) {
      // The component's enqueued batch number should always be the current
      // batch or the following one.
      process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0;
      return;
    }
    if (process.env.NODE_ENV !== 'production') {
      if (internalInstance._debugID !== 0) {
        ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement);
      }
    }
    internalInstance.performUpdateIfNecessary(transaction);
    if (process.env.NODE_ENV !== 'production') {
      if (internalInstance._debugID !== 0) {
        ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
      }
    }
  }
1142967
public static final void getAnnotationCMTransactions(TransactionAttribute[] tranAttrs,
                                                         int methodInterfaceType,
                                                         Method[] beanMethods,
                                                         BeanMetaData bmd)
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "getAnnotationCMTransactions");

        for (int i = 0; i < beanMethods.length; i++)
        {
            // Only get the value from annotations if it is not already set by WCCM
            if (tranAttrs[i] == null)
            {
                javax.ejb.TransactionAttribute methTranAttr = null;

                // Don't bother looking for annotations, if we're told there are none.
                if (!bmd.metadataComplete) {
                    methTranAttr = beanMethods[i].getAnnotation(javax.ejb.TransactionAttribute.class);

                    if (methTranAttr == null &&
                        // EJB 3.2, section 4.3.14:
                        // "A stateful session bean's PostConstruct, PreDestroy,
                        // PrePassivate or PostActivate lifecycle callback
                        // interceptor method is invoked in the scope of a
                        // transaction determined by the transaction attribute
                        // specified in the lifecycle callback method's metadata
                        // annotations or deployment descriptor"
                        (bmd.type != InternalConstants.TYPE_STATEFUL_SESSION ||
                        methodInterfaceType != InternalConstants.METHOD_INTF_LIFECYCLE_INTERCEPTOR))
                    {
                        methTranAttr = beanMethods[i].getDeclaringClass().getAnnotation(javax.ejb.TransactionAttribute.class);

                        if (isTraceOn && tc.isDebugEnabled() &&
                            methTranAttr != null)
                            Tr.debug(tc, beanMethods[i].getName() + " from class " +
                                         beanMethods[i].getDeclaringClass().getName());
                    }
                }

                if (methTranAttr == null) {
                    // set the default value
                    if (methodInterfaceType == InternalConstants.METHOD_INTF_LIFECYCLE_INTERCEPTOR &&
                        bmd.type == InternalConstants.TYPE_STATEFUL_SESSION) {
                        // "By default a stateful session bean's PostConstruct,
                        // PreDestroy, PrePassivate and PostActivate methods are
                        // executed in an unspecified transactional context."
                        //
                        // WebSphere implements an unspecified transactional
                        // context as TX_NOT_SUPPORTED.
                        tranAttrs[i] = TransactionAttribute.TX_NOT_SUPPORTED;
                    } else {
                        tranAttrs[i] = TransactionAttribute.TX_REQUIRED;
                    }

                    if (isTraceOn && tc.isDebugEnabled())
                        Tr.debug(tc, beanMethods[i].getName() + " = REQUIRED (defaulted)");
                } else {
                    // Switch the javax.ejb.TransactionAttribute to com.ibm.websphere.csi.TransactionAttribute
                    int tranType = methTranAttr.value().ordinal();
                    tranAttrs[i] = txAttrFromJEE15Map[tranType];

                    if (isTraceOn && tc.isDebugEnabled())
                        Tr.debug(tc, beanMethods[i].getName() + " = " + methTranAttr.value());
                }
            }
        }

        if (isTraceOn && tc.isEntryEnabled()) {
            Tr.exit(tc, "getAnnotationsCMTransactions", Arrays.toString(tranAttrs));
        }

    }
1331071
private boolean shouldRollback(Transactional annotation, Exception e)
	{
		return isInstanceOf(e, annotation.rollbackOn()) && !isInstanceOf(e, annotation.exceptOn());
	}
1300742
@Override
    public final EntityTransaction getTransaction()
    {
        checkClosed();
        if (this.transactionType == PersistenceUnitTransactionType.JTA)
        {
            throw new IllegalStateException("A JTA EntityManager cannot use getTransaction()");
        }

        if (this.entityTransaction == null)
        {
            this.entityTransaction = new KunderaEntityTransaction(this);
        }
        return this.entityTransaction;
    }
105953
@Override
    public int getTransactionTimeout() {
        for (TransactionSettingsProvider s : _serverWideConfigProvider.getTransactionSettingsProviders().services()) {
            if (s.isActive()) {

                final GlobalTransactionSettings gts = s.getGlobalTransactionSettings();

                if (gts != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Found a GlobalTransactionSettings");
                    return gts.getTransactionTimeout();
                } else {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "No GlobalTransactionSettings on this thread");
                }
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "Found the TransactionSettingsProvider but it was inactive");
            }
        }

        return -1;
    }