Workaround for CAM-5609: In general, only async continuations should be represented as TransitionInstances, but
due to this bug, completed multi-instances are represented like that as well. We tolerate the second case.
978414
protected boolean isAsyncTransitionInstance(TransitionInstance transitionInstance) {
    String executionId = transitionInstance.getExecutionId();
    ExecutionEntity execution = Context.getCommandContext().getExecutionManager().findExecutionById(executionId);
    for (JobEntity job : execution.getJobs()) {
      if (AsyncContinuationJobHandler.TYPE.equals(job.getJobHandlerType())) {
        return true;
      }
    }

    return false;
  }
474116
@Override
    public void deregisterAsynchConsumerCallback()
                    throws SISessionUnavailableException, SISessionDroppedException,
                    SIErrorException,
                    SIIncorrectCallException
    {
        if (TraceComponent.isAnyTracingEnabled() && CoreSPIConsumerSession.tc.isEntryEnabled())
            SibTr.entry(CoreSPIConsumerSession.tc, "deregisterAsynchConsumerCallback", this);
        //Deregister the AsynchConsumer by registering null with the LCP
        //the other params don't matter
        registerAsynchConsumerCallback(null, 1, 0, 1, null);
        if (TraceComponent.isAnyTracingEnabled() && CoreSPIConsumerSession.tc.isEntryEnabled())
            SibTr.exit(CoreSPIConsumerSession.tc, "deregisterAsynchConsumerCallback");
    }
1268824
@Override
    protected void checkTransitions(StreamTokenizer streamTokenizer) throws FSMParseException {

        // Only if no states are defined we add all from the transitions we found.
        // This is necessary because states are not necessarily defined in FSMs.
        if (getStates().isEmpty()) {
            getStates().addAll(transitionsFSM.keySet());
        }

        // copy the set of states
        final Set<Integer> newStates = new HashSet<>(getStates());

        // retrieve the initial state in the FSM source
        final Integer initialState = getStates().iterator().next();

        // make the actual FSM transitions
        makeTransitions(initialState, null, newStates, 0, output != null ? new WordBuilder<>() : null, streamTokenizer);

        // check we do not have a partial FSM
        if (!newStates.isEmpty()) {
            throw new FSMParseException(String.format(PARTIAL_FSM, newStates, initialState), streamTokenizer);
        }
    }
877772
@Override
    public boolean addSync() throws ResourceException {

        if (tc.isEntryEnabled()) {
            Tr.entry(this, tc, "addSync");
        }

        UOWCoordinator uowCoord = mcWrapper.getUOWCoordinator();

        if (uowCoord == null) {
            IllegalStateException e = new IllegalStateException("addSync: illegal state exception. uowCoord is null");
            Tr.error(tc, "ILLEGAL_STATE_EXCEPTION_J2CA0079", "addSync", e);
            if (tc.isEntryEnabled())
                Tr.exit(this, tc, "addSync", e);
            throw e;
        }

        try {
            // added a second synchronization
            //
            // RRS Transactions don't follow the XA model, and therefore don't receive callbacks for
            // end, prepare, and commit/rollback.  Defect  added State Management for RRS
            // controlled transactions, and because the state on the adapter is, for XA transactions,
            // reset during the commit callback, we need to reset the adapter state as close as
            // possible after the commit time.  Therefore, we need to register as a priority sync
            // for the purpose of resetting the adapter state.  We need to also register as a normal
            // sync, however, because we have additional afterCompletion code that returns the
            // managed connection to the free pool.  This code must be executed AFTER DB2 gets its
            // afterCompletion callback.  DB2 is also registered as a priority sync, and since we
            // can't guarantee the order of the afterCompletion callbacks if two syncs are registered
            // as priority, we need to register as a regular sync to execute this part of the code.
            EmbeddableWebSphereTransactionManager tranMgr = mcWrapper.pm.connectorSvc.transactionManager;
            tranMgr.registerSynchronization(uowCoord, this); 
            final ManagedConnection mc = mcWrapper.getManagedConnection();

            // Registering a synchronization object with priority SYNC_TIER_RRS (3) allows the
            // synchronization to be called last.
            if (mc instanceof WSManagedConnection)
            {
                tranMgr.registerSynchronization( 
                uowCoord,
                                                new Synchronization()
                                                {
                                                    @Override
                                                    public void beforeCompletion() 
                                                    {
                                                    } 

                                                    @Override
                                                    public void afterCompletion(int status) 
                                                    {
                                                        ((WSManagedConnection) mc).afterCompletionRRS();
                                                    }
                                                },
                                                RegisteredSyncs.SYNC_TIER_RRS
               );
            }
        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(
                                                        e,
                                                        "com.ibm.ejs.j2c.RRSGlobalTransactionWrapper.addSync",
                                                        "238",
                                                        this);
            Tr.error(tc, "REGISTER_WITH_SYNCHRONIZATION_EXCP_J2CA0026", "addSync", e, "ResourceException");
            ResourceException re = new ResourceException("addSync: caught Exception");
            re.initCause(e); 
            if (tc.isEntryEnabled())
                Tr.exit(this, tc, "addSync", e);
            throw re;
        }
        if (tc.isEntryEnabled()) {
            Tr.exit(this, tc, "addSync", true);
        }
        return true;
    }
