When a new channel comes up associated it with the peer. Be warned a peer
can have multiple calls associated with it.

@param b
@throws Exception
343547
public void handleEvent(final NewChannelEvent b)
    {
        // Very occasionally we get a null channel which we can't do anything
        // with so just throw the event away.
        // If we get a Console/dsp channel name it means that someone has
        // dialled from the asterisk
        // console. We just ignore these.
        if ((b.getChannel() == null) || (b.getChannel().isConsole()))
        {
            return;
        }

        if (this.isConnectedToSelf(b.getChannel()))
        {
            CallTracker call = this.registerChannel(b.getChannel());
            if (call != null)
            {
                call.setState(b.getChannelState());
                this.evaluateState();
            }
        }
    }
396762
@Override
    public Association addServerAssociation(String peerAddress, int peerPort, String serverName, String assocName)
            throws Exception {
        return addServerAssociation(peerAddress, peerPort, serverName, assocName, IpChannelType.SCTP);
    }
816657
public void connect() throws Exception {
        if (connection != null && !connection.isConnected()) {
            connection.connect();
            transaction = connection.getModbusTransport().createTransaction();
            setTransaction(transaction);
        }
    }
281242
@Override
    public void notifyOfConnection(
            int hostId,
            SocketChannel socket,
            SSLEngine sslEngine,
            InetSocketAddress listeningAddress) throws Exception
    {
        networkLog.info("Host " + getHostId() + " receives a new connection from host " + hostId);
        prepSocketChannel(socket);
        // Auxiliary connection never time out
        ForeignHost fhost = new ForeignHost(this, hostId, socket, Integer.MAX_VALUE,
                listeningAddress,
                createPicoNetwork(sslEngine, socket, true));
        putForeignHost(hostId, fhost);
        fhost.enableRead(VERBOTEN_THREADS);
        // Do all peers have enough secondary connections?
        for (int hId : m_peers) {
            if (m_foreignHosts.get(hId).size() != (m_secondaryConnections + 1)) {
                return;
            }
        }
        // Now it's time to use secondary pico network, see comments in presend() to know why we can't
        // do this earlier.
        m_hasAllSecondaryConnectionCreated = true;
}
768205
@Override
    public void start() throws ChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "start");
        }
        if (this.stopFlag) {
            // only start once
            this.stopFlag = false;
            if (this.config.isInbound()) {
                // Socket is already open, just need to start accepting connections
                try {
                    // PK60924 - check for a restart path requiring the re-init
                    if (null == this.endPoint.getServerSocket()) {
                        initializePort();
                    }
                    acceptReqProcessor.get().registerPort(this.endPoint);
                    this.preparingToStop = false;

                    String IPvType = "IPv4";
                    if (this.endPoint.getServerSocket().getInetAddress() instanceof Inet6Address) {
                        IPvType = "IPv6";
                    }

                    if (this.config.getHostname() == null) {
                        this.displayableHostName = "*  (" + IPvType + ")";
                    } else {
                        this.displayableHostName = this.endPoint.getServerSocket().getInetAddress().getHostName() + "  (" + IPvType + ": "
                                                   + this.endPoint.getServerSocket().getInetAddress().getHostAddress() + ")";
                    }
                    Tr.info(tc, TCPChannelMessageConstants.TCP_CHANNEL_STARTED,
                            new Object[] { getExternalName(), this.displayableHostName, String.valueOf(this.endPoint.getListenPort()) });

                } catch (IOException e) {
                    FFDCFilter.processException(e, getClass().getName() + ".start", "100", this);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(tc, "TCP Channel: " + getExternalName() + "- Problem occurred while starting TCP Channel: " + e.getMessage());
                    }
                    ChannelException x = new ChannelException("TCP Channel: " + getExternalName() + "- Problem occurred while starting channel: " + e.getMessage());
                    // Adjust flag so follow up attempt is possible.
                    this.stopFlag = true;
                    throw x;
                }
            }
            if (this.config.getDumpStatsInterval() > 0) {
                createStatisticsThread();
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "start");
        }
    }
