Terminates all subscriptions to a given heap from a single session
976967
private void terminateSubscriptions(IoSession session, String heapUri, Subscription.CloseReason reason) {
        terminateSubscriptions(session, heapStates.get(heapUri), heapUri, reason);
    }
1007261
@Override
    protected void onSessionClose(long sessionId, Map<Long, Object> responses) {
        SessionSemaphoreState state = sessionStates.get(sessionId);
        if (state != null) {
            // remove the session after release() because release() checks existence of the session
            if (state.acquiredPermits > 0) {
                SemaphoreEndpoint endpoint = new SemaphoreEndpoint(sessionId, 0);
                ReleaseResult result = release(endpoint, newUnsecureUUID(), state.acquiredPermits);
                assert result.cancelled.isEmpty();
                for (AcquireInvocationKey key : result.acquired) {
                    responses.put(key.commitIndex(), Boolean.TRUE);
                }
            }

            sessionStates.remove(sessionId);
        }
    }
1199078
@Override
	public void terminateAllConnections() {
		this.terminationLock.lock();
		try {
			for (int i = 0; i < this.pool.thriftServerCount; i++) {
				this.pool.partitions.get(i).setUnableToCreateMoreTransactions(false);
				List<ThriftConnectionHandle<T>> clist = new LinkedList<>();
				this.pool.partitions.get(i).getFreeConnections().drainTo(clist);
				for (ThriftConnectionHandle<T> c : clist) {
					this.pool.destroyConnection(c);
				}

			}
		} finally {
			this.terminationLock.unlock();
		}
	}
1033523
public void removeAll() {
    LOGGER.debug("Removing {} reverse connections from subscription manager", reverse.size());
    Iterator<HomekitClientConnection> i = reverse.keySet().iterator();
    while (i.hasNext()) {
      HomekitClientConnection connection = i.next();
      LOGGER.debug("Removing connection {}", connection.hashCode());
      removeConnection(connection);
    }
    LOGGER.debug("Subscription sizes are {} and {}", reverse.size(), subscriptions.size());
  }
990026
def unsubscribe(self, event):
        """"""
        # TODO: Automatic Unsubscription
        uuids = event.data

        if not isinstance(uuids, list):
            uuids = [uuids]

        result = []

        for uuid in uuids:
            if uuid in self.subscriptions:
                self.subscriptions[uuid].pop(event.client.uuid)

                if len(self.subscriptions[uuid]) == 0:
                    del (self.subscriptions[uuid])

                result.append(uuid)

        result = {
            'component': 'hfos.events.objectmanager',
            'action': 'unsubscribe',
            'data': {
                'uuid': result, 'success': True
            }
        }

        self._respond(None, result, event)
995724
public void destroySession() {
    	JsonObject session = get("session");
        if (session == null) {
            return;
        }

        String sessionId = session.getString("id");
        // remove from the context
        put("session", null);

        if (sessionId == null) {
            return;
        }

        store.destroy(sessionId, new Handler<Object>() {
            @Override
            public void handle(Object error) {
                if (error != null) {
                    // TODO: better handling of errors
                    System.err.println(error);
                }
            }
        });
    }
29552
function _drainOperationQueue() {

      //
      // Handle our active subscriptions first, using a cloned
      // copy of the array.  We shift them out one-by-one until
      // all have been processed, leaving the official record
      // of active subscriptions untouched.
      // 
      var subscription = clonedSubscriptions.shift();

      if (!isUndefined(subscription)) {
         //
         // If the 3rd argument (namely callback) is not present, we will
         // use two-argument form to call mqtt.Client#subscribe(), which
         // supports both subscribe(topics, options) and subscribe(topics, callback).
         //
         if (!isUndefined(subscription.callback)) {
            device.subscribe(subscription.topic, subscription.options, subscription.callback);
         } else {
            device.subscribe(subscription.topic, subscription.options);
         }
      } else {
         //
         // If no remaining active subscriptions to process,
         // then handle subscription requests queued while offline.
         //
         var req = offlineSubscriptionQueue.shift();

         if (!isUndefined(req)) {
            _updateSubscriptionCache(req.type, req.topics, req.options);
            if (req.type === 'subscribe') {
               if (!isUndefined(req.callback)) {
                  device.subscribe(req.topics, req.options, req.callback);
               } else {
                  device.subscribe(req.topics, req.options);
               }
            } else if (req.type === 'unsubscribe') {
               device.unsubscribe(req.topics, req.callback);
            }
         } else {
            //
            // If no active or queued subscriptions remaining to process,
            // then handle queued publish operations.
            //
            var offlinePublishMessage = offlinePublishQueue.shift();

            if (!isUndefined(offlinePublishMessage)) {
               device.publish(offlinePublishMessage.topic,
                  offlinePublishMessage.message,
                  offlinePublishMessage.options,
                  offlinePublishMessage.callback);
            }
            if (offlinePublishQueue.length === 0) {
               //
               // The subscription and offlinePublishQueue queues are fully drained,
               // cancel the draining timer.
               //
               clearInterval(drainingTimer);
               drainingTimer = null;
            }
         }
      }
   }
683106
def _del_all_subscriptions(self, session):
        
        filter_queue = deque()
        for topic in self._subscriptions:
            if self._del_subscription(topic, session):
                filter_queue.append(topic)
        for topic in filter_queue:
            if not self._subscriptions[topic]:
                del self._subscriptions[topic]
