This is the root module of the datachannel freedom.js demo.
It runs in an isolated thread with its own namespace,
peerconnection and datachannel objects are provided through
freedom.
431198
function (dispatchEvents, name) {
  this.dispatchEvent = dispatchEvents;
  this.name = name;
  this.connection = freedom['core.rtcpeerconnection']();
  this.connection.on(function (type, msg) {
    if (type === 'onsignalingstatechange' ||
        type === 'onnegotiationneeded' ||
        type === 'oniceconnectionstatechange') {
      this.dispatchEvent('message', '<small style="color:gray">' + type + '</small>');
    } else if (type === 'onicecandidate') {
      if (msg) {
        this.dispatchEvent('ice', JSON.stringify(msg));
      }
      this.dispatchEvent('message', '<small style="color:lightgray">Ice Candidate Produced</small>');
    } else if (type === 'ondatachannel') {
      this.dispatchEvent('message', '<small style="color:blue">Data Channel Ready [Recipient]</small>');
      this.channel = freedom['core.rtcdatachannel'](msg.channel);
      this.channel.on(this.onDataChannelMsg.bind(this));
    } else {
      this.dispatchEvent('message', JSON.stringify({type: type, msg: msg}));
    }
  }.bind(this));
}
1365404
private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,
                                                     createDaemonThreadFactory(serviceName + "-boss-thread-%d"));
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,
                                                       createDaemonThreadFactory(serviceName + "-worker-thread-%d"));
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap
      .group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          channelGroup.add(ch);

          ChannelPipeline pipeline = ch.pipeline();
          if (sslHandlerFactory != null) {
            // Add SSLHandler if SSL is enabled
            pipeline.addLast("ssl", sslHandlerFactory.create(ch.alloc()));
          }
          pipeline.addLast("codec", new HttpServerCodec());
          pipeline.addLast("compressor", new HttpContentCompressor());
          pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
          pipeline.addLast("keepAlive", new HttpServerKeepAliveHandler());
          pipeline.addLast("router", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));
          if (eventExecutorGroup == null) {
            pipeline.addLast("dispatcher", new HttpDispatcher());
          } else {
            pipeline.addLast(eventExecutorGroup, "dispatcher", new HttpDispatcher());
          }

          if (pipelineModifier != null) {
            pipelineModifier.modify(pipeline);
          }
        }
      });

    for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {
      bootstrap.option(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {
      bootstrap.childOption(entry.getKey(), entry.getValue());
    }

    return bootstrap;
  }
904668
function Messaging() {

    /***********************************************************
    * @attributes 
    ***********************************************************/

    var appKey;                     // application key
    var authToken;                  // authentication token
    var clusterUrl;                 // cluster URL to connect
    var connectionTimeout;          // connection timeout in milliseconds
    var messageMaxSize;             // message maximum size in bytes
    var channelMaxSize;             // channel maximum size in bytes
    var messagesBuffer;             // buffer to hold the message parts
    var id;                         // object identifier
    var isConnected;                // indicates whether the client object is connected
    var isConnecting;               // indicates whether the client object is connecting
    var alreadyConnectedFirstTime;  // indicates whether the client already connected for the first time
    var stopReconnecting;           // indicates whether the user disconnected (stop the reconnecting proccess)
    var ortc;                       // represents the object itself
    var reconnectIntervalId;        // id used for the reconnect interval
    var reconnectTimeoutlId;        // id used for the reconnect timeout
    var sockjs;                     // socket connected to
    var url;                        // URL to connect
    var userPerms;                  // user permissions
    var connectionMetadata;         // connection metadata used to identify the client
    var announcementSubChannel;     // announcement subchannel
    var subscribedChannels;         // subscribed/subscribing channels
    var lastKeepAlive;              // holds the time of the last keep alive received
    var invalidConnection;          // indicates whether the connection is valid
    var reconnectStartedAt;         // the time which the reconnect started
    var eventEmitter;               // event emitter to send message
   

    /***********************************************************
    * @attributes initialization
    ***********************************************************/

    connectionTimeout = 15000;
    messageMaxSize = 800;
    channelMaxSize = 100;
    connectionMetadataMaxSize = 256;

    messagesBuffer = Object.create(null);
    subscribedChannels = Object.create(null);

    isConnected = false;
    isConnecting = false;
    alreadyConnectedFirstTime = false;
    invalidConnection = false;

    ortc = this;
    lastKeepAlive = null;
    userPerms = null;
    reconnectStartedAt = null;
    
    this.eventEmitter = new process.EventEmitter();

    /***********************************************************
    * @properties
    ***********************************************************/

    this.getId = function () { return id; };
    this.setId = function (newId) { id = newId; };

    this.getUrl = function () { return url; };
    this.setUrl = function (newUrl) { url = newUrl; clusterUrl = null; };

    this.getClusterUrl = function () { return clusterUrl; };
    this.setClusterUrl = function (newUrl) { clusterUrl = newUrl; url = null; };

    this.getConnectionTimeout = function () { return connectionTimeout; };
    this.setConnectionTimeout = function (newTimeout) { connectionTimeout = newTimeout; };

    this.getIsConnected = function () { return isConnected && ortc.sockjs != null; };

    this.getConnectionMetadata = function () { return connectionMetadata; };
    this.setConnectionMetadata = function (newConnectionMetadata) { connectionMetadata = newConnectionMetadata; };

    this.getAnnouncementSubChannel = function () { return announcementSubChannel; };
    this.setAnnouncementSubChannel = function (newAnnouncementSubChannel) { announcementSubChannel = newAnnouncementSubChannel; };

    /***********************************************************
    * @events
    ***********************************************************/

    this.onConnected = null;
    this.onDisconnected = null;
    this.onSubscribed = null;
    this.onUnsubscribed = null;
    this.onException = null;
    this.onReconnecting = null;
    this.onReconnected = null;

    /***********************************************************
    * @public methods
    ***********************************************************/

    /*
    * Connects to the gateway with the application key and authentication token.
    */
    this.connect = function (appKey, authToken) {
        /*
        Sanity Checks
        */
        if (isConnected) {
            delegateExceptionCallback(ortc, 'Already connected');
        }
        else if (!url && !clusterUrl) {
            delegateExceptionCallback(ortc, 'URL and Cluster URL are null or empty');
        }
        else if (!appKey) {
            delegateExceptionCallback(ortc, 'Application key is null or empty');
        }
        else if (!authToken) {
            delegateExceptionCallback(ortc, 'Authentication Token is null or empty');
        }
        else if (url && !ortcIsValidUrl(url)) {
            delegateExceptionCallback(ortc, 'Invalid URL');
        }
        else if (clusterUrl && !ortcIsValidUrl(clusterUrl)) {
            delegateExceptionCallback(ortc, 'Invalid Cluster URL');
        }
        else if (!ortcIsValidInput(appKey)) {
            delegateExceptionCallback(ortc, 'Application Key has invalid characters');
        }
        else if (!ortcIsValidInput(authToken)) {
            delegateExceptionCallback(ortc, 'Authentication Token has invalid characters');
        }
        else if (!ortcIsValidInput(announcementSubChannel)) {
            delegateExceptionCallback(ortc, 'Announcement Subchannel has invalid characters');
        }
        else if (connectionMetadata && connectionMetadata.length > connectionMetadataMaxSize) {
            delegateExceptionCallback(ortc, 'Connection metadata size exceeds the limit of ' + connectionMetadataMaxSize + ' characters');
        }
        else{
            ortc.appKey = appKey;
            ortc.authToken = authToken;

            isConnecting = true;
            stopReconnecting = false;

            if (clusterUrl && clusterUrl != null) {
                clusterUrl = ortcTreatUrl(clusterUrl);

                clusterConnection(ortc.getConnectionTimeout());
            }
            else {
                url = ortcTreatUrl(url);

                ortc.sockjs = createSocketConnection(url);
            }

            if (!ortc.reconnectTimeoutlId) {
                // Timeout to reconnect
                ortc.reconnectTimeoutlId = setTimeout(function () {
                    if (!isConnected) {
                        reconnectSocket(ortc.getConnectionTimeout());
                    }
                }, ortc.getConnectionTimeout());
            }
        }
    };

    /*
    * Subscribes to the channel so the client object can receive all messages sent to it by other clients.
    */
    this.subscribe = function (channel, subscribeOnReconnected, onMessageCallback) {
        /*
        Sanity Checks
        */
        if (!isConnected) {
            delegateExceptionCallback(ortc, 'Not connected');
        }
        else if (!channel) {
            delegateExceptionCallback(ortc, 'Channel is null or empty');
        }
        else if (!ortcIsValidInput(channel)) {
            delegateExceptionCallback(ortc, 'Channel has invalid characters');
        }
        else if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribing) {
            delegateExceptionCallback(ortc, 'Already subscribing to the channel \'' + channel + '\'');
        }
        else if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribed) {
            delegateExceptionCallback(ortc, 'Already subscribed to the channel \'' + channel + '\'');
        }
        else if (channel.length > channelMaxSize) {
            delegateExceptionCallback(ortc, 'Channel size exceeds the limit of ' + channelMaxSize + ' characters');
        }
        else if (!ortcIsValidBoolean(subscribeOnReconnected)) {
            delegateExceptionCallback(ortc, 'The argument \'subscribeOnReconnected\' must be a boolean');
        }
        else if (!ortcIsFunction(onMessageCallback)) {
            delegateExceptionCallback(ortc, 'The argument \'onMessageCallback\' must be a function');
        }
        else {
            if (ortc.sockjs != null) {
                var domainChannelCharacterIndex = channel.indexOf(':');
                var channelToValidate = channel;
                var hashPerm = null;

                if (domainChannelCharacterIndex > 0) {
                    channelToValidate = channel.substring(0, domainChannelCharacterIndex + 1) + '*';
                }

                if (userPerms && userPerms != null) {
                    hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[channel];
                }

                if (userPerms && userPerms != null && !hashPerm) {
                    delegateExceptionCallback(ortc, 'No permission found to subscribe to the channel \'' + channel + '\'');
                }
                else {
                    if (subscribedChannels[channel]) {
                        subscribedChannels[channel].isSubscribing = true;
                        subscribedChannels[channel].isSubscribed = false;
                        subscribedChannels[channel].subscribeOnReconnected = subscribeOnReconnected;
                        subscribedChannels[channel].onMessageCallback = onMessageCallback;
                    }
                    else {
                        subscribedChannels[channel] = { 'isSubscribing': true, 'isSubscribed': false, 'subscribeOnReconnected': subscribeOnReconnected, 'onMessageCallback': onMessageCallback };
                    }
                    if(ortc.sockjs){
                        ortc.sockjs.sendText(JSON.stringify('subscribe;' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + hashPerm));
                    }
                }
            }
        }
    };

    /*
    * Unsubscribes from the channel so the client object stops receiving messages sent to it.
    */
    this.unsubscribe = function (channel) {
        /*
        Sanity Checks
        */
        if (!isConnected) {
            delegateExceptionCallback(ortc, 'Not connected');
        }
        else if (!channel) {
            delegateExceptionCallback(ortc, 'Channel is null or empty');
        }
        else if (!ortcIsValidInput(channel)) {
            delegateExceptionCallback(ortc, 'Channel has invalid characters');
        }
        else if (!subscribedChannels[channel] || (subscribedChannels[channel] && !subscribedChannels[channel].isSubscribed)) {
            delegateExceptionCallback(ortc, 'Not subscribed to the channel ' + channel);
        }
        else if (channel.length > channelMaxSize) {
            delegateExceptionCallback(ortc, 'Channel size exceeds the limit of ' + channelMaxSize + ' characters');
        }
        else {
            if (ortc.sockjs) {
                ortc.sockjs.sendText(JSON.stringify('unsubscribe;' + ortc.appKey + ';' + channel));
            }
        }
    };

    /*
    * Sends the message to the channel.
    */
    this.send = function (channel, message) {
        /*
        Sanity Checks
        */
        if (!isConnected || ortc.sockjs == null) {
            delegateExceptionCallback(ortc, 'Not connected');
        }
        else if (!channel) {
            delegateExceptionCallback(ortc, 'Channel is null or empty');
        }
        else if (!ortcIsValidInput(channel)) {
            delegateExceptionCallback(ortc, 'Channel has invalid characters');
        }
        else if (!message) {
            delegateExceptionCallback(ortc, 'Message is null or empty');
        }
        else if (!ortcIsString(message)) {
            delegateExceptionCallback(ortc, 'Message must be a string');
        }
        else if (channel.length > channelMaxSize) {
            delegateExceptionCallback(ortc, 'Channel size exceeds the limit of ' + channelMaxSize + ' characters');
        }
        else {
            var domainChannelCharacterIndex = channel.indexOf(':');
            var channelToValidate = channel;
            var hashPerm = null;

            if (domainChannelCharacterIndex > 0) {
                channelToValidate = channel.substring(0, domainChannelCharacterIndex + 1) + '*';
            }

            if (userPerms && userPerms != null) {
                hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[channel];
            }

            if (userPerms && userPerms != null && !hashPerm) {
                delegateExceptionCallback(ortc, 'No permission found to send to the channel \'' + channel + '\'');
            }
            else {
                // Multi part
                var messageParts = [];
                var messageId = generateId(8);
                var i;
                var allowedMaxSize = messageMaxSize - channel.length;

                for (i = 0; i < message.length; i = i + allowedMaxSize) {
                    // Just one part
                    if (message.length <= allowedMaxSize) {
                        messageParts.push(message);
                        break;
                    }

                    if (message.substring(i, i + allowedMaxSize)) {
                        messageParts.push(message.substring(i, i + allowedMaxSize));
                    }
                }

                if (messageParts.length == 1) {
                    if(ortc.sockjs){
                        ortc.sockjs.sendText(JSON.stringify('send;' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + hashPerm + ';' + messageId + '_1-1_' + messageParts[0]));
                    }  
                }
                else {
                    for (var j = 1; j <= messageParts.length; j++) {
                        var messageToSend = 'send;' + ortc.appKey + ';' + ortc.authToken + ';' + channel + ';' + hashPerm + ';' + messageId + '_' + j + '-' + messageParts.length + '_' + messageParts[j - 1];
                        this.sendMultiPartMessage(messageToSend);                        
                    }
                }
            }
        }
    };

    /*
    * Sends the message to the channel.
    */
    this.sendProxy = function (applicationKey, privateKey, channel, message) {
        /*
        Sanity Checks
        */
        if (!isConnected || ortc.sockjs == null) {
            delegateExceptionCallback(ortc, 'Not connected');
        }
        else if (!applicationKey) {
            delegateExceptionCallback(ortc, 'Application key is null or empty');
        }
        else if (!privateKey) {
            delegateExceptionCallback(ortc, 'Private key is null or empty');
        }
        else if (!channel) {
            delegateExceptionCallback(ortc, 'Channel is null or empty');
        }
        else if (!ortcIsValidInput(channel)) {
            delegateExceptionCallback(ortc, 'Channel ' + channel + ' has invalid characters');
        }
        else if (!message) {
            delegateExceptionCallback(ortc, 'Message is null or empty');
        }
        else if (!ortcIsString(message)) {
            delegateExceptionCallback(ortc, 'Message must be a string');
        }
        else if (channel.length > channelMaxSize) {
            delegateExceptionCallback(ortc, 'Channel size exceeds the limit of ' + channelMaxSize + ' characters');
        }
        else {

            // Multi part
            var messageParts = [];
            var messageId = generateId(8);
            var i;
            var allowedMaxSize = messageMaxSize - channel.length;

            for (i = 0; i < message.length; i = i + allowedMaxSize) {
                // Just one part
                if (message.length <= allowedMaxSize) {
                    messageParts.push(message);
                    break;
                }

                if (message.substring(i, i + allowedMaxSize)) {
                    messageParts.push(message.substring(i, i + allowedMaxSize));
                }
            }

            if (messageParts.length == 1) {
                if(ortc.sockjs){
                    ortc.sockjs.sendText(JSON.stringify('sendproxy;' + applicationKey + ';' + privateKey + ';' + channel + ';' + messageId + '_1-1_' + messageParts[0]));
                }  
            }
            else {
                for (var j = 1; j <= messageParts.length; j++) {
                    var messageToSend = 'sendproxy;' + applicationKey + ';' + privateKey + ';' + channel + ';' + messageId + '_' + j + '-' + messageParts.length + '_' + messageParts[j - 1];
                    this.sendMultiPartMessage(messageToSend);                        
                }
            }
        }
    };


    this.sendMultiPartMessage = function(message){
        process.nextTick(function(){
            if(ortc.sockjs){
                ortc.sockjs.sendText(JSON.stringify(message));
            }
        });
    }

    /*
    * Disconnects from the gateway.
    */
    this.disconnect = function () {
        clearReconnectInterval();

        // Stop the reconnecting process
        stopReconnecting = true;
        alreadyConnectedFirstTime = false;

        // Clear subscribed channels
        subscribedChannels = Object.create(null);

        /*
        Sanity Checks
        */
        if (!isConnected && !invalidConnection) {
            delegateExceptionCallback(ortc, 'Not connected');
        }
        else {
            disconnectSocket();
        }
    };

    /*
    * Gets a value indicating whether this client object is subscribed to the channel.
    */
    this.isSubscribed = function (channel) {
        /*
        Sanity Checks
        */
        if (!isConnected) {
            delegateExceptionCallback(ortc, 'Not connected');
        }
        else if (!channel) {
            delegateExceptionCallback(ortc, 'Channel is null or empty');
        }
        else if (!ortcIsValidInput(channel)) {
            delegateExceptionCallback(ortc, 'Channel has invalid characters');
        }
        else {
            if (subscribedChannels[channel] && subscribedChannels[channel].isSubscribed) {
                return subscribedChannels[channel].isSubscribed;
            }
            else {
                return false;
            }
        }
    };   
    
    /**
    * @function {public} saveAuthentication Saves the channels and its permissions for the supplied application key and authentication token.
    * @param {string} url The ORTC server URL.
    * @param {bool} isCluster Indicates whether the ORTC server is in a cluster.
    * @param {string} authenticationToken The authentication token generated by an application server (for instance: a unique session ID).
    * @param {bool} authenticationTokenIsPrivate Indicates whether the authentication token is private.
    * @param {string} applicationKey The application key provided when the ORTC service is purchased.
    * @param {int} timeToLive The authentication token time to live (TTL), in other words, the allowed activity time (in seconds).
    * @param {string} privateKey The private key provided when the ORTC service is purchased.
    * @param {object} permissions The channels and their permissions (w: write/read or r: read or p: presence, case sensitive).
    * @param {function(error, success)} callback Function called when the authentication finishes. If 'error' is not null then an error occurred.
    * @returns void

    * @returns void
    *
    * </br>
    * <b class="codeSample">Code Sample:</b>
    *
    * <pre class="brush: js; gutter: false;">
    *   ortcClient.saveAuthentication('http://developers2.realtime.livehtml.net/server/2.1/', true, 'myAuthenticationToken', 0, 'myApplicationKey', 1400, 'myPrivateKey', { "channel1": "wrp", "channel2": "w" }, function (error, success) {
    *       if (error) {
    *           console.log('Error saving authentication: ' + error);
    *       } else if (success) {
    *           console.log('Successfully authenticated');
    *       } else {
    *           console.log('Not authenticated');
    *       }
    *   });
    * </pre>
    */
    this.saveAuthentication = function (url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, callback) {
        var connectionUrl = url;

        if (isCluster) {
            getServerFromCluster({
                clusterUri : connectionUrl, 
                connectionTimeout : ortc.getConnectionTimeout(),
                appKey : applicationKey
            }, 
            function (error, body) {
                if (error != null) {
                    delegateExceptionCallback(ortc, 'Error getting server from Cluster');
                    callback('Error getting server from Cluster',null);
                }
                else {
                    connectionUrl = body.substring(body.indexOf('=') + 3, body.length - 2);
                    IbtRealtimeRestServices.saveAuthentication(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, callback);
                }
            });
        } else {
            IbtRealtimeRestServices.saveAuthentication(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, callback);
        }
    };

    /**
     * @function {public} presence Gets a json indicating the subscriptions in the specified channel and if active the first 100 unique metadata.
     * @param {object} Object literal with presence attributes.
     * @... {String} url Server containing the presence service (optional if connected).
     * @... {bool} isCluster Specifies if url is cluster (optional if connected).
     * @... {String} applicationKey Application key with access to presence service (optional if connected).
     * @... {String} authenticationToken Authentication token with access to presence service (optional if connected).
     * @... {String} channel Channel with presence data active.
     * @param {function} Callback with error and result parameters.
     * @returns void
     * 
     * </br>
     * <b class="codeSample">Code Sample:</b>
     *
     * <pre class="brush: js; gutter: false;">
     *      ortcClient.presence({
     *          applicationKey : 'ORTC_APPLICATION_KEY',
     *          authenticationToken : 'AUTHENTICATION_TOKEN',
     *          isCluster : true,
     *          url : 'http://ortc-developers.realtime.co/server/2.1/',
     *          channel : 'CHANNEL_WITH_ACTIVE_PRESENCE'
     *      },
     *      function(error,result){
     *          if(error){
     *              console.log('Presence error:',error);
     *          }else{
     *              if(result){
     *                  console.log('Subscriptions',result.subscriptions);  
     *
     *                  for(var metadata in result.metadata){
     *                      console.log(metadata,'-',result.metadata[metadata]);                                    
     *                  }
     *              }else{
     *                  console.log('Subscriptions empty'); 
     *              }                           
     *          }
     *      }); 
     * </pre>
     */
    this.presence = function (parameters,callback) {
        try{
            var requestUrl = null
            , isCluster = false
            , appKey = ortc.appKey
            , authToken = ortc.authToken;

            if(parameters.url){
                requestUrl = parameters.url;
                isCluster = parameters.isCluster;
                appKey = parameters.applicationKey;
                authToken = parameters.authenticationToken;
            }else{
                if (clusterUrl && clusterUrl != null) {
                    requestUrl = clusterUrl;
                    isCluster = true;
                }
                else {
                    requestUrl = url;
                }    
            }

            getServerUrl({
                requestUrl : requestUrl,
                isCluster : isCluster,
                appKey : appKey
            },
            function(error,serverUrl){
                if(error){
                    callback(error,null);
                }else{
                    IbtRealtimeRestServices.getPresence({
                        url : serverUrl,
                        appKey : appKey, 
                        authToken : authToken,
                        channel : parameters.channel
                    },callback);
                }
            });
        }catch(e){
            callback('Unable to get presence data ' + e,null);
        }
    };

    /**
     * @function {public} enablePresence Enables presence for the specified channel with first 100 unique metadata if true.
     * @param {object} Object literal with presence attributes.
     * @... {String} url Server containing the presence service (optional if connected).
     * @... {bool} isCluster Specifies if url is cluster (optional if connected).
     * @... {String} applicationKey Application key with access to presence service (optional if connected).
     * @... {String} privateKey The private key provided when the ORTC service is purchased.
     * @... {String} channel Channel to activate presence.
     * @... {bool} metadata Defines if to collect first 100 unique metadata.
     * @param {function} Callback with error and result parameters.
     * @returns void
     * 
     * </br>
     * <b class="codeSample">Code Sample:</b>
     *
     * <pre class="brush: js; gutter: false;">
     *      ortcClient.enablePresence({
     *          applicationKey : 'ORTC_APPLICATION_KEY',
     *          channel : 'CHANNEL_TO_ACTIVATE_PRESENCE', 
     *          privateKey : 'ORTC_PRIVATE_KEY', 
     *          url : 'http://ortc-developers.realtime.co/server/2.1/',
     *          isCluster : true,
                metadata : true
     *      },
     *      function(error,result){
     *          if(error){
     *              console.log('Presence',error);  
     *          }else{
     *              console.log('Presence enable',result);              
     *      }); 
     * </pre>
     */
    this.enablePresence = function (parameters,callback) {
        try{
            var requestUrl = null
            , isCluster = false
            , appKey = ortc.appKey;

            if(parameters.url){
                requestUrl = parameters.url;
                isCluster = parameters.isCluster;
                appKey = parameters.applicationKey;
            }else{
                if (clusterUrl && clusterUrl != null) {
                    requestUrl = clusterUrl;
                    isCluster = true;
                }
                else {
                    requestUrl = url;
                }    
            }

            getServerUrl({
                requestUrl : requestUrl,
                isCluster : isCluster,
                appKey : appKey
            },
            function(error,serverUrl){
                if(error){
                    callback(error,null);
                }else{
                    IbtRealtimeRestServices.enablePresence({
                        url : serverUrl,
                        appKey : appKey, 
                        privateKey : parameters.privateKey,
                        channel : parameters.channel,
                        metadata : parameters.metadata == true ? 1 : 0
                    },callback);
                }
            });
        }catch(e){
            callback('Unable to enable presence ' + e,null);
        }
    };

    /**
     * @function {public} disablePresence Disables presence for the specified channel.
     * @param {object} Object literal with presence attributes.
     * @... {String} url Server containing the presence service (optional if connected).
     * @... {bool} isCluster Specifies if url is cluster (optional if connected).
     * @... {String} applicationKey Application key with access to presence service (optional if connected).
     * @... {String} privateKey The private key provided when the ORTC service is purchased.
     * @... {String} channel Channel to disable presence.
     * @param {function} Callback with error and result parameters.
     * @returns void
     * 
     * </br>
     * <b class="codeSample">Code Sample:</b>
     *
     * <pre class="brush: js; gutter: false;">
     *      ortcClient.disablePresence({
     *          applicationKey : 'ORTC_APPLICATION_KEY',
     *          channel : 'CHANNEL_TO_ACTIVATE_PRESENCE', 
     *          privateKey : 'ORTC_PRIVATE_KEY', 
     *          url : 'http://ortc-developers.realtime.co/server/2.1/',
     *          isCluster : true
     *      },
     *      function(error,result){
     *          if(error){
     *              console.log('Presence',error);  
     *          }else{
     *              console.log('Presence enable',result);              
     *      }); 
     * </pre>
     */
    this.disablePresence = function (parameters,callback) {
        try{
            var requestUrl = null
            , isCluster = false
            , appKey = ortc.appKey;

            if(parameters.url){
                requestUrl = parameters.url;
                isCluster = parameters.isCluster;
                appKey = parameters.applicationKey;
            }else{
                if (clusterUrl && clusterUrl != null) {
                    requestUrl = clusterUrl;
                    isCluster = true;
                }
                else {
                    requestUrl = url;
                }    
            }

            getServerUrl({
                requestUrl : requestUrl,
                isCluster : isCluster,
                appKey : appKey
            },
            function(error,serverUrl){
                if(error){
                    callback(error,null);
                }else{
                    IbtRealtimeRestServices.disablePresence({
                        url : serverUrl,
                        appKey : appKey, 
                        privateKey : parameters.privateKey,
                        channel : parameters.channel
                    },callback);
                }
            });
        }catch(e){
            callback('Unable to disable presence ' + e,null);
        }
    };

    /***********************************************************
    * @private methods
    ***********************************************************/

    var getServerUrl = function(parameters,callback){
         if (parameters.requestUrl && parameters.isCluster) {
            var clusterUrl = ortcTreatUrl(parameters.requestUrl);

            getServerFromCluster({
                clusterUri : clusterUrl, 
                appKey : parameters.appKey
            }, 
            function (error, body) {
                if (error != null) {
                    callback('Error getting server from Cluster',null);
                }
                else {
                    var resultUrl = body.substring(body.indexOf('=') + 3, body.length - 2);
                    callback(null,resultUrl);
                }
            });
        }
        else {
            var resultUrl = ortcTreatUrl(parameters.requestUrl);
            callback(null,resultUrl);
        }
    };

    var clearReconnectInterval = function () {
        // Clear the reconnecting interval
        if (ortc.reconnectIntervalId) {
            clearInterval(ortc.reconnectIntervalId);
            ortc.reconnectIntervalId = null;
        }

        // Clear the reconnecting timeout
        if (ortc.reconnectTimeoutlId) {
            clearTimeout(ortc.reconnectTimeoutlId);
            ortc.reconnectTimeoutlId = null;
        }
    };

    var ortcIsValidUrl = function (input) {
        return (/^\s*(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?\s*$/).exec(input) ? true : false;
    };

    var ortcIsValidInput = function (input) {
        //regex
        //var regexPattern = (\/^[\\w-:s\/\\.]*$/);
        //var match = regexPattern.exec(input);
        //return match ? true : false;
        return true;
    };

    var ortcIsValidBoolean = function (input) {
        return (/^(true|false|0|1)$/).exec(input) ? true : false;
    };

    var ortcIsFunction = function (input) {
        return typeof (input) == 'function' ? true : false;
    };

    var ortcIsString = function (input) {
        return typeof (input) == 'string' ? true : false;
    };

    var ortcTreatUrl = function (url) {
        url = url.replace(/\s+/g, '');

        if (url.charAt(url.length - 1) == '/') {
            url = url.substring(0, url.length - 1);
        }

        return url;
    };

    /*
    * Generates an ID.
    */
    var generateId = function (size) {
        var result = '';

        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };

        for (var i = 0; i < size / 4; i++) {
            result += S4();
        }

        return result;
    };

    /*
    * Disconnects the socket.
    */
    var disconnectSocket = function () {
        reconnectStartedAt = null;
        isConnecting = false;
        if (ortc.sockjs && ortc.sockjs != null) {
            ortc.sockjs.close();
            ortc.sockjs = null;
        }
    };

    /*
    * Reconnects the socket.
    */
    var reconnectSocket = function (clusterTimeout) {
        clearReconnectInterval();

        if (isConnecting) {
            delegateExceptionCallback(ortc, 'Unable to connect...');
            disconnectSocket();
        }

        isConnecting = true;

        delegateReconnectingCallback(ortc);

        reconnectStartedAt = new Date().getTime();

        if (clusterUrl && clusterUrl != null) {
            clusterConnection(clusterTimeout);
        }
        else {
            ortc.sockjs = createSocketConnection(url);
        }

        if (!ortc.reconnectTimeoutlId) {
            // Timeout to reconnect
            ortc.reconnectTimeoutlId = setTimeout(function () {
                if (!isConnected) {
                    reconnectSocket(ortc.getConnectionTimeout());
                }
            }, ortc.getConnectionTimeout());
        }
    };

    /*
    * Tries a connection through the cluster gateway with the application key and authentication token.
    */
    var clusterConnection = function (clusterTimeout) {
        if (clusterUrl != null) {
            getServerFromCluster({
                clusterUri : clusterUrl, 
                clusterTimeout : clusterTimeout,
                appKey : ortc.appKey
            }, 
            function (error, body) {
                if (error != null) {
                    delegateExceptionCallback(ortc, 'Error getting server from Cluster');
                }
                else {
                    if (body.indexOf('SOCKET_SERVER') >= 0) {
                        url = body.substring(body.indexOf('=') + 3, body.length - 2);
                        sockjs = createSocketConnection(ortc.getUrl());
                    }
                }
            });
        }
    };

    /*
    * Gets server from the cluster.
    */
    var getServerFromCluster = function (parameters,callback) {
        var queryString = parameters.appKey ? 'appkey=' + parameters.appKey : "";

        var parsedUrl = urlParser.parse(parameters.clusterUri + '?' + queryString);
        
        httpRequest.get({
            url : parsedUrl.hostname,        
            path : parsedUrl.pathname,
            parameters : parsedUrl.query,
            callback : function(error,responseData){
                if (error != null) {
                    callback(error, null);
                }
                else {
                    callback(null, responseData.content);
                }
            }
        });
    };

    /*
    * Creates a socket connection.
    */
    var createSocketConnection = function (connectionUrl) {
        if (ortc.sockjs == null) {
            var wsScheme = 'ws';
            var wsUrl = connectionUrl;

            if (connectionUrl.substring(0, 7) == 'http://') {
                wsUrl = wsUrl.substring(7);
            }
            else if (connectionUrl.substring(0, 8) == 'https://') {
                wsUrl = wsUrl.substring(8);
                wsScheme = 'wss';
            }

            var connid = strings.random_string(8);
            var serverId = strings.random_number_string(1000);

            var socket = new IbtRealTimeWebSocket(wsScheme + '://' + wsUrl + '/broadcast/' + serverId + '/' + connid + '/websocket');
            ortc.sockjs = socket.connection(function () {
                // Update last keep alive time

                lastKeepAlive = new Date().getTime();
                if(ortc.sockjs){
                    ortc.sockjs.sendText(JSON.stringify('validate;' + ortc.appKey + ';' + ortc.authToken + ';' + (announcementSubChannel ? announcementSubChannel : '') + ';' + '' + ';' + (connectionMetadata ? connectionMetadata : '')));
                }

            });
            // Connect handler

            // Disconnect handler
            ortc.sockjs.on('close',function (code, reason) {
                ortc.sockjs = null;

                if (isConnected) {
                    isConnected = false;
                    isConnecting = false;
                    delegateDisconnectedCallback(ortc);
                }

                if (!stopReconnecting && (!reconnectStartedAt || (reconnectStartedAt + connectionTimeout < new Date().getTime()))) {
                    reconnectSocket(ortc.getConnectionTimeout());
                }
            });

            // Error handler (when connecting to an non existent server)
            ortc.sockjs.on('error', function (e) {

            });

            // Receive handler
            ortc.sockjs.on('text', function(m) {
                // Update last keep alive time
                lastKeepAlive = new Date().getTime();

                var messageType = m[0];

                switch (messageType) {
                    case 'o': // open
                        break;
                    case 'a': // message
                        var data = JSON.parse(JSON.parse(m.substring(1))[0]);
                        var op = data.op;

                        switch (op) {
                            case 'ortc-validated':
                                if (data.up) {
                                    userPerms = data.up; // user permissions
                                }

                                isConnecting = false;
                                isConnected = true;
                                reconnectStartedAt = null;

                                if (alreadyConnectedFirstTime) {
                                    var channelsToRemove = Object.create(null);

                                    // Subscribe to the previously subscribed channels
                                    for (var key in subscribedChannels) {
                                        // Subscribe again
                                        if (subscribedChannels[key].subscribeOnReconnected == true && (subscribedChannels[key].isSubscribing || subscribedChannels[key].isSubscribed)) {
                                            subscribedChannels[key].isSubscribing = true;
                                            subscribedChannels[key].isSubscribed = false;

                                            var domainChannelCharacterIndex = key.indexOf(':');
                                            var channelToValidate = key;
                                            var hashPerm = null;

                                            if (domainChannelCharacterIndex > 0) {
                                                channelToValidate = key.substring(0, domainChannelCharacterIndex + 1) + '*';
                                            }

                                            if (userPerms && userPerms != null) {
                                                hashPerm = userPerms[channelToValidate] ? userPerms[channelToValidate] : userPerms[key];
                                            }
                                            if(ortc.sockjs){
                                                ortc.sockjs.sendText(JSON.stringify('subscribe;' + ortc.appKey + ';' + ortc.authToken + ';' + key + ';' + hashPerm));
                                            }
                                        }
                                        else {
                                            channelsToRemove[key] = key;
                                        }
                                    }

                                    for (var chnKey in channelsToRemove) {                                        
                                        ObjectLiterals.removeEntry(subscribedChannels,chnKey);
                                    }

                                    // Clean messages buffer (can have lost message parts in memory)
                                    messagesBuffer = Object.create(null);

                                    delegateReconnectedCallback(ortc);
                                }
                                else {
                                    alreadyConnectedFirstTime = true;

                                    delegateConnectedCallback(ortc);
                                }

                                if (!ortc.reconnectIntervalId  && !stopReconnecting) {
                                    // Interval to reconnect
                                    ortc.reconnectIntervalId = setInterval(function () {
                                        if (lastKeepAlive != null && (lastKeepAlive + 35000 < new Date().getTime())) { // 35 seconds
                                            lastKeepAlive = null;

                                            // Server went down
                                            if (isConnected) {
                                                disconnectSocket();

                                                if (isConnected) {
                                                    isConnected = false;
                                                    isConnecting = false;

                                                    delegateDisconnectedCallback(ortc);

                                                    reconnectSocket(ortc.getConnectionTimeout());
                                                }
                                            }
                                        }
                                    }, ortc.getConnectionTimeout());
                                }

                                break;
                            case 'ortc-subscribed':
                                var channelSubscribed = data.ch;

                                if (subscribedChannels[channelSubscribed]) {
                                    subscribedChannels[channelSubscribed].isSubscribing = false;
                                    subscribedChannels[channelSubscribed].isSubscribed = true;
                                }

                                delegateSubscribedCallback(ortc, channelSubscribed)
                                break;
                            case 'ortc-unsubscribed':
                                var channelUnsubscribed = data.ch;

                                if (subscribedChannels[channelUnsubscribed]) {
                                    subscribedChannels[channelUnsubscribed].isSubscribing = false;
                                    subscribedChannels[channelUnsubscribed].isSubscribed = false;
                                }

                                delegateUnsubscribedCallback(ortc, channelUnsubscribed)
                                break;
                            case 'ortc-error':
                                var data = data.ex ? data.ex : data;
                                var operation = data.op;
                                var error = data.ex;

                                delegateExceptionCallback(ortc, error);
                                switch (operation) {
                                    case 'validate':
                                        if(error.indexOf("Unable to connect") > -1 || error.indexOf("Server is too busy") > -1){
                                            disconnectSocket();                                            
                                        }else{
                                            invalidConnection = true;

                                            // Stop the reconnecting process
                                            stopReconnecting = true;
                                            alreadyConnectedFirstTime = false;
                                            subscribedChannels = Object.create(null);
                                            clearReconnectInterval();
                                            
                                        }                                        
                                        break;
                                    case 'subscribe':
                                        if (channel && subscribedChannels[channel]) {
                                            subscribedChannels[channel].isSubscribing = false;
                                        }
                                        break;
                                    case 'subscribe_maxsize':
                                    case 'unsubscribe_maxsize':
                                    case 'send_maxsize':
                                        if (channel && subscribedChannels[channel]) {
                                            subscribedChannels[channel].isSubscribing = false;
                                        }

                                        // Stop the reconnecting process
                                        stopReconnecting = true;
                                        alreadyConnectedFirstTime = false;

                                        clearReconnectInterval();
                                        break;
                                    default:
                                        break;
                                }

                                if (stopReconnecting) {
                                    delegateDisconnectedCallback(ortc);
                                }
                                break;
                            default:
                                var channel = data.ch;
                                var message = data.m;

                                var messageId = null;
                                var messageCurrentPart = 1;
                                var messageTotalPart = 1;
                                var lastPart = false;

                                var a = message.split("_");

                                if(a.length < 2){
                                    //lastPart = true;
                                }else{
                                    if (a[0].length != 8) {
                                        //lastPart = true;
                                    }else{
                                        var b = a[1].split("-");
                                        if ((b[0] && b[1]) && (!isNaN(b[0]) && !isNaN(b[1]))) { 
                                            messageId = a[0];
                                            messageCurrentPart = parseInt(b[0], 10);
                                            messageTotalPart = parseInt(b[1], 10);

                                            message = '';
                                            for (var i = 2; i < a.length; i++) {
                                                if (i > 2) {
                                                    message += '_';
                                                };
                                                message += a[i];
                                            };
                                        };
                                    }
                                }


                                // Is a message part
                                if (messageId) {
                                    if (!messagesBuffer[messageId]) {
                                        messagesBuffer[messageId] = Object.create(null);
                                    }

                                    messagesBuffer[messageId][messageCurrentPart] = message;

                                    // Last message part
                                    if (Object.keys(messagesBuffer[messageId]).length == messageTotalPart) {
                                        lastPart = true;
                                    }
                                }
                                // Message does not have multipart, like the messages received at announcement channels
                                else {
                                    lastPart = true;
                                }

                                if (lastPart) {
                                    if (messageId) {
                                        message = '';

                                        for (var i = 1; i <= messageTotalPart; i++) {
                                            message += messagesBuffer[messageId][i];

                                            // Delete from messages buffer                                            
                                            ObjectLiterals.removeEntry(messagesBuffer[messageId],i)
                                        }

                                        // Delete from messages buffer
                                        ObjectLiterals.removeEntry(messagesBuffer,messageId);
                                    }
                                    delegateMessagesCallback(ortc, channel, message);
                                }
                                break;
                        }

                        break;
                    case 'h': // heartbeat
                        break;
                    default:
                        break;
                }
            });
        }

        return ortc.sockjs;
    };

    /*
    * Calls the onConnected callback if defined.
    */
    var delegateConnectedCallback = function (ortc) {
        if (ortc != null && ortc.onConnected != null) {
            ortc.onConnected(ortc);
        }
    };

    /*
    * Calls the onDisconnected callback if defined.
    */
    var delegateDisconnectedCallback = function (ortc) {
        if (ortc != null && ortc.onDisconnected != null) {
            ortc.onDisconnected(ortc);
        }
    };

    /*
    * Calls the onSubscribed callback if defined.
    */
    var delegateSubscribedCallback = function (ortc, channel) {
        if (ortc != null && ortc.onSubscribed != null && channel != null) {
            ortc.onSubscribed(ortc, channel);
        }
    };

    /*
    * Calls the onUnsubscribed callback if defined.
    */
    var delegateUnsubscribedCallback = function (ortc, channel) {
        if (ortc != null && ortc.onUnsubscribed != null && channel != null) {
            ortc.onUnsubscribed(ortc, channel);
        }
    };

    /*
    * Calls the onMessages callbacks if defined.
    */
    var delegateMessagesCallback = function (ortc, channel, message) {
        if (ortc != null && subscribedChannels[channel] && subscribedChannels[channel].isSubscribed && subscribedChannels[channel].onMessageCallback != null) {
            subscribedChannels[channel].onMessageCallback(ortc, channel, message);
        }
    };

    /*
    * Calls the onException callback if defined.
    */
    var delegateExceptionCallback = function (ortc, event) {
        if (ortc != null && ortc.onException != null) {
            ortc.onException(ortc, event);
        }
    };

    /*
    * Calls the onReconnecting callback if defined.
    */
    var delegateReconnectingCallback = function (ortc) {
        if (ortc != null && ortc.onReconnecting != null) {
            ortc.onReconnecting(ortc);
        }
    };

    /*
    * Calls the onReconnected callback if defined.
    */
    var delegateReconnectedCallback = function (ortc) {
        if (ortc != null && ortc.onReconnected != null) {
            ortc.onReconnected(ortc);
        }
    };
}
1237376
private SocketChannel createLeaderSocket(
            SocketAddress hostAddr,
            ConnectStrategy mode) throws IOException
    {
        SocketChannel socket;
        int connectAttempts = 0;
        do {
            try {
                socket = SocketChannel.open();
                socket.socket().connect(hostAddr, 5000);
            }
            catch (java.net.ConnectException
                  |java.nio.channels.UnresolvedAddressException
                  |java.net.NoRouteToHostException
                  |java.net.PortUnreachableException e)
            {
                // reset the socket to null for loop purposes
                socket = null;

                if (mode == ConnectStrategy.PROBE) {
                    return null;
                }
                if ((++connectAttempts % 8) == 0) {
                    LOG.warn("Joining primary failed: " + e + " retrying..");
                }
                try {
                    Thread.sleep(250); //  milliseconds
                }
                catch (InterruptedException dontcare) {}
            }
        } while (socket == null);
        return socket;
    }
