/*
Internal method called when a stoppable asynchronous session is stopped, the session is put into stopped state and the registered
application consumerSessionStopped() method is invoked to inform the application that the session has been stopped.
327638
public void stoppableConsumerSessionStopped () {
     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "stoppableConsumerSessionStopped");

     try {
       stopInternal(false); // No need to notify our peer as the stop came from our peer
     } catch (Exception e) {
       FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.CONSUMERSESSIONPROXY_SESSION_STOPPED_03, this);
     }

     final AsynchConsumerCallback asynchConsumerCallback = proxyQueue.getAsynchConsumerCallback();
     if (asynchConsumerCallback instanceof StoppableAsynchConsumerCallback) {
       final StoppableAsynchConsumerCallback stoppableAsynchConsumerCallback = (StoppableAsynchConsumerCallback)asynchConsumerCallback;
       // Protect ourselves from the application as far as possible then call the application
       try {
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "** Calling application StoppableAsynchConsumerCallback");
         stoppableAsynchConsumerCallback.consumerSessionStopped();
       } catch (Throwable e) {
         FFDCFilter.processException(e, CLASS_NAME + ".stoppableConsumerSessionStopped", CommsConstants.CONSUMERSESSIONPROXY_SESSION_STOPPED_01, this);
       }
     } else {
       if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "asynchConsumerCallback not an instance of StoppableAsynchConsumerCallback is an instance of "+ asynchConsumerCallback.getClass().getName());
       SIErrorException e = new SIErrorException(nls.getFormattedMessage("WRONG_CLASS_CWSICO8022", new Object[] {asynchConsumerCallback.getClass().getName()}, null));
       FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.CONSUMERSESSIONPROXY_SESSION_STOPPED_02, this);
       SibTr.error(tc, "WRONG_CLASS_CWSICO8022", e);
       throw e;
     }

     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "stoppableConsumerSessionStopped");
   }
654828
public static void pause() {
        SiftImpl localInstance = instance;
        if (localInstance != null) {
            localInstance.save();
        }

        AppStateCollector localAppStateCollector = appStateCollector;
        if (localAppStateCollector != null) {
            localAppStateCollector.disconnectLocationServices();
        }
    }
773987
@Override
    public void registerStoppableAsynchConsumerCallback(
                                                        StoppableAsynchConsumerCallback callback,
                                                        int maxActiveMessages,
                                                        long messageLockExpiry,
                                                        int maxBatchSize,
                                                        Reliability unrecoverableReliability,
                                                        boolean inLine,
                                                        OrderingContext extendedMessageOrderingContext,
                                                        int maxSequentialFailures,
                                                        long hiddenMessageDelay)
                    throws SISessionUnavailableException, SISessionDroppedException, SIIncorrectCallException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "registerStoppableAsynchConsumerCallback",
                        new Object[] { callback,
                                      maxActiveMessages,
                                      messageLockExpiry,
                                      maxBatchSize,
                                      unrecoverableReliability,
                                      inLine,
                                      extendedMessageOrderingContext,
                                      maxSequentialFailures,
                                      hiddenMessageDelay });

        //register the AsynchConsumer with the LCP
        _localConsumerPoint.registerStoppableAsynchConsumer(
                                                            callback,
                                                            maxActiveMessages,
                                                            messageLockExpiry,
                                                            maxBatchSize,
                                                            unrecoverableReliability,
                                                            inLine,
                                                            (OrderingContextImpl) extendedMessageOrderingContext,
                                                            null, // No callback busy lock is used for non-mediation consumers.
                                                            maxSequentialFailures,
                                                            hiddenMessageDelay);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "registerStoppableAsynchConsumerCallback");
    }
1122777
@EventThread
    protected void clientSessionWillEnd (final PresentsSession session)
    {
        // notify the observers that the session is ended
        _dclobservers.apply(new ObserverList.ObserverOp<DetailedClientObserver>() {
            public boolean apply (DetailedClientObserver observer) {
                observer.clientSessionWillEnd(session);
                return true;
            }
        });
    }
1183210
@Override
    public void checkNotClosed() throws SISessionUnavailableException
    {
        if ((_closed) || (_closing && !(_asynchConsumer.isAsynchConsumerRunning())))
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.entry(tc, "checkNotClosed");

            //check the close conditions to produce a well-formed error message
            if (_consumerKey.isClosedDueToDelete())
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    SibTr.exit(tc, "checkNotClosed", "SISessionDroppedException - deleted");
                throw new SISessionDroppedException(
                                nls.getFormattedMessage(
                                                        "DESTINATION_DELETED_ERROR_CWSIP00221",
                                                        new Object[] {
                                                                      _consumerDispatcher.getDestination().getName(),
                                                                      _consumerDispatcher.getMessageProcessor().getMessagingEngineName() },
                                                        null));
            }
            if (_consumerKey.isClosedDueToReceiveExclusive())
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    SibTr.exit(tc, "checkNotClosed", "SISessionDroppedException - receive Exclusive");
                throw new SISessionDroppedException(
                                nls.getFormattedMessage(
                                                        "DESTINATION_EXCLUSIVE_ERROR_CWSIP00222",
                                                        new Object[] {
                                                                      _consumerDispatcher.getDestination().getName(),
                                                                      _consumerDispatcher.getMessageProcessor().getMessagingEngineName() },
                                                        null));
            }
            if (_consumerKey.isClosedDueToLocalizationUnreachable())
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    SibTr.exit(tc, "checkNotClosed", "SISessionDroppedException - localisation unreachable");
                throw new SISessionDroppedException(
                                nls.getFormattedMessage(
                                                        "DESTINATION_UNREACHABLE_ERROR_CWSIP00223",
                                                        new Object[] {
                                                                      _consumerDispatcher.getDestination().getName(),
                                                                      _consumerDispatcher.getMessageProcessor().getMessagingEngineName() },
                                                        null));
            }

            SISessionUnavailableException e =
                            new SISessionUnavailableException(
                                            nls.getFormattedMessage(
                                                                    "CONSUMER_CLOSED_ERROR_CWSIP0177",
                                                                    new Object[] { _consumerDispatcher.getDestination().getName(),
                                                                                  _messageProcessor.getMessagingEngineName() },
                                                                    null));

            SibTr.exception(tc, e);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "checkNotClosed", "consumer closed");

            throw e;
        }
    }
752948
public void stopping() {
        boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isDebugEnabled())
            Tr.debug(tc, "stopping");

        J2EEName j2eeName = ivApplicationMetaData == null ? null : ivApplicationMetaData.getJ2EEName();
        beginStopping(true, j2eeName, ivModules); // F743-26072
    }
1278857
@Override
    public void stop(int mode) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "stop, mode ", mode);

        // Now force state to STOPPING - regardless of how we got here
        setState(STATE_STOPPING);

        // Reset MP Admin
        _localizer.clearMPAdmin();
        _mpAdmin = null;
        _messageProcessor.stop(mode);
        _messageStore.stop(mode);

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Messaging Engine " + _name + " finished stop phases");

        setState(STATE_STOPPED);
        SibTr.debug(tc, "Messaging Engine stopped");
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Messaging Engine " + _name + " has been stopped before dynamic config cycle completed.");

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.debug(tc, "stop");
    }
23570
public void sessionDidActivate(SipApplicationSessionEvent event) {
		logger.info("Following sip application session just activated " + event.getApplicationSession().getId() + " cause " + ((SipApplicationSessionActivationEvent)event).getCause());
		if(((SipApplicationSessionActivationEvent)event).getCause() == SessionActivationNotificationCause.FAILOVER) {
			event.getApplicationSession().setAttribute(SIP_APPLICATION_SESSION_ACTIVATED, "true" );
		}

	}
710919
@Override
   public final void stop() {
      // Trying to stop() from FAILED is valid, but may not work
      boolean failed;

      synchronized (this) {
         try {
            while (state == ComponentStatus.STOPPING) {
               wait();
            }
            if (!state.stopAllowed()) {
               getLog().debugf("Ignoring call to stop() as current state is %s", state);
               return;
            }

            failed = state == ComponentStatus.FAILED;
            state = ComponentStatus.STOPPING;
         } catch (InterruptedException e) {
            throw new CacheException("Interrupted waiting for the component registry to stop");
         }
      }

      preStop();

      try {
         internalStop();

         postStop();
      } catch (Throwable t) {
         if (failed) {
            getLog().failedToCallStopAfterFailure(t);
         } else {
            handleLifecycleTransitionFailure(t);
         }
      } finally {
         synchronized (this) {
            state = ComponentStatus.TERMINATED;
         }
      }
   }
40177
@EventThread
    protected void finishResumeSession ()
    {
        // if we have no client object for whatever reason; we're hosed, shut ourselves down
        if (_clobj == null) {
            log.info("Missing client object for resuming session " + this + ".");
            endSession();
            return;
        }

        // make extra sure we have no lingering subscriptions
        clearSubscrips(false);

        // Update our client secret with the new auth request
        _clobj.getLocal(ClientLocal.class).secret = getSecret();

        // let derived classes do any session resuming
        sessionWillResume();

        // send off a bootstrap notification immediately as we've already got our client object
        sendBootstrap();

        // resend the throttle update if non-default
        if (_messagesPerSec != Client.DEFAULT_MSGS_PER_SECOND) {
            sendThrottleUpdate();
        }

        log.info("Session resumed " + this + ".");
    }
852521
public void terminateSession(final SipSession session,
    							 final int calleeResponseCode, final String calleeResponseText,
    							 final int callerResponseCode, final String callerResponseText)
    							 throws IllegalStateException, IOException {
    	if(null == finalBranchForSubsequentRequests) {
			throw new IllegalStateException("Proxy has not yet been established. Before final response use cancel.");
    	}
    	if (!storeTerminationInfo || terminationInfo == null) {
    		logger.error("storeTerminationInfo = " + storeTerminationInfo);
    		if (terminationInfo == null) {
    			logger.error("terminationInfo = null");
    		}
    		throw new IllegalStateException("No termination information stored.Call storeTerminationInformation before final response arrives.");
    	}
    	terminationInfo.terminate(session, calleeResponseCode, calleeResponseText, callerResponseCode, callerResponseText);
    }
771920
public void checkInactiveSession(Session session) {
        if (session == null) {
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug("Checking for idle " +  session.getId());
        }
        try (Lock ignored = session.lock()) {
            if (getEvictionPolicy() > 0 && session.isIdleLongerThan(getEvictionPolicy()) &&
                    session.isValid() && session.isResident() && session.getRequests() <= 0) {
                // Be careful with saveOnInactiveEviction - you may be able to re-animate a session that was
                // being managed on another node and has expired.
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Evicting idle session " + session.getId());
                    }

                    // save before evicting
                    if (isSaveOnInactiveEviction() && sessionDataStore != null) {
                        if (sessionDataStore.isPassivating()) {
                            sessionHandler.willPassivate(session);
                        }
                        sessionDataStore.store(session.getId(), session.getSessionData());
                    }

                    doDelete(session.getId()); // detach from this cache
                    session.setResident(false);
                } catch (Exception e) {
                    log.warn("Passivation of idle session" + session.getId() + " failed", e);
                    session.updateInactivityTimer();
                }
            }
        }
    }
1301163
@Override
  public void stopSession() {
    serverInstrumentation.finishAllActivities();
    this.activeWindowType = WindowType.NATIVE_APP.name();
    this.session = null;
    nativeSearchScope = null;
    selendroidNativeDriver = null;
    selendroidWebDriver = null;
    webviewSearchScope = null;
  }
877223
private static SessionEventsState getSessionEventsState(Context context, AccessTokenAppIdPair accessTokenAppId) {
        // Do this work outside of the lock to prevent deadlocks in implementation of
        //  AdvertisingIdClient.getAdvertisingIdInfo, because that implementation blocks waiting on the main thread,
        //  which may also grab this staticLock.
        SessionEventsState state = stateMap.get(accessTokenAppId);
        AttributionIdentifiers attributionIdentifiers = null;
        if (state == null) {
            // Retrieve attributionId, but we will only send it if attribution is supported for the app.
            attributionIdentifiers = AttributionIdentifiers.getAttributionIdentifiers(context);
        }

        synchronized (staticLock) {
            // Check state again while we're locked.
            state = stateMap.get(accessTokenAppId);
            if (state == null) {
                state = new SessionEventsState(attributionIdentifiers, context.getPackageName(), hashedDeviceAndAppId);
                stateMap.put(accessTokenAppId, state);
            }
            return state;
        }
    }
1052511
void checkNotClosed() throws SISessionUnavailableException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "checkNotClosed");

        try
        {
            synchronized (_localConsumerPoint)
            {
                _localConsumerPoint.checkNotClosed();
            }
        } catch (SISessionUnavailableException e)
        {
            // No FFDC code needed
            SibTr.exception(tc, e);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "checkNotClosed", e);

            throw e;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "checkNotClosed");
    }
471787
private void onStateChange(Session.State state) {
    switch (state) {
      // When the session is opened, transition the state to CONNECTED.
      case OPEN:
        setState(State.CONNECTED);
        break;
      // When the session becomes unstable, transition the state to SUSPENDED.
      case UNSTABLE:
        setState(State.SUSPENDED);
        break;
      case STALE:
        setState(State.SUSPENDED);
        this.close();
        break;
      // When the session is expired, transition the state to SUSPENDED if necessary. The recovery strategy
      // must determine whether to attempt to recover the client.
      case EXPIRED:
        setState(State.SUSPENDED);
        recoveryStrategy.recover(this);
        break;
      case CLOSED:
        setState(State.CLOSED);
        break;
      default:
        break;
    }
  }
538348
def stop(self, signum=None, _unused=None):
        
        LOGGER.debug('Stop called in state: %s', self.state_description)
        if self.is_stopped:
            LOGGER.warning('Stop requested but consumer is already stopped')
            return
        elif self.is_shutting_down:
            LOGGER.warning('Stop requested, consumer is already shutting down')
            return
        elif self.is_waiting_to_shutdown:
            LOGGER.warning('Stop requested but already waiting to shut down')
            return

        # Stop consuming and close AMQP connections
        self.shutdown_connections()

        # Wait until the consumer has finished processing to shutdown
        if self.is_processing:
            LOGGER.info('Waiting for consumer to finish processing')
            self.set_state(self.STATE_STOP_REQUESTED)
            if signum == signal.SIGTERM:
                signal.siginterrupt(signal.SIGTERM, False)
            return