547579
public Channel addPeer(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException {
        if (shutdown) {
            throw new InvalidArgumentException(format("Channel %s has been shutdown.", name));
        }

        if (null == peer) {
            throw new InvalidArgumentException("Peer is invalid can not be null.");
        }

        if (peer.getChannel() != null && peer.getChannel() != this) {
            throw new InvalidArgumentException(format("Peer already connected to channel %s", peer.getChannel().getName()));
        }

        if (null == peerOptions) {
            throw new InvalidArgumentException("peerOptions is invalid can not be null.");
        }

        logger.debug(format("%s adding peer: %s, peerOptions: %s", toString(), peer, "" + peerOptions));
        peer.setChannel(this);

        peers.add(peer);
        peerOptionsMap.put(peer, peerOptions.clone());
        peerEndpointMap.put(peer.getEndpoint(), peer);

        if (peerOptions.getPeerRoles().contains(PeerRole.SERVICE_DISCOVERY)) {

            final Properties properties = peer.getProperties();
            if ((properties == null) || properties.isEmpty() || (isNullOrEmpty(properties.getProperty("clientCertFile")) &&
                    !properties.containsKey("clientCertBytes"))) {
                TLSCertificateBuilder tlsCertificateBuilder = new TLSCertificateBuilder();
                TLSCertificateKeyPair tlsCertificateKeyPair = tlsCertificateBuilder.clientCert();
                peer.setTLSCertificateKeyPair(tlsCertificateKeyPair);
            }

            discoveryEndpoints.add(peer.getEndpoint());

        }

        for (Map.Entry<PeerRole, Set<Peer>> peerRole : peerRoleSetMap.entrySet()) {
            if (peerOptions.getPeerRoles().contains(peerRole.getKey())) {
                peerRole.getValue().add(peer);

            }
        }

        if (isInitialized() && peerOptions.getPeerRoles().contains(PeerRole.EVENT_SOURCE)) {
            try {
                peer.initiateEventing(getTransactionContext(), getPeersOptions(peer));
            } catch (TransactionException e) {
                logger.error(format("Error channel %s enabling eventing on peer %s", toString(), peer));
            }

        }
        return this;
    }
1158759
public void write(int b) throws java.io.IOException
  {
    byte[] buf = new byte[1];
    buf[0] = (byte) b;
    write(buf, 0, 1);
  }
949450
@Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        if (ctx.channel().isRegistered()) {
            // This should always be true with our current DefaultChannelPipeline implementation.
            // The good thing about calling initChannel(...) in handlerAdded(...) is that there will be no ordering
            // surprises if a ChannelInitializer will add another ChannelInitializer. This is as all handlers
            // will be added in the expected order.
            if (initChannel(ctx)) {

                // We are done with init the Channel, removing the initializer now.
                removeState(ctx);
            }
        }
    }
589869
@Handler(priority = 1000)
    public void onProtocolSwitchAccepted(
            ProtocolSwitchAccepted event, IOSubchannel channel) {
        event.requestEvent().associated(Session.class)
            .ifPresent(session -> {
                channel.setAssociated(Session.class, session);
            });
    }
862944
@SuppressWarnings("unchecked")
	protected void initBroadcastInputReaders() throws Exception {
		final int numBroadcastInputs = this.config.getNumBroadcastInputs();
		final MutableReader<?>[] broadcastInputReaders = new MutableReader[numBroadcastInputs];
		
		for (int i = 0; i < this.config.getNumBroadcastInputs(); i++) {
			//  ---------------- create the input readers ---------------------
			// in case where a logical input unions multiple physical inputs, create a union reader
			final int groupSize = this.config.getBroadcastGroupSize(i);
			if (groupSize == 1) {
				// non-union case
				broadcastInputReaders[i] = new MutableRecordReader<IOReadableWritable>(this);
			} else if (groupSize > 1){
				// union case
				MutableRecordReader<IOReadableWritable>[] readers = new MutableRecordReader[groupSize];
				for (int j = 0; j < groupSize; ++j) {
					readers[j] = new MutableRecordReader<IOReadableWritable>(this);
				}
				broadcastInputReaders[i] = new MutableUnionRecordReader<IOReadableWritable>(readers);
			} else {
				throw new Exception("Illegal input group size in task configuration: " + groupSize);
			}
		}
		this.broadcastInputReaders = broadcastInputReaders;
	}
65727
@SuppressWarnings("unchecked") // Channel Framework implements state map...
   public void connect(Object address) throws Exception
   {
      if (tc.isEntryEnabled()) SibTr.entry(this, tc, "connect", address);

      final JFapAddress jfapAddress = (JFapAddress) address;
      if ((jfapAddress != null) && (jfapAddress.getAttachType() == Conversation.CLIENT))
      {
         vc.getStateMap().put(OutboundProtocol.PROTOCOL, "BUS_CLIENT");
      }
      else
         vc.getStateMap().put(OutboundProtocol.PROTOCOL, "BUS_TO_BUS");
      
      super.connect(address);

      if (tc.isEntryEnabled()) SibTr.exit(this, tc, "connect");
   }
389120
public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e)
            throws Exception {
        final NioDatagramChannel channel = (NioDatagramChannel) e.getChannel();
        final ChannelFuture future = e.getFuture();
        if (e instanceof ChannelStateEvent) {
            final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
            final ChannelState state = stateEvent.getState();
            final Object value = stateEvent.getValue();
            switch (state) {
                case OPEN:
                    if (Boolean.FALSE.equals(value)) {
                        channel.worker.close(channel, future);
                    }
                    break;
                case BOUND:
                    if (value != null) {
                        bind(channel, future, (InetSocketAddress) value);
                    } else {
                        channel.worker.close(channel, future);
                    }
                    break;
                case CONNECTED:
                    if (value != null) {
                        connect(channel, future, (InetSocketAddress) value);
                    } else {
                        NioServerDatagramBoss.disconnect(channel, future);
                    }
                    break;
                case INTEREST_OPS:
                    channel.worker.setInterestOps(channel, future, ((Integer) value).intValue());
                    break;
            }
        } else if (e instanceof MessageEvent) {
            final MessageEvent event = (MessageEvent) e;
            final boolean offered = channel.writeBufferQueue.offer(event);
            assert offered;
            channel.worker.writeFromUserCode(channel);
        }
    }