6253
function evaluateState(state, instance, message) {
    var result = false;
    // delegate to child regions first if a non-continuation
    if (message !== state) {
        state.regions.every(function (region) {
            var currentState = instance.getLastKnownState(region);
            if (currentState && evaluateState(currentState, instance, message)) {
                result = true;
                return isActive(state, instance); // NOTE: this just controls the every loop; also isActive is a litte costly so using sparingly
            }
            return true; // NOTE: this just controls the every loop
        });
    }
    // if a transition occured in a child region, check for completions
    if (result) {
        if ((message !== state) && isComplete(state, instance)) {
            evaluateState(state, instance, state);
        }
    }
    else {
        // otherwise look for a transition from this state
        var transitions = state.outgoing.filter(function (transition) { return transition.guard(message, instance); });
        if (transitions.length === 1) {
            // execute if a single transition was found
            result = traverse(transitions[0], instance, message);
        }
        else if (transitions.length > 1) {
            // error if multiple transitions evaluated true
            exports.console.error(state + ": multiple outbound transitions evaluated true for message " + message);
        }
    }
    return result;
}
473799
public void handleChildTransition(CmmnExecution child, String transition) {
    // Step 1: collect all affected sentries
    List<String> affectedSentries = collectAffectedSentries(child, transition);

    // Step 2: fire force update on all case sentry part
    // contained by a affected sentry to provoke an
    // OptimisticLockingException
    forceUpdateOnSentries(affectedSentries);

    // Step 3: check each affected sentry whether it is satisfied.
    // the returned list contains all satisfied sentries
    List<String> satisfiedSentries = getSatisfiedSentries(affectedSentries);

    // Step 4: reset sentries -> satisfied == false
    resetSentries(satisfiedSentries);

    // Step 5: fire satisfied sentries
    fireSentries(satisfiedSentries);

  }
890258
protected void ensureTransitionAllowed(CmmnActivityExecution execution, CaseExecutionState expected, CaseExecutionState target, String transition) {
    String id = execution.getId();

    CaseExecutionState currentState = execution.getCurrentState();

    // the state "suspending" or "terminating" will set immediately
    // inside the corresponding AtomicOperation, that's why the
    // previous state will be used to ensure that the transition
    // is allowed.
    if (execution.isTerminating() || execution.isSuspending()) {
      currentState = execution.getPreviousState();
    }

    // is the case execution already in the target state
    if (target.equals(currentState)) {
      throw LOG.isAlreadyInStateException(transition, id, target);

    } else
    // is the case execution in the expected state
    if (!expected.equals(currentState)) {
      throw LOG.unexpectedStateException(transition, id, expected, currentState);
    }
  }
1129338
private void waitForInstances(String flowletId, int expectedInstances) throws InterruptedException, TimeoutException {
    int numRunningFlowlets = getNumberOfProvisionedInstances(flowletId);
    int secondsWaited = 0;
    while (numRunningFlowlets != expectedInstances) {
      LOG.debug("waiting for {} instances of {} before suspending flowlets", expectedInstances, flowletId);
      TimeUnit.SECONDS.sleep(SECONDS_PER_WAIT);
      secondsWaited += SECONDS_PER_WAIT;
      if (secondsWaited > MAX_WAIT_SECONDS) {
        String errmsg =
          String.format("waited %d seconds for instances of %s to reach expected count of %d, but %d are running",
                                      secondsWaited, flowletId, expectedInstances, numRunningFlowlets);
        LOG.error(errmsg);
        throw new TimeoutException(errmsg);
      }
      numRunningFlowlets = getNumberOfProvisionedInstances(flowletId);
    }
  }
