Send an event to the channel framework that there are no more active
connections on this quiesced channel instance. This will allow an early
final chain stop instead of waiting the full quiesce timeout length.
191627
private void signalNoConnections() {
        EventEngine events = _commsServerFacade.getEventEngine();
        if (null == events) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                SibTr.event(tc, "Unable to send event, missing service");
            }
            return;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            SibTr.event(tc, "No active connections, sending stop chain event");
        }
        Event event = events.createEvent(ChannelFramework.EVENT_STOPCHAIN);
        event.setProperty(ChannelFramework.EVENT_CHANNELNAME, _cfw.getChannel(_jfapName).getExternalName());
        events.postEvent(event);
    }
33319
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
		KNXLinkClosedException
	{
		doSend(adjustMsgType(msg), waitForCon);
	}
932681
private void writeEvent(final ChannelHandlerContext ctx, final Object message) {
        if (isFinishedSent)
            return;
        
        if (message instanceof FinishedMessage)
            isFinishedSent = true;

        Channels.write(ctx, Channels.future(null), message);
    }
626397
def send_events(self, events):
        
        for event in events:
            self.queue.events.add().MergeFrom(event)
        return None
1163917
def timeout(self, timeout):
        '''
        '''
        if self._timeout is None:
            self.event('connection_made').bind(self._add_timeout)
            self.event('connection_lost').bind(self._cancel_timeout)
        self._timeout = timeout or 0
        self._add_timeout(None)
631486
private void socketClosedHandler() {
        // If the book-keeping has already been completed earlier, then
        // we should just bail.
        if (getReadyState() == ReadyState.CLOSED) {
            return;
        }
        
        // TODO: Determine whether channels need to be cleaned up
        if (this.channels.size() != 0) {
            // Iterate over the channels and close them.
            for (int i = 1; i <= this.channels.size(); i++) { // 1-based
                AmqpChannel channel = this.channels.get(i);
                AmqpFrame   f = new AmqpFrame();
                
                // Close the channel and ensure that the CLOSE event is
                // fired on the registered ChannelListener objects.
                f.setMethodName("closeChannel");
                f.setChannelId((short) i);
                channel.channelClosedHandler(this, "", f, "closeChannel");
            }
        }
        
        // Mark the readyState as CLOSED.
        readyState = ReadyState.CLOSED;

        // Fire the CLOSE event on the ConnectionListener(s) registered on
        // the AmqpClient object.
        fireOnClosed(new ConnectionEvent(this, Kind.CLOSE));
    }
814368
@Override
    public void serverStopping() {
        // If the system is configured to quiesce connections..
        long timeout = chfw.getDefaultChainQuiesceTimeout();
        if (timeout > 0) {
            ChainData[] runningChains = chfw.getRunningChains();

            // build list of chain names to pass to stop, use ChannelUtils.stopChains so as to not return until the
            // channels are inactive or the quiesce timeout has hit.
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < runningChains.length; i++) {
                if (FlowType.INBOUND.equals(runningChains[i].getType())) {
                    names.add(runningChains[i].getName());
                }
            }

            ChannelUtils.stopChains(names, -1, null);

        }
    }
892469
protected void queueSendToWebsocketNB(String msg) {
        if (this.sendProcess.getPendingStepCount() < MAX_MSG_BACKLOG) {
            MySendStep sendStep = new MySendStep(msg);
            this.sendProcess.addStep(sendStep);
        } else {
            log.info("websocket backlog is full; aborting connection: sessionId={}", this.socketSessionId);

            this.safeClose();
        }
    }
791516
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
		KNXLinkClosedException
	{
		doSend(createEMI(msg), waitForCon, msg.getDestination());
	}
881716
private void sendPingFrame(ChannelHandlerContext ctx, SendPingCommand msg,
      ChannelPromise promise) {
    // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown
    // but before termination. After termination, messages will no longer arrive because the
    // pipeline clears all handlers on channel close.

    PingCallback callback = msg.callback();
    Executor executor = msg.executor();
    // we only allow one outstanding ping at a time, so just add the callback to
    // any outstanding operation
    if (ping != null) {
      promise.setSuccess();
      ping.addCallback(callback, executor);
      return;
    }

    // Use a new promise to prevent calling the callback twice on write failure: here and in
    // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if
    // ping != null above.
    promise.setSuccess();
    promise = ctx().newPromise();
    // set outstanding operation
    long data = USER_PING_PAYLOAD;
    Stopwatch stopwatch = stopwatchFactory.get();
    stopwatch.start();
    ping = new Http2Ping(data, stopwatch);
    ping.addCallback(callback, executor);
    // and then write the ping
    encoder().writePing(ctx, false, USER_PING_PAYLOAD, promise);
    ctx.flush();
    final Http2Ping finalPing = ping;
    promise.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
          transportTracer.reportKeepAliveSent();
        } else {
          Throwable cause = future.cause();
          if (cause instanceof ClosedChannelException) {
            cause = lifecycleManager.getShutdownThrowable();
            if (cause == null) {
              cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.")
                  .withCause(future.cause()).asException();
            }
          }
          finalPing.failed(cause);
          if (ping == finalPing) {
            ping = null;
          }
        }
      }
    });
  }
