/*
@see
com.ibm.wsspi.channelfw.ChannelFactory#findOrCreateChannel(ChannelData)
437114
public synchronized Channel findOrCreateChannel(ChannelData channelData) throws ChannelException {
        String channelName = channelData.getName();
        Channel rc = this.existingChannels.get(channelName);
        if (null == rc) {
            rc = createChannel(channelData);
            this.existingChannels.put(channelName, rc);
        }
        return rc;
    }
354518
public synchronized boolean doesChannelReferenceChain(String channelName, String chainName) {
        boolean foundRef = false;
        Chain chain = this.chainRunningMap.get(chainName);
        if (chain != null) {
            ChannelData channelsData[] = chain.getChannelsData();
            ChildChannelDataImpl childChannelData = null;
            for (int i = 0; i < channelsData.length; i++) {
                childChannelData = (ChildChannelDataImpl) channelsData[i];
                if (childChannelData.getExternalName().equals(channelName)) {
                    foundRef = true;
                    break;
                }
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "doesChannelReferenceChain: channel=" + channelName + ", chain=" + chainName + ", rc=" + foundRef);
        }
        return foundRef;
    }
625858
private void determineChannelAccessor() throws ChannelFrameworkException, ChannelFactoryException {
        // Extract the factory class from the application side channel definition.
        OutboundChannelDefinition first = this.outboundChannelDefs.getFirst();
        Class<?> factoryClass = first.getOutboundFactory();
        if (factoryClass == null) {
            throw new ChannelFrameworkException("No factory class associated with outbound channel " + first);
        }
        // Get an instance of the channel factory from the framework.
        ChannelFactory outboundFactory = framework.getChannelFactoryInternal(factoryClass, false);
        if (outboundFactory == null) {
            throw new ChannelFrameworkException("No channel factory could be found for factory class " + factoryClass);
        }
        // Get the channel accessor from the factory instance.
        this.channelAccessor = outboundFactory.getApplicationInterface();
    }
75448
synchronized void setChannelFactory(ChannelFactory factory) throws ChannelFactoryException {
        if (factory != null && cf != null) {
            throw new ChannelFactoryException("ChannelFactory already exists");
        }
        this.cf = factory;
    }
723009
public Message getOrCreateMessage(TextChannel channel, JsonNode data) {
        long id = Long.parseLong(data.get("id").asText());
        synchronized (messages) {
            return getCachedMessageById(id).orElseGet(() -> new MessageImpl(this, channel, data));
        }
    }
1083969
public function channel($channel_id, $source_factory = null, $emitter_factory = null)
    {
        if (isset($this->channel_list[$channel_id])){
            return $this->channel_list[$channel_id];
        }

        $source = null;
        if ($source_factory){
            if (is_callable($source_factory)){
                $source = call_user_func($source_factory);
            }
            else if ($source_factory instanceof EventSourceFactoryInterface){
                $source = $source_factory->createEventSource();
            }
        }

        $emitter = null;
        if ($emitter_factory){
            if (is_callable($emitter_factory)){
                $emitter = call_user_func($emitter_factory);
            }
            else if ($emitter_factory instanceof EventSourceFactoryInterface){
                $emitter = $emitter_factory->createEventEmitter();
            }
        }

        $channel = new EventChannel($source, $emitter);
        $this->channel_list[$channel_id] = $channel;

        return $channel;
    }
670078
@Programmatic
    public CommunicationChannelOwnerLink createLink(final CommunicationChannel communicationChannel, final CommunicationChannelOwner owner) {
        final CommunicationChannelOwnerLink link = linkFactory.createLink(communicationChannel, owner);
        // copy over the type, to support subsequent querying.
        link.setCommunicationChannelType(communicationChannel.getType());
        return link;
    }
16615
public FileIOChannel.ID createChannel() {
		final int num = getNextPathNum();
		return new FileIOChannel.ID(this.paths[num], num, this.random);
	}
892720
def channels_create(self, name, **kwargs):
        """"""
        return self.__call_api_post('channels.create', name=name, kwargs=kwargs)
1236107
public synchronized Channel findOrCreateChannel(ChannelData channelData) throws ChannelException {
        String channelName = channelData.getName();
        Channel ret = this.existingChannels.get(channelName);
        if (ret == null) {
            // Create the new channel with the input configuration
            ret = new JFapChannelInbound(_channelFactoryData, channelData);
            this.existingChannels.put(channelName, ret);
        }
        return ret;
    }
134802
public ServerVoiceChannel getOrCreateServerVoiceChannel(JsonNode data) {
        long id = Long.parseLong(data.get("id").asText());
        ChannelType type = ChannelType.fromId(data.get("type").asInt());
        synchronized (this) {
            if (type == ChannelType.SERVER_VOICE_CHANNEL) {
                return getVoiceChannelById(id).orElseGet(() -> new ServerVoiceChannelImpl(api, this, data));
            }
        }
        // Invalid channel type
        return null;
    }
1273305
private static Channel createChannel() throws IOException {

        // dup the file descriptor - we do this so that for two reasons :-
        // 1. Avoids any timing issues with FileDescriptor.in being closed
        //    or redirected while we create the channel.
        // 2. Allows streams based on file descriptor 0 to co-exist with
        //    the channel (closing one doesn't impact the other)

        int fdVal = dup(0);

        // Examine the file descriptor - if it's not a socket then we don't
        // create a channel so we release the file descriptor.

        int st;
        st = soType0(fdVal);
        if (st != SOCK_STREAM && st != SOCK_DGRAM) {
            close0(fdVal);
            return null;
        }


        // Next we create a FileDescriptor for the dup'ed file descriptor
        // Have to use reflection and also make assumption on how FD
        // is implemented.

        Class paramTypes[] = { int.class };
        Constructor ctr = Reflect.lookupConstructor("java.io.FileDescriptor",
                                                    paramTypes);
        Object args[] = { new Integer(fdVal) };
        FileDescriptor fd = (FileDescriptor)Reflect.invoke(ctr, args);


        // Now create the channel. If the socket is a streams socket then
        // we see if tthere is a peer (ie: connected). If so, then we
        // create a SocketChannel, otherwise a ServerSocketChannel.
        // If the socket is a datagram socket then create a DatagramChannel

        SelectorProvider provider = SelectorProvider.provider();
        assert provider instanceof sun.nio.ch.SelectorProviderImpl;

        Channel c;
        if (st == SOCK_STREAM) {
            InetAddress ia = peerAddress0(fdVal);
            if (ia == null) {
               c = new InheritedServerSocketChannelImpl(provider, fd);
            } else {
               int port = peerPort0(fdVal);
               assert port > 0;
               InetSocketAddress isa = new InetSocketAddress(ia, port);
               c = new InheritedSocketChannelImpl(provider, fd, isa);
            }
        } else {
            c = new InheritedDatagramChannelImpl(provider, fd);
        }
        return c;
    }
1371300
@Process(actionType = CreateConnector.class)
    public void createConnector(final CreateConnector action, final Dispatcher.Channel channel) {

        final List<Property> connectors = getModelsFor(action.getAddressTemplate());
        // First create the connector, then create the security=sasl singleton and finally
        // create the sasl-policy=policy singleton
        Outcome<FunctionContext> outcome = new Outcome<FunctionContext>() {
            @Override
            public void onFailure(FunctionContext context) {
                channel.nack(context.getError());
            }

            @Override
            public void onSuccess(FunctionContext context) {
                lastModifiedInstance = action.getInstanceName();
                read(action.getAddressTemplate().getResourceType(), getModelsFor(action.getAddressTemplate()), channel);
            }
        };

        AddressTemplate securityAddress = action.getAddressTemplate().append("security=" + SASL_SINGLETON);
        AddressTemplate policyAddress = securityAddress.append("sasl-policy=" + POLICY_SINGLETON);
        new Async<FunctionContext>(new Progress.Nop()).waterfall(new FunctionContext(), outcome,
                new CreateConnectorFn(dispatcher, statementContext, action.getAddressTemplate(),
                        action.getInstanceName(), action.getNewModel()),
                new CreateSaslSingleton(dispatcher, statementContext, action.getInstanceName(), securityAddress),
                new CreateSaslSingleton(dispatcher, statementContext, action.getInstanceName(), policyAddress));
    }
1324862
@Override
    public Channel createChannel(String ccid, String trackingId) {

        try {
            // The controller has to assign the channel to a bounce proxy
            // instance.
            ControlledBounceProxyInformation bpInfo = strategy.calculateBounceProxy(ccid);

            URI channelLocation = bpFacade.createChannel(bpInfo, ccid, trackingId);

            Channel channel = new Channel(bpInfo, ccid, channelLocation);

            channelDirectory.addChannel(channel);
            bounceProxyDirectory.updateChannelAssignment(ccid, bpInfo);

            return channel;

        } catch (Exception e) {
            log.error("Could not create channel on bounce proxy: channel {}, error: {}", ccid, e.getMessage());
            throw new JoynrRuntimeException("Error creating channel on bounce proxy", e);
        }
    }
507954
private synchronized void createChannel(String channel) {
        if (!channelExists(channel)) {
            Queue queue = new Queue(channel, true, false, true);
            admin.declareQueue(queue);
            Binding binding = new Binding(channel, DestinationType.QUEUE, exchange.getName(), channel + ".#", null);
            admin.declareBinding(binding);
        }
    }
1317532
synchronized void initChainInternal(ChainData inputChainData) throws ChannelException, ChainException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "initChainInternal");
        }
        String inputChainName = inputChainData.getName();
        Chain chain = null;
        ChainData newChainData = null;
        ChannelData inputChannelDataArray[] = inputChainData.getChannelList();
        ChannelData newChannelDataArray[] = new ChannelData[inputChannelDataArray.length];
        ChannelDataImpl parent = null;
        ChildChannelDataImpl child = null;
        // Track whether new children are created (or simply reused) in case we need
        // to rollback from an excepction
        boolean childrenNew[] = new boolean[inputChannelDataArray.length];
        // Initialize array to false.
        for (int i = 0; i < childrenNew.length; i++) {
            childrenNew[i] = false;
        }

        try {
            if (FlowType.INBOUND.equals(inputChainData.getType())) {

                // Construct an inbound chain - note nothing is inited yet
                // Use parents to create new channel data array of children (reuse
                // existing children where possible)
                newChannelDataArray = generateChildDataArray(inputChannelDataArray, childrenNew);
                // Create new chain data with child channel data objects.
                newChainData = new ChainDataImpl((ChainDataImpl) inputChainData, newChannelDataArray);
                try {
                    chain = new InboundChain(newChainData, this);
                } catch (ChannelException e) {
                    // The channel exception may specify that FFDC should be suppressed
                    if (!e.suppressFFDC()) {
                        FFDCFilter.processException(e, getClass().getName() + ".initChainInternal", "2206", this, new Object[] { newChainData });
                        Tr.error(tc, "chain.initialization.error", new Object[] { inputChainData.getName(), e.toString() });
                    } else if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(tc, "An exception occurred when initializing chain", new Object[] { inputChainData.getName(), e.toString() });
                    }
                    // Clean up the already created child refs in the parent.
                    cleanChildRefsInParent(newChannelDataArray, childrenNew);
                    throw e;
                } catch (IncoherentChainException e) {
                    // No FFDC Needed as it is called in the constructor above.
                    // Clean up the already created child refs in the parent.
                    cleanChildRefsInParent(newChannelDataArray, childrenNew);
                    // Throw exception to caller.
                    throw e;
                }
            } else {

                // Construct an outbound chain - note nothing is inited yet
                // Get children for each outbound parent channel data.
                // Loop through each channel of this new chain - note, these are parent
                // names
                for (int i = 0; i < inputChannelDataArray.length; i++) {
                    // Get the parent channel data object.
                    parent = (ChannelDataImpl) channelDataMap.get(inputChannelDataArray[i].getName());
                    // Get an existing one from the runtime.
                    newChannelDataArray[i] = parent.getOutboundChild();
                    if (null == newChannelDataArray[i]) {
                        // None available in runtime. Create one.
                        newChannelDataArray[i] = parent.createChild();
                        childrenNew[i] = true;
                    } else {
                        childrenNew[i] = false;
                    }
                }
                // Create new outbound chain data with child channel data objects.
                newChainData = new ChainDataImpl(inputChainName, inputChainData.getType(), newChannelDataArray, null);
                try {
                    chain = new OutboundChain(newChainData, this);
                } catch (ChannelException e) {
                    // The channel exception may specify that FFDC should be suppressed
                    if (!e.suppressFFDC()) {
                        FFDCFilter.processException(e, getClass().getName() + ".initChainInternal", "2241", this, new Object[] { newChainData });
                        Tr.error(tc, "chain.initialization.error", new Object[] { inputChainData.getName(), e.toString() });
                    } else if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(tc, "An exception occurred when initializing chain", new Object[] { inputChainData.getName(), e.toString() });
                    }
                    // Clean up the already created child refs in the parent.
                    cleanChildRefsInParent(newChannelDataArray, childrenNew);
                    throw e;
                } catch (IncoherentChainException e) {
                    // No FFDC Needed as it is called in the constructor called above.
                    // Clean up the already created child refs in the parent.
                    cleanChildRefsInParent(newChannelDataArray, childrenNew);
                    // Continue to throw exception to caller.
                    throw e;
                }
            }

            // Initialize the chain and its channels
            Channel[] chainChannels = chain.getChannels();
            List<Channel> chainsDone = new ArrayList<Channel>();
            Channel channelX = null; // may need this in the exception clause
            try {
                for (int i = 0; i < chainChannels.length; ++i) {
                    channelX = chainChannels[i];
                    initChannelInChain(channelX, chain);
                    chainsDone.add(channelX);
                    channelX = null;
                }
                // Update the chain state and its event listeners.
                chain.init();
            } catch (ChannelException e) {
                if (e instanceof RetryableChannelException) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Caught RetryableChannelException indicating the port is busy");
                    }
                } else {
                    Tr.error(tc, "chain.initialization.error", new Object[] { chain.getName(), e.toString() });
                    // The channel exception may specify that FFDC should be suppressed
                    if (!e.suppressFFDC()) {
                        FFDCFilter.processException(e, getClass().getName() + ".initChainInternal", "2266", this, new Object[] { chainChannels, chainsDone, chain });
                    }
                }

                // Handle partially created chain. Undo any inits that have been done
                // thus far.
                for (int i = 0; i < newChannelDataArray.length; i++) {
                    if (childrenNew[i]) {
                        child = (ChildChannelDataImpl) newChannelDataArray[i];
                        child.getParent().removeChild(child);
                    }
                }

                // try to destroy a channel that failed but was not add to the "done" list.
                if (channelX != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "calling destory on channel outside of destroyChannelInChain: " + channelX);
                    }
                    channelX.destroy();
                }

                for (int i = 0; i < chainsDone.size(); i++) {
                    try {
                        destroyChannelInChain(chainsDone.get(i), chain, newChannelDataArray[i]);
                        // Clean up the already created child refs in the parent.
                    } catch (Exception e1) {
                        // No FFDC needed.
                    }
                }
                // Throw the exception up to the caller.
                throw e;
            }

            // Add the new chain to the framework.
            this.chainRunningMap.put(inputChainName, chain);
        } catch (IncoherentChainException e) {
            FFDCFilter.processException(e, getClass().getName() + ".initChainInternal", "2290", this, new Object[] { inputChainData, chain });
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Caught exception during chain init: " + e);
            }
            // Can only happen in cases where the factory has multiple dev side
            // interfaces.
            // And the channel being created uses one that isn't compatible in the
            // chain.
            throw e;
        } catch (InvalidChannelNameException e) {
            FFDCFilter.processException(e, getClass().getName() + ".initChainInternal", "2298", this, new Object[] { inputChainData, chain });
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Caught exception during chain init: " + e);
            }
            // This should never happen. If the chain config exists, then the channel
            // configs must exist.
            throw e;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "initChainInternal");
        }
    }
1165359
public static MessageCreator creator(final String pathServiceSid, 
                                         final String pathChannelSid, 
                                         final String body) {
        return new MessageCreator(pathServiceSid, pathChannelSid, body);
    }