693452
public void asyncRequestWithoutSession(AsyncRequest asyncRequest, AsyncResponseCallback asyncResponseCallback) {
        doRequest.doRequest(asyncRequest, false, asyncResponseCallback);
    }
669299
@Override
  public void recordSubProcessInstanceStart(ExecutionEntity parentExecution, ExecutionEntity subProcessInstance, FlowElement initialElement) {
    if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {

      HistoricProcessInstanceEntity historicProcessInstance = getHistoricProcessInstanceEntityManager().create(subProcessInstance); 

      // Fix for ACT-1728: startActivityId not initialized with subprocess instance
      if (historicProcessInstance.getStartActivityId() == null) {
        historicProcessInstance.setStartActivityId(initialElement.getId());
      }
      getHistoricProcessInstanceEntityManager().insert(historicProcessInstance, false);
      
      // Fire event
      ActivitiEventDispatcher activitiEventDispatcher = getEventDispatcher();
      if (activitiEventDispatcher != null && activitiEventDispatcher.isEnabled()) {
        activitiEventDispatcher.dispatchEvent(
            ActivitiEventBuilder.createEntityEvent(ActivitiEventType.HISTORIC_PROCESS_INSTANCE_CREATED, historicProcessInstance));
      }

      HistoricActivityInstanceEntity activitiyInstance = findActivityInstance(parentExecution, false, true);
      if (activitiyInstance != null) {
        activitiyInstance.setCalledProcessInstanceId(subProcessInstance.getProcessInstanceId());
      }

    }
  }
1141970
protected int createInstances(DelegateExecution execution) {
    int nrOfInstances = resolveNrOfInstances(execution);
    if (nrOfInstances < 0) {
      throw new ActivitiIllegalArgumentException("Invalid number of instances: must be non-negative integer value" + ", but was " + nrOfInstances);
    }

    execution.setMultiInstanceRoot(true);

    setLoopVariable(execution, NUMBER_OF_INSTANCES, nrOfInstances);
    setLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES, 0);
    setLoopVariable(execution, NUMBER_OF_ACTIVE_INSTANCES, nrOfInstances);

    List<DelegateExecution> concurrentExecutions = new ArrayList<DelegateExecution>();
    for (int loopCounter = 0; loopCounter < nrOfInstances; loopCounter++) {
      DelegateExecution concurrentExecution = Context.getCommandContext().getExecutionEntityManager()
          .createChildExecution((ExecutionEntity) execution);
      concurrentExecution.setCurrentFlowElement(activity);
      concurrentExecution.setActive(true);
      concurrentExecution.setScope(false);

      concurrentExecutions.add(concurrentExecution);
      logLoopDetails(concurrentExecution, "initialized", loopCounter, 0, nrOfInstances, nrOfInstances);
    }

    // Before the activities are executed, all executions MUST be created up front
    // Do not try to merge this loop with the previous one, as it will lead
    // to bugs, due to possible child execution pruning.
    for (int loopCounter = 0; loopCounter < nrOfInstances; loopCounter++) {
      DelegateExecution concurrentExecution = concurrentExecutions.get(loopCounter);
      // executions can be inactive, if instances are all automatics
      // (no-waitstate) and completionCondition has been met in the meantime
      if (concurrentExecution.isActive() && !concurrentExecution.isEnded() && concurrentExecution.getParent().isActive() && !concurrentExecution.getParent().isEnded()) {
        setLoopVariable(concurrentExecution, getCollectionElementIndexVariable(), loopCounter);
        executeOriginalBehavior(concurrentExecution, loopCounter);
      }
    }

    // See ACT-1586: ExecutionQuery returns wrong results when using multi
    // instance on a receive task The parent execution must be set to false, so it wouldn't show up in
    // the execution query when using .activityId(something). Do not we cannot nullify the
    // activityId (that would have been a better solution), as it would break boundary event behavior.
    if (!concurrentExecutions.isEmpty()) {
      ExecutionEntity executionEntity = (ExecutionEntity) execution;
      executionEntity.setActive(false);
    }

    return nrOfInstances;
  }