1109521
private void doBind() throws Exception {
        LOG.debug("Creating listener socket");
        try {
            m_selector = Selector.open();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        ServerSocketChannel listenerSocket = ServerSocketChannel.open();
        InetSocketAddress inetsockaddr;
        if ((m_internalInterface == null) || (m_internalInterface.length() == 0)) {
            inetsockaddr = new InetSocketAddress(m_internalPort);
        }
        else {
            inetsockaddr = new InetSocketAddress(m_internalInterface, m_internalPort);
        }
        try {
            hostLog.info("Attempting to bind to internal ip " + inetsockaddr);
            listenerSocket.socket().bind(inetsockaddr);
            listenerSocket.configureBlocking(false);
            m_listenerSockets.add(listenerSocket);
        } catch (Exception e) {
            /*
             * If we bound to the leader address, the internal interface address  might not
             * bind if it is all interfaces
             */
            if (m_listenerSockets.isEmpty()) {
                LOG.fatal("Failed to bind to " + inetsockaddr);
                CoreUtils.printPortsInUse(hostLog);
                throw e;
            }
        }

        for (ServerSocketChannel ssc : m_listenerSockets) {
            ssc.register(m_selector, SelectionKey.OP_ACCEPT);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Non-Primary Listening on:" + inetsockaddr.toString());
        }
    }
1272561
private boolean splitTwo() throws PBXException
    {
        final AsteriskSettings profile = PBXFactory.getActiveProfile();
        AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX();

        List<Channel> channels = new LinkedList<>();
        channels.add(channel1);
        if (!pbx.waitForChannelsToQuiescent(channels, 3000))
        {
            logger.error(callSite, callSite);
            throw new PBXException("Channel: " + channel1 + " cannot be split as they are still in transition.");
        }

        /*
         * redirects the specified channels to the specified endpoints. Returns
         * true or false reflecting success.
         */

        AgiChannelActivityHold agi1 = new AgiChannelActivityHold();

        pbx.setVariable(channel1, "proxyId", "" + ((ChannelProxy) channel1).getIdentity());

        channel1.setCurrentActivityAction(agi1);

        final String agiExten = profile.getAgiExtension();
        final String agiContext = profile.getManagementContext();
        logger.debug("redirect channel lhs:" + channel1 + " to " + agiExten + " in context " + agiContext);

        final EndPoint extensionAgi = pbx.getExtensionAgi();
        final RedirectAction redirect = new RedirectAction(channel1, agiContext, extensionAgi, 1);
        // logger.error(redirect);

        boolean ret = false;
        {
            try
            {

                // final ManagerResponse response =
                pbx.sendAction(redirect, 1000);
                double ctr = 0;
                while (!agi1.hasCallReachedAgi() && ctr < 10)
                {
                    Thread.sleep(100);
                    ctr += 100.0 / 1000.0;
                    if (!agi1.hasCallReachedAgi())
                    {
                        logger.warn("Waiting on (agi1) " + channel1);
                    }

                }
                ret = agi1.hasCallReachedAgi();

            }
            catch (final Exception e)
            {
                logger.error(e, e);
            }
        }
        return ret;
    }
529415
private void invoke(final Request<?> marshalledRequest, final Bootstrap b, final PutMediaResponseHandler responseHandler) throws InterruptedException {
        b.connect().addListener(new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                try {
                    Channel channel = future.channel();

                    HttpRequest request = RequestAdapter.adapt(marshalledRequest);

                    // Send request
                    channel.writeAndFlush(request);

                    // Send chunked content
                    channel.writeAndFlush(new HttpChunkedInput(new ChunkedStream(marshalledRequest.getContent())));
                } catch (Exception e) {
                    responseHandler.onFailure(e);
                }
            }
        });
    }
286231
protected static void checkChannels(final Iterable<String> channels) {
        if (channels == null) {
            throw new IllegalArgumentException("channels must not be null");
        }
        for (final String channel : channels) {
            if (channel == null || "".equals(channel)) {
                throw new IllegalArgumentException("channels' members must not be null: " + channels);
            }
        }
    }
671099
@Setup(Level.Trial)
  public void setup() throws Exception {
    super.setup(clientExecutor,
        ExecutorType.DIRECT,
        MessageSize.SMALL,
        responseSize,
        FlowWindowSize.MEDIUM,
        ChannelType.NIO,
        maxConcurrentStreams,
        channelCount);
    callCounter = new AtomicLong();
    completed = new AtomicBoolean();
    record = new AtomicBoolean();
    latch =
        startFlowControlledStreamingCalls(maxConcurrentStreams, callCounter, record, completed, 1);
  }