2863
function Connection(uri) {
    this.channels = {};
    let version = require('../package.json').version;
    let opts = {
        query: 'instanceId=' + 'js_cli_' + version,
        'sync disconnect on unload': true,
        path: '/syncsocket'
    };
    this.socket = io.connect(uri, opts);
    this.bindEvents();
}
697840
def _open_data_stream(self):
        '''
        '''
        @asyncio.coroutine
        def connection_factory(address: Tuple[int, int]):
            self._data_connection = yield from self._acquire_connection(address[0], address[1])
            return self._data_connection

        self._data_stream = yield from self._commander.setup_data_stream(
            connection_factory
        )

        self._response.data_address = self._data_connection.address

        read_callback = functools.partial(self.event_dispatcher.notify, self.Event.transfer_receive_data)
        self._data_stream.data_event_dispatcher.add_read_listener(read_callback)

        write_callback = functools.partial(self.event_dispatcher.notify, self.Event.transfer_send_data)
        self._data_stream.data_event_dispatcher.add_write_listener(write_callback)
332158
function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) {

  function $WebSocket(url, protocols, options, wsOptions = {}) {
    if (!options && isObject(protocols) && !isArray(protocols)) {
      options = protocols;
      protocols = undefined;
    }
    this.wsOptions = wsOptions;
    this.protocols = protocols;
    this.url = url || 'Missing URL';
    this.ssl = /(wss)/i.test(this.url);

    // this.binaryType = '';
    // this.extensions = '';
    // this.bufferedAmount = 0;
    // this.trasnmitting = false;
    // this.buffer = [];

    // TODO: refactor options to use isDefined
    this.scope                       = options && options.scope                      || $rootScope;
    this.rootScopeFailover           = options && options.rootScopeFailover          && true;
    this.useApplyAsync               = options && options.useApplyAsync              || false;
    this.initialTimeout              = options && options.initialTimeout             || 500; // 500ms
    this.maxTimeout                  = options && options.maxTimeout                 || 5 * 60 * 1000; // 5 minutes
    this.reconnectIfNotNormalClose   = options && options.reconnectIfNotNormalClose  || false;
    this.binaryType                  = options && options.binaryType                 || 'blob';

    this._reconnectAttempts = 0;
    this.sendQueue          = [];
    this.onOpenCallbacks    = [];
    this.onMessageCallbacks = [];
    this.onErrorCallbacks   = [];
    this.onCloseCallbacks   = [];

    objectFreeze(this._readyStateConstants);

    if (url) {
      this._connect();
    } else {
      this._setInternalState(0);
    }

  }


  $WebSocket.prototype._readyStateConstants = {
    'CONNECTING': 0,
    'OPEN': 1,
    'CLOSING': 2,
    'CLOSED': 3,
    'RECONNECT_ABORTED': 4
  };

  $WebSocket.prototype._normalCloseCode = 1000;

  $WebSocket.prototype._reconnectableStatusCodes = [
    4000
  ];

  $WebSocket.prototype.safeDigest = function safeDigest(autoApply) {
    if (autoApply && !this.scope.$$phase) {
      this.scope.$digest();
    }
  };

  $WebSocket.prototype.bindToScope = function bindToScope(scope) {
    var self = this;
    if (scope) {
      this.scope = scope;
      if (this.rootScopeFailover) {
        this.scope.$on('$destroy', function() {
          self.scope = $rootScope;
        });
      }
    }
    return self;
  };

  $WebSocket.prototype._connect = function _connect(force) {
    if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) {
      this.socket = $websocketBackend.create(this.url, this.protocols, this.wsOptions);
      this.socket.onmessage = angular.bind(this, this._onMessageHandler);
      this.socket.onopen  = angular.bind(this, this._onOpenHandler);
      this.socket.onerror = angular.bind(this, this._onErrorHandler);
      this.socket.onclose = angular.bind(this, this._onCloseHandler);
      this.socket.binaryType = this.binaryType;
    }
  };

  $WebSocket.prototype.fireQueue = function fireQueue() {
    while (this.sendQueue.length && this.socket.readyState === this._readyStateConstants.OPEN) {
      var data = this.sendQueue.shift();

      this.socket.send(
        isString(data.message) || this.binaryType != 'blob' ? data.message : JSON.stringify(data.message)
      );
      data.deferred.resolve();
    }
  };

  $WebSocket.prototype.notifyOpenCallbacks = function notifyOpenCallbacks(event) {
    for (var i = 0; i < this.onOpenCallbacks.length; i++) {
      this.onOpenCallbacks[i].call(this, event);
    }
  };

  $WebSocket.prototype.notifyCloseCallbacks = function notifyCloseCallbacks(event) {
    for (var i = 0; i < this.onCloseCallbacks.length; i++) {
      this.onCloseCallbacks[i].call(this, event);
    }
  };

  $WebSocket.prototype.notifyErrorCallbacks = function notifyErrorCallbacks(event) {
    for (var i = 0; i < this.onErrorCallbacks.length; i++) {
      this.onErrorCallbacks[i].call(this, event);
    }
  };

  $WebSocket.prototype.onOpen = function onOpen(cb) {
    this.onOpenCallbacks.push(cb);
    return this;
  };

  $WebSocket.prototype.onClose = function onClose(cb) {
    this.onCloseCallbacks.push(cb);
    return this;
  };

  $WebSocket.prototype.onError = function onError(cb) {
    this.onErrorCallbacks.push(cb);
    return this;
  };


  $WebSocket.prototype.onMessage = function onMessage(callback, options) {
    if (!isFunction(callback)) {
      throw new Error('Callback must be a function');
    }

    if (options && isDefined(options.filter) && !isString(options.filter) && !(options.filter instanceof RegExp)) {
      throw new Error('Pattern must be a string or regular expression');
    }

    this.onMessageCallbacks.push({
      fn: callback,
      pattern: options ? options.filter : undefined,
      autoApply: options ? options.autoApply : true
    });
    return this;
  };

  $WebSocket.prototype._onOpenHandler = function _onOpenHandler(event) {
    this._reconnectAttempts = 0;
    this.notifyOpenCallbacks(event);
    this.fireQueue();
  };

  $WebSocket.prototype._onCloseHandler = function _onCloseHandler(event) {
    var self = this;
    if (self.useApplyAsync) {
      self.scope.$applyAsync(function() {
        self.notifyCloseCallbacks(event);
      });
    } else {
      self.notifyCloseCallbacks(event);
      self.safeDigest(true);
    }
    if ((this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode) || this._reconnectableStatusCodes.indexOf(event.code) > -1) {
      this.reconnect();
    }
  };

  $WebSocket.prototype._onErrorHandler = function _onErrorHandler(event) {
    var self = this;
    if (self.useApplyAsync) {
      self.scope.$applyAsync(function() {
        self.notifyErrorCallbacks(event);
      });
    } else {
      self.notifyErrorCallbacks(event);
      self.safeDigest(true);
    }
  };

  $WebSocket.prototype._onMessageHandler = function _onMessageHandler(message) {
    var pattern;
    var self = this;
    var currentCallback;
    for (var i = 0; i < self.onMessageCallbacks.length; i++) {
      currentCallback = self.onMessageCallbacks[i];
      pattern = currentCallback.pattern;
      if (pattern) {
        if (isString(pattern) && message.data === pattern) {
          applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message);
        }
        else if (pattern instanceof RegExp && pattern.exec(message.data)) {
          applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message);
        }
      }
      else {
        applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message);
      }
    }

    function applyAsyncOrDigest(callback, autoApply, args) {
      args = arraySlice.call(arguments, 2);
      if (self.useApplyAsync) {
        self.scope.$applyAsync(function() {
          callback.apply(self, args);
        });
      } else {
        callback.apply(self, args);
        self.safeDigest(autoApply);
      }
    }

  };

  $WebSocket.prototype.close = function close(force) {
    if (force || !this.socket.bufferedAmount) {
      this.socket.close();
    }
    return this;
  };

  $WebSocket.prototype.send = function send(data) {
    var deferred = $q.defer();
    var self = this;
    var promise = cancelableify(deferred.promise);

    if (self.readyState === self._readyStateConstants.RECONNECT_ABORTED) {
      deferred.reject('Socket connection has been closed');
    }
    else {
      self.sendQueue.push({
        message: data,
        deferred: deferred
      });
      self.fireQueue();
    }

    // Credit goes to @btford
    function cancelableify(promise) {
      promise.cancel = cancel;
      var then = promise.then;
      promise.then = function() {
        var newPromise = then.apply(this, arguments);
        return cancelableify(newPromise);
      };
      return promise;
    }

    function cancel(reason) {
      self.sendQueue.splice(self.sendQueue.indexOf(data), 1);
      deferred.reject(reason);
      return self;
    }

    if ($websocketBackend.isMocked && $websocketBackend.isMocked() &&
            $websocketBackend.isConnected(this.url)) {
      this._onMessageHandler($websocketBackend.mockSend());
    }

    return promise;
  };

  $WebSocket.prototype.reconnect = function reconnect() {
    this.close();

    var backoffDelay = this._getBackoffDelay(++this._reconnectAttempts);

    var backoffDelaySeconds = backoffDelay / 1000;
    console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds');

    $timeout(angular.bind(this, this._connect), backoffDelay);

    return this;
  };
  // Exponential Backoff Formula by Prof. Douglas Thain
  // http://dthain.blogspot.co.uk/2009/02/exponential-backoff-in-distributed.html
  $WebSocket.prototype._getBackoffDelay = function _getBackoffDelay(attempt) {
    var R = Math.random() + 1;
    var T = this.initialTimeout;
    var F = 2;
    var N = attempt;
    var M = this.maxTimeout;

    return Math.floor(Math.min(R * T * Math.pow(F, N), M));
  };

  $WebSocket.prototype._setInternalState = function _setInternalState(state) {
    if (Math.floor(state) !== state || state < 0 || state > 4) {
      throw new Error('state must be an integer between 0 and 4, got: ' + state);
    }

    // ie8 wat
    if (!objectDefineProperty) {
      this.readyState = state || this.socket.readyState;
    }
    this._internalConnectionState = state;


    forEach(this.sendQueue, function(pending) {
      pending.deferred.reject('Message cancelled due to closed socket connection');
    });
  };

  // Read only .readyState
  if (objectDefineProperty) {
    objectDefineProperty($WebSocket.prototype, 'readyState', {
      get: function() {
        return this._internalConnectionState || this.socket.readyState;
      },
      set: function() {
        throw new Error('The readyState property is read-only');
      }
    });
  }

  return function(url, protocols, options) {
    return new $WebSocket(url, protocols, options);
  };
}
613812
@Override
    public synchronized ChainData createOutboundChain() throws ChannelFrameworkException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "createOutboundChain");
        }

        // Check to see if the chain has already been created.
        if (outboundChainData == null) {
            this.outboundChainData = framework.createOutboundChain(this);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "createOutboundChain");
        }
        return this.outboundChainData;
    }
1347014
function RootContext(argv, profileFilenames, view) {
  var self = {
      commands: COMMANDS, // Overwritten when interactive
      profileFilenames: profileFilenames,
      interactive: false,
      argv: argv,
      view: view,
      config: null,
      nick: null,
      privkey: null,
      hubClient: null,
      voxClient: null,
  };

  self.initWithConfig = function(config) {
    if (self.voxClient) {
      throw new Error('Already initialized!');
    }

    self.config = config;
    self.nick = config.nick;

    self.voxClient = new VoxClient({
        config: config,
        agentString: AGENT_STRING,
    });
    return self.voxClient.connect();
  }

  self.reinitWithConfig = function(config) {
    self.close();
    return self.initWithConfig(config);
  }

  self.close = function() {
    if (self.voxClient) {
      self.voxClient.close();
      self.voxClient = null;
    }
  }

  /**
   * Logs connection status events.
   */
  self.listenForConnectionStatusEvents = function() {
    self.voxClient.on('connect', function(info) {
      self.view.log(colors.cyan.dim('Connected: ' + info.interchangeUrl));
    });
    self.voxClient.on('disconnect', function(info) {
      self.view.log(colors.red.dim('Disconnected: ' + info.interchangeUrl));
    });
    self.voxClient.on('error', function(info) {
      self.view.log(colors.red.dim('Connection error: ' + info.interchangeUrl));
    });
    self.voxClient.on('reconnect_failed', function(info) {
      self.view.log(colors.red.dim('Reconnection failed: ' + info.interchangeUrl));
    });
  }

  self.printJson = function(obj_or_name, obj) {
    if (obj !== undefined) {
      self.view.log('%s %s', obj_or_name, JSON.stringify(obj));
    } else {
      self.view.log(JSON.stringify(obj_or_name));
    }
  }

  return self;
}
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));
    }