89186
function applyTransforms(transforms, t, callback) {
  log.debug('applying', transforms.length, 'transforms');
  for (var i = 0; i < transforms.length; i++) {
    var transform = transforms[i];
    log.debug('next transform', transform);
    if (transform.isAsync) {
      // asynchronous case
      return transform(t, function(t) {
        // this is only called when the async transform was successful,
        // otherwise t.callback has already been called with an error.
        applyTransforms(transforms.slice(i + 1), t, callback);
      });
    } else {
      // synchronous case
      var result = transform(t);
      if (!result) {
        log.debug('transform has failed or was a final transform');
        // stop processing t.callback has already been called
        return;
      }
    }
  }
  log.debug('all transformations done, starting next step');
  if (nextTickAvailable) {
    return process.nextTick(function() {
      callback(t);
    });
  }
  return callback(t);
}
18778
function leaf_to( sceneName, argsArr, deferred ) {
    
    this._transitioning = true;
    var complete = this._complete = deferred || _.Deferred(),
    args = argsArr ? argsArr : [],
    handlerComplete = _.Deferred()
      .done(_.bind(function() {
        this._transitioning = false;
        this._current = sceneName;
        complete.resolve();
      }, this))
      .fail(_.bind(function() {
        this._transitioning = false;
        complete.reject();
      }, this));

    this.handlers[sceneName].call(this._context, args, handlerComplete);

    return complete.promise();
  }
131414
@Override
    public java.util.concurrent.Future<DescribeDBSnapshotsResult> describeDBSnapshotsAsync(
            com.amazonaws.handlers.AsyncHandler<DescribeDBSnapshotsRequest, DescribeDBSnapshotsResult> asyncHandler) {

        return describeDBSnapshotsAsync(new DescribeDBSnapshotsRequest(), asyncHandler);
    }
965173
@Override
    public void registerAsynchConsumerCallback(
                                               AsynchConsumerCallback callback,
                                               int maxActiveMessages,
                                               long messageLockExpiry,
                                               int maxBatchSize,
                                               OrderingContext context)
                    throws SISessionUnavailableException, SISessionDroppedException,
                    SIErrorException,
                    SIIncorrectCallException
    {
        if (TraceComponent.isAnyTracingEnabled() && CoreSPIConsumerSession.tc.isEntryEnabled())
            SibTr.entry(CoreSPIConsumerSession.tc, "registerAsynchConsumerCallback",
                        new Object[] { this,
                                      callback,
                                      new Integer(maxActiveMessages),
                                      new Long(messageLockExpiry),
                                      new Integer(maxBatchSize),
                                      context });
        registerAsynchConsumerCallback(callback,
                                       maxActiveMessages,
                                       messageLockExpiry,
                                       maxBatchSize,
                                       null,
                                       false,
                                       context);

        if (TraceComponent.isAnyTracingEnabled() && CoreSPIConsumerSession.tc.isEntryEnabled())
            SibTr.exit(CoreSPIConsumerSession.tc, "registerAsynchConsumerCallback");
    }
937210
@Override
    public java.util.concurrent.Future<DescribeFileSystemsResult> describeFileSystemsAsync(
            com.amazonaws.handlers.AsyncHandler<DescribeFileSystemsRequest, DescribeFileSystemsResult> asyncHandler) {

        return describeFileSystemsAsync(new DescribeFileSystemsRequest(), asyncHandler);
    }
1339902
public void executeActivitiesConcurrent(List<PvmActivity> activityStack, PvmActivity targetActivity,
                                          PvmTransition targetTransition, Map<String, Object> variables, Map<String, Object> localVariables,
                                          boolean skipCustomListeners, boolean skipIoMappings) {


    ScopeImpl flowScope = null;
    if (!activityStack.isEmpty()) {
      flowScope = activityStack.get(0).getFlowScope();
    } else if (targetActivity != null) {
      flowScope = targetActivity.getFlowScope();
    } else if (targetTransition != null) {
      flowScope = targetTransition.getSource().getFlowScope();
    }

    PvmExecutionImpl propagatingExecution = null;
    if (flowScope.getActivityBehavior() instanceof ModificationObserverBehavior) {
      ModificationObserverBehavior flowScopeBehavior = (ModificationObserverBehavior) flowScope.getActivityBehavior();
      propagatingExecution = (PvmExecutionImpl) flowScopeBehavior.createInnerInstance(this);
    } else {
      propagatingExecution = createConcurrentExecution();
    }

    propagatingExecution.executeActivities(activityStack, targetActivity, targetTransition, variables, localVariables,
      skipCustomListeners, skipIoMappings);
  }