875617
function(client, subscriptions, channel, callback, done_callback) {
    if (subscriptions[channel]===undefined)
        return;
    subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
    if (subscriptions[channel].length===0) {
        delete subscriptions[channel];
        client.unsubscribe(channel, function() {
            // If there is a done_callback defined, execute it
            if (done_callback!==undefined) done_callback();
        });
    }
}
83326
def detach_session(self):
        """"""
        if self._session is not None:
            self._session.unsubscribe(self)
            self._session = None
488243
public void terminateSubscription(IoSession session, String heapUri, String subscriptionId, Subscription.CloseReason reason) {
        Lock heapUpdateLock = null;
        try {
            HeapState state = heapStates.get(heapUri);
            if (state != null) {
                heapUpdateLock = state.getUpdateLock();
                heapUpdateLock.lock();
            }
            subTermLock.lock();

            if (state != null) {
                if (!state.isTerminated()) {
                    state.terminateSubscription(session, subscriptionId, reason);
                    // notify client
                    if (reason == REQUESTED_BY_PUBLISHER || reason == Subscription.CloseReason.REQUESTED_BY_PUBLISHER_ADMINISTRATOR) {
                        try {
                            nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Notifying client that publisher has terminated subscription %s", subscriptionId);
                            NioUtils.writeEventMessageToSession(session, new TerminateSubscription(state.getHeapId(), subscriptionId, reason.name()), objectIOFactory);
                        } catch (Exception e) {
                            // if we can't tell them about it then something more serious has just happened.
                            // the client will likely find out anyway since this will likely mean a dead session
                            // we'll just log some info to the log to aid any debugging. We won't change the closure reason.
                            LOGGER.info("Error occurred whilst trying to inform client of subscription termination", e);
                            nioLogger.log(NioLogger.LoggingLevel.SESSION, session, "Error occurred whilst trying to inform client of subscription termination, closing session");
                            // we'll request a closure of the session too to make sure everything gets cleaned up, although chances are it's already closed
                            session.close();
                        }
                    }

                    if (state.hasSubscriptions()) {
                        terminateSubscriptions(heapUri, reason);
                    } else if (state.getSubscriptions(session).isEmpty()) {
                        terminateSubscriptions(session, heapUri, reason);
                    }
                }
            }

            Multiset<String> heapsForSession = heapsByClient.get(session);
            if (heapsForSession != null) {
                heapsForSession.remove(heapUri);
                if (heapsForSession.isEmpty()) {
                    terminateSubscriptions(session, reason);
                }
            }
        } finally {
            subTermLock.unlock();
            if (heapUpdateLock != null) {
                heapUpdateLock.unlock();
            }
        }
    }
170957
private void deletePubsubSubscription(String subscription) throws IOException {
    if (pubsubClient == null) {
      pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build();
    }
    if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) {
      pubsubClient.projects().subscriptions().delete(subscription).execute();
    }
  }
466969
@SuppressWarnings({ "rawtypes", "unchecked" })
    private void cleanupSessions(List<String> storeNamesToCleanUp) {

        logger.info("Performing cleanup");
        for(String store: storeNamesToCleanUp) {

            for(Node node: nodesToStream) {
                try {
                    SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store,
                                                                                        node.getId()));
                    close(sands.getSocket());
                    SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,
                                                                                            node.getId()));
                    streamingSocketPool.checkin(destination, sands);
                } catch(Exception ioE) {
                    logger.error(ioE);
                }
            }

        }

        cleanedUp = true;

    }
1017669
void terminate( boolean removeFromActiveSession ) {
        if (!isLive()) {
            return;
        }

        isLive = false;

        JcrObservationManager jcrObservationManager = observationManager();
        if (jcrObservationManager != null) {
            jcrObservationManager.removeAllEventListeners();
        }

        cleanLocks();
        if (removeFromActiveSession) this.repository.runningState().removeSession(this);
        this.context.getSecurityContext().logout();
    }
891569
def purge(self, jid, node):
        

        iq = aioxmpp.stanza.IQ(
            type_=aioxmpp.structs.IQType.SET,
            to=jid,
            payload=pubsub_xso.OwnerRequest(
                pubsub_xso.OwnerPurge(
                    node
                )
            )
        )

        yield from self.client.send(iq)
56188
private void stopWriterAndClearMasterServerList() {
		for (Server server : this.masterServersList) {
			for (OutputWriter writer : server.getOutputWriters()) {
				try {
					writer.close();
				} catch (LifecycleException ex) {
					log.error("Eror stopping writer: {}", writer);
				}
			}
			for (Query query : server.getQueries()) {
				for (OutputWriter writer : query.getOutputWriterInstances()) {
					try {
						writer.close();
						log.debug("Stopped writer: {} for query: {}", writer, query);
					} catch (LifecycleException ex) {
						log.error("Error stopping writer: {} for query: {}", writer, query, ex);
					}
				}
			}
		}
		this.masterServersList = ImmutableList.of();
	}
367848
def stop_subscribe(self):
        
        asyncio.gather(*asyncio.Task.all_tasks()).cancel()
        self.event_loop.stop()
        self.event_loop.close()