594037
function() {
    ws = new SockJS(location.pathname.split("index")[0] + 'socket');
    ws.onopen = function() {
        console.log("CONNECTED");
        if (!inIframe) {
            document.getElementById("footer").innerHTML = "<font color='#494'>"+ibmfoot+"</font>";
        }
        ws.send(JSON.stringify({action:"connected"}));
        onoffline();
    };
    ws.onclose = function() {
        console.log("DISCONNECTED");
        if (!inIframe) {
            document.getElementById("footer").innerHTML = "<font color='#900'>"+ibmfoot+"</font>";
        }
        setTimeout(function() { connect(); }, 2500);
    };
    ws.onmessage = function(e) {
        var data = JSON.parse(e.data);
        //console.log("DATA" typeof data,data);
        if (Array.isArray(data)) {
            //console.log("ARRAY");
            // map.closePopup();
            // var bnds= L.latLngBounds([0,0]);
            for (var prop in data) {
                if (data[prop].command) { doCommand(data[prop].command); delete data[prop].command; }
                if (data[prop].hasOwnProperty("name")) {
                    setMarker(data[prop]);
                    // bnds.extend(markers[data[prop].name].getLatLng());
                }
                else { console.log("SKIP A",data[prop]); }
            }
            // map.fitBounds(bnds.pad(0.25));
        }
        else {
            if (data.command) { doCommand(data.command); delete data.command; }
            if (data.hasOwnProperty("name")) { setMarker(data); }
            else if (data.hasOwnProperty("type")) { doGeojson(data); }
            else {
                console.log("SKIP",data);
                // if (typeof data === "string") { doDialog(data); }
                // else { console.log("SKIP",data); }
            }
        }
    };
}
28026
function SplashCtrl($scope, $location, $rootScope, $window, $timeout, $sce, 
                    _bind, _req, _socket) {

  /****************************************************************************/
  /* INITIALIZATION                                                           */
  /****************************************************************************/
  /* Handhsaking [modules] */
  _socket.emit('handshake', 'splash');
  _socket.emit('handshake', 'modules');

  /* Handhsaking [splash] */
  _socket.on('splash', function(state) {
    //console.log('========================================');
    //console.log(JSON.stringify(state, null, 2));
    //console.log('----------------------------------------');
    $scope.splash = state;
  });

  _socket.on('modules', function(state) {
    //console.log('========================================');
    //console.log(JSON.stringify(state, null, 2));
    //console.log('----------------------------------------');
    $scope.modules = state;
    if($scope.modules.length === 0) {
      $location.path("/onboarding");
    }
    else {
      $('.splash').css({ opacity: 1 });
    }
  });

}
1130311
function clientConnects(p) {
        var pList;
        var nPlayers;
        var waitTime;
        var widgetConfig;

        node.remoteSetup('page', p.id, {
            clearBody: true,
            title: { title: 'Welcome!', addToBody: true }
        });

        node.remoteSetup('widgets', p.id, {
            destroyAll: true,
            append: { 'WaitingRoom': {} }
        });

        if (waitRoom.isRoomOpen()) {
            console.log('Client connected to waiting room: ', p.id);

            // Mark code as used.
            channel.registry.markInvalid(p.id);

            pList = waitRoom.clients.player;
            nPlayers = pList.size();


            if (waitRoom.START_DATE) {
                waitTime = new Date(waitRoom.START_DATE).getTime() -
                    (new Date().getTime());
            }
            else if (waitRoom.MAX_WAIT_TIME) {
                waitTime = waitRoom.MAX_WAIT_TIME;
            }
            else {
                waitTime = null; // Widget won't start timer.
            }

            // Send the number of minutes to wait and all waitRoom settings.
            widgetConfig = waitRoom.makeWidgetConfig();
            widgetConfig.waitTime = waitTime;
            node.remoteSetup('waitroom', p.id, widgetConfig);

            console.log('NPL ', nPlayers);

            // Notify all players of new connection.
            node.say('PLAYERSCONNECTED', 'ROOM', nPlayers);

            // Start counting a timeout for max stay in waiting room.
            waitRoom.makeTimeOut(p.id, waitTime);

            // Wait for all players to connect.
            if (nPlayers < waitRoom.POOL_SIZE) return;

            if (waitRoom.EXECUTION_MODE === 'WAIT_FOR_N_PLAYERS') {
                waitRoom.dispatch({
                    action: 'AllPlayersConnected',
                    exit: 0
                });
            }
        }
        else {
            node.say('ROOM_CLOSED', p.id);
        }
    }