380885
def send(self, data, opcode=ABNF.OPCODE_TEXT):
        

        if not self.sock or self.sock.send(data, opcode) == 0:
            raise WebSocketConnectionClosedException(
                "Connection is already closed.")
77541
@FFDCIgnore(InvalidRuntimeStateException.class)
    public synchronized void stop() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(this, tc, "stop chain " + this);
        }

        // When the chain is being stopped, remove the previously
        // registered EndPoint created in update
        endpointMgr.removeEndPoint(endpointName);

        // We don't have to check enabled/disabled here: chains are always allowed to stop.
        if (currentConfig == null || chainState.get() <= ChainState.QUIESCED.val)
            return;

        // Quiesce and then stop the chain. The CFW internally uses a StopTimer for
        // the quiesce/stop operation-- the listener method will be called when the chain
        // has stopped. So to see what happens next, visit chainStopped
        try {
            ChainData cd = cfw.getChain(chainName);
            if (cd != null) {
                cfw.stopChain(cd, cfw.getDefaultChainQuiesceTimeout());
                stopWait.waitForStop(cfw.getDefaultChainQuiesceTimeout(), this); // BLOCK
                try {
                    cfw.destroyChain(cd);
                    cfw.removeChain(cd);
                } catch (InvalidRuntimeStateException e) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "Error destroying or removing chain " + chainName, this, e);
                    }
                }
            }
        } catch (ChannelException e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "Error stopping chain " + chainName, this, e);
            }
        } catch (ChainException e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "Error stopping chain " + chainName, this, e);
            }
        }
    }
956806
public void doReconnect() {
        if (channelRef.get() != null) {
            // if (channelRef.get().isWritable()) {
            // LOG.info("already exist a writable channel, give up reconnect, {}",
            // channelRef.get());
            // return;
            // }
            return;
        }

        if (isClosed()) {
            return;
        }

        if (isConnecting.getAndSet(true)) {
            LOG.info("Connect twice {}", name());
            return;
        }

        long sleepMs = getSleepTimeMs();
        LOG.info("Reconnect ... [{}], {}, sleep {}ms", retries.get(), name, sleepMs);
        ChannelFuture future = bootstrap.connect(remoteAddr);
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                isConnecting.set(false);
                Channel channel = future.getChannel();
                if (future.isSuccess()) {
                    // do something else
                    LOG.info("Connection established, channel = :{}", channel);
                    setChannel(channel);
                    // handleResponse();
                    BATCH_THRESHOLD_WARN = ConfigExtension.getNettyBufferThresholdSize(stormConf);

                    // Check if any pending message
                    /*synchronized (writeLock) {
                        if (channel != null && messageBuffer.size() > 0) {
                            MessageBatch messageBatch = messageBuffer.drain();
                            flushRequest(channel, messageBatch);
                        } else {
                            LOG.warn("Failed to flush pending message after reconnecting, channel={}, messageBuffer.size={}",
                                    channel, messageBuffer.size());
                        }
                    }*/
                } else {
                    if (!isClosed()) {
                        LOG.info("Failed to reconnect ... [{}], {}, channel = {}, cause = {}",
                                retries.get(), name, channel, future.getCause());
                        reconnect();
                    }
                }
            }
        });
        JStormUtils.sleepMs(sleepMs);
    }
840256
private void fireConnectionClosed() {
        assertUnlocked();

        BOSHClientConnEvent event = null;
        for (BOSHClientConnListener listener : connListeners) {
            if (event == null) {
                event = BOSHClientConnEvent.createConnectionClosedEvent(this);
            }
            try {
                listener.connectionEvent(event);
            } catch (Exception ex) {
                LOG.log(Level.WARNING, UNHANDLED, ex);
            }
        }
    }
812093
def on_timeout(limit, handler=handler_func, hint=None):
    
    def notify_handler(signum, frame):
        handler("'%s' is not finished in %d second(s)." % (hint, limit))

    def __decorator(function):
        def __wrapper(*args, **kwargs):
            import signal
            signal.signal(signal.SIGALRM, notify_handler)
            signal.alarm(limit)
            result = function(*args, **kwargs)
            signal.alarm(0)
            return result
        return wraps(function)(__wrapper)
    return __decorator
279795
def wait(self):
        
        if self.error:
            raise self.error
        if not self.running:
            raise ValueError("Unable to send until client has been started.")
        try:
            self._handler.wait()
        except (errors.TokenExpired, errors.AuthenticationException):
            log.info("Sender disconnected due to token error. Attempting reconnect.")
            self.reconnect()
        except (errors.LinkDetach, errors.ConnectionClose) as shutdown:
            if shutdown.action.retry and self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except errors.MessageHandlerError as shutdown:
            if self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except Exception as e:
            log.info("Unexpected error occurred (%r).", e)
            raise EventHubError("Send failed: {}".format(e))
458915
public synchronized void sendRetry(long retry, EventCallback callback) {

        if (open == 0 || shutdown) {
            if (callback != null) {
                callback.failed(this, null, null, null, new ClosedChannelException());
            }
            return;
        }
        queue.add(new SSEData(retry, callback));
        sink.getIoThread().execute(new Runnable() {
            @Override
            public void run() {
                synchronized (ServerSentEventConnection.this) {
                    if (pooled == null) {
                        fillBuffer();
                        writeListener.handleEvent(sink);
                    }
                }
            }
        });
    }