1105426
function StatefulServerChannel(server, readable, writable, opts) {
  ServerChannel.call(this, server, opts);
  this._adapter = undefined;
  this._writable = writable.on('finish', onFinish);
  this._readable = readable.on('data', onHandshake).on('end', onEnd);

  this
    .once('_drain', function () {
      // Stop listening to incoming events.
      this._readable
        .removeListener('data', onHandshake)
        .removeListener('data', onRequest)
        .removeListener('end', onEnd);
    })
    .once('eot', function () {
      // Clean up any references to the channel on the underlying streams.
      this._writable.removeListener('finish', onFinish);
      if (this._endWritable) {
        this._writable.end();
      }
    });

  var self = this;

  function onHandshake(obj) {
    var id = obj.id;
    if (!self._matchesPrefix(id)) {
      return;
    }
    var buf = Buffer.concat(obj.payload);
    var err;
    try {
      var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf);
      var hreq = parts.head;
      self._adapter = self._getAdapter(hreq);
    } catch (cause) {
      err = toRpcError('INVALID_HANDSHAKE_REQUEST', cause);
    }
    var hres = self._createHandshakeResponse(err, hreq);
    self.emit('handshake', hreq, hres);
    if (err) {
      // Either the client's protocol was unknown or it isn't compatible.
      done(self._encodeSystemError(err));
    } else {
      self._readable
        .removeListener('data', onHandshake)
        .on('data', onRequest);
      self._receive(parts.tail, self._adapter, done);
    }

    function done(resBuf) {
      if (self.destroyed) {
        return;
      }
      self._writable.write({
        id: id,
        payload: [HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf]
      });
    }
  }

  function onRequest(obj) {
    // These requests are not prefixed with handshakes.
    var id = obj.id;
    if (!self._matchesPrefix(id)) {
      return;
    }
    var reqBuf = Buffer.concat(obj.payload);
    self._receive(reqBuf, self._adapter, function (resBuf, oneWay) {
      if (self.destroyed || oneWay) {
        return;
      }
      self._writable.write({id: id, payload: [resBuf]});
    });
  }

  function onEnd() { self.destroy(); }

  function onFinish() { self.destroy(true); }
}
997408
def _low_level_dispatch(pcapdev, devname, pktqueue):
        '''
        
        '''
        while LLNetReal.running:
            # a non-zero timeout value is ok here; this is an
            # independent thread that handles input for this
            # one pcap device.  it throws any packets received
            # into the shared queue (which is read by the actual
            # user code)
            pktinfo = pcapdev.recv_packet(timeout=0.2)
            if pktinfo is None:
                continue
            pktqueue.put( (devname,pcapdev.dlt,pktinfo) )

        log_debug("Receiver thread for {} exiting".format(devname))
        stats = pcapdev.stats()
        log_debug("Final device statistics {}: {} received, {} dropped, {} dropped/if".format(devname, stats.ps_recv, stats.ps_drop, stats.ps_ifdrop))
1330381
function (dispatchEvent) {
  this.dispatchEvent = dispatchEvent;
  this.name = null;
  this._setup = false;
  this.pc = freedom['core.peerconnection']();
  this.pc.on('onReceived', this.onData.bind(this));
  this.pc.on('onClose', this.onClose.bind(this));
  this.pc.on('onOpenDataChannel', this.onNewTag.bind(this));
  this._tags = [];
  // Maps tags to booleans. The boolean corresponding to a given tag
  // is true if this WebRTCTransportProvider is currently sending out
  // chunks of a message for that tag.
  this._sending = {};
  // Maps tags to lists of whole outgoing messages that are waiting to
  // be sent over the wire. Messages must be sent one at a time to
  // prevent the interleaving of chunks from two or messages.
  this._queuedMessages = {};
  // Entries in this dictionary map tags to arrays containing chunks
  // of incoming messages. If there is no entry for a tag in the
  // dictionary, then we have not received the first chunk of the next
  // message.
  this._chunks = {};
  // Messages may be limited to a 16KB length
  // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-07#section-6.6
  this._chunkSize = 15000;
  // The maximum amount of bytes we should allow to get queued up in
  // peerconnection, any more and we start queueing ourself.
  this._pcQueueLimit = 1024 * 250;
  // Javascript has trouble representing integers larger than 2^53 exactly
  this._maxMessageSize = Math.pow(2, 53);
}
1216127
function BasicConnection() {
  var _this = this

  this._disconnected = false
  this._messageHandler = function() {
  }
  this._disconnectHandler = function() {
  }

  var childArgs = []

  process.execArgv.forEach(function(arg) {
    if (arg.indexOf('--debug-brk') !== -1) {
      var _debugPort = parseInt(arg.substr(12)) + 1
      debug('Child process debugger listening on port %d', _debugPort)
      childArgs.push('--debug-brk=' + _debugPort)
    }
  })

  this._process = child_process.fork(__dirname + '/../sandbox/sandbox.js', childArgs)

  this._startHeartBeat()

  this._process.on('message', function(data) {
    var m = codec.decode(data);
    debug('Recibing message: %j', m)
    _this._messageHandler(m)
  })

  this._process.on('exit', function(m) {
    debug('Exit process: %j', m)
    _this._stopHeartBeat()
    _this._disconnected = true
    _this._disconnectHandler(m)
  })
}