Creates and configures web socket instance.

@param token                      Authentication token.
@param stateListenerWeakReference Weak reference to socket connection state callbacks.
505478
SocketInterface createSocket(@NonNull final String token, @NonNull final WeakReference<SocketStateListener> stateListenerWeakReference) {

        WebSocket socket = null;

        WebSocketFactory factory = new WebSocketFactory();

        // Configure proxy if provided
        if (proxyAddress != null) {
            ProxySettings settings = factory.getProxySettings();
            settings.setServer(proxyAddress);
        }

        try {
            socket = factory.createSocket(uri, TIMEOUT);
        } catch (IOException e) {
            log.f("Creating socket failed", e);
        }

        if (socket != null) {

            String header = AuthManager.AUTH_PREFIX + token;
            socket.addHeader("Authorization", header);

            socket.addListener(createWebSocketAdapter(stateListenerWeakReference));

            socket.setPingInterval(PING_INTERVAL);

            return new SocketWrapperImpl(socket);
        }

        return null;
    }
10492
public void setStateBackend(StateBackend backend) {
		if (backend != null) {
			try {
				InstantiationUtil.writeObjectToConfig(backend, this.config, STATE_BACKEND);
			} catch (Exception e) {
				throw new StreamTaskException("Could not serialize stateHandle provider.", e);
			}
		}
	}
1362258
@Trivial
    protected void setSslSupport(ServiceReference<ChannelFactoryProvider> ref) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.entry(this, tc, "setSslSupport", new Object[] { ref.getProperty("type"), ref });
        }

        // If sslsupport is bound then set it to true 
        _isSSLEnabled = true;

        // bind can get called before unbind for new config/ modify.Hence the precaution
        if (_sslFactoryProvider.getReference() != null) { // existing chain is still there so destroy 
            if (_isChainStarted)
                performAction(destroyChainAction);
        }

        _sslFactoryProvider.setReference(ref);
        // we will only invoke createchain if 
        // 1) activate() is complete
        // this is because bind method get called first before activate and without activate we don't have any properties
        // 2) if useSSL is set in config 
        if (_isActivated && _isSSLChain) {
            //TODO: when executor service is used for performaction() make sure about sequence of destroy and create chain
            //Now currently its not threaded
            if (_isChainStarted)
                performAction(destroyChainAction);
            performAction(createChainAction);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "setSslSupport", _isSSLEnabled);
        }
    }
707435
public void addTangoUserListener(ITangoUserListener listener, boolean stateless)
                throws DevFailed
    {
		event_listeners.add(ITangoUserListener.class, listener);
        event_identifier = subscribe_user_event(attr_name, filters, stateless);
    }
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}
1022507
@RequiresPermission(ACCESS_WIFI_STATE) public static Observable<WifiState> observeWifiStateChange(
      final Context context) {
    final IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    return Observable.create(new ObservableOnSubscribe<WifiState>() {
      @Override public void subscribe(final ObservableEmitter<WifiState> emitter) throws Exception {
        final BroadcastReceiver receiver = createWifiStateChangeReceiver(emitter);
        context.registerReceiver(receiver, filter);
        Disposable disposable = disposeInUiThread(new Action() {
          @Override public void run() {
            tryToUnregisterReceiver(context, receiver);
          }
        });

        emitter.setDisposable(disposable);
      }
    });
  }
553542
@Override
    public void processAuthorize(WebSocketChannel channel, String authorizeToken) {
        LOG.entering(CLASS_NAME, "processAuthorize");

        WebSocketNativeChannel nativeChannel = (WebSocketNativeChannel)channel;
        Proxy proxy = nativeChannel.getProxy();
        proxy.processEvent(XoaEventKind.AUTHORIZE, new String[] { authorizeToken });
    }
1292303
private Socket createConnectedSocket(final String url) {
		try {
			final Socket initSocket = IO.socket(url);

			final Callback callback = new Callback();
			
			initSocket.on(Socket.EVENT_CONNECT, callback);
			initSocket.on(Socket.EVENT_CONNECT_ERROR, callback);
			initSocket.on(Socket.EVENT_CONNECT_TIMEOUT, callback);
			initSocket.on(Socket.EVENT_CONNECT_ERROR, callback);
			initSocket.on(Socket.EVENT_DISCONNECT, callback);
			initSocket.on(Socket.EVENT_ERROR, callback);
			
			// Be sure that the emit/ack is synchronous to get the filters before the test are run
			LOGGER.finest("Connection to Probe Dock RT"); // Unable to use the logger into the run method
			new Thread(new Runnable() {
				@Override
				public void run() {
					initSocket.connect();
				}
			}).start();
			
			synchronized (callback) {
				callback.wait();
			}

			if (!initSocket.connected()) {
				LOGGER.warning("Probe Dock RT is not available");
				return null;
			}
			
			return initSocket;
		}
		catch (URISyntaxException | InterruptedException e) {
			LOGGER.log(Level.WARNING, "Unknown error", e);
		}
		
		return null;
	}
49528
private synchronized void setChannelState(String channelName, RuntimeState state) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "setChannelState channelName=" + channelName + ", state=" + state.ordinal);
        }
        if (null != channelName) {
            ChannelContainer channelContainer = this.channelRunningMap.get(channelName);
            if (null != channelContainer) {
                channelContainer.setState(state);
            }
        }
    }
1157033
function SnowflakeService(connectionConfig, httpClient, config)
{
  // validate input
  Errors.assertInternal(Util.isObject(connectionConfig));
  Errors.assertInternal(Util.isObject(httpClient));
  Errors.assertInternal(!Util.exists(config) || Util.isObject(config));

  // if a config object was specified, verify
  // that it has all the information we need
  var tokenInfoConfig;
  if (Util.exists(config))
  {
    Errors.assertInternal(Util.isObject(config));
    Errors.assertInternal(Util.isObject(config.tokenInfo));

    tokenInfoConfig = config.tokenInfo;
  }

  // create a new TokenInfo instance
  var tokenInfo = new TokenInfo(tokenInfoConfig);

  // create state objects for all the different states we can be in
  var stateOptions =
  {
    snowflakeService : this,
    httpClient       : httpClient,
    connectionConfig : connectionConfig,
    tokenInfo        : tokenInfo
  };
  var statePristine     = new StatePristine(stateOptions);
  var stateConnecting   = new StateConnecting(stateOptions);
  var stateConnected    = new StateConnected(stateOptions);
  var stateRenewing     = new StateRenewing(stateOptions);
  var stateDisconnected = new StateDisconnected(stateOptions);

  var currentState;

  /**
   * Transitions to a given state.
   *
   * @param {Object} state
   * @param {Object} [transitionContext]
   */
  var transitionTo = function(state, transitionContext)
  {
    // this check is necessary to make sure we don't re-enter a transient state
    // like Renewing when we're already in it
    if (currentState !== state)
    {
      // if we have a current state, exit it; the null check is necessary
      // because the currentState is undefined at bootstrap time when we
      // transition to the first state
      if (currentState)
      {
        currentState.exit();
      }

      // update the current state
      currentState = state;

      // enter the new state
      currentState.enter(transitionContext);
    }
  };

  /**
   * Transitions to the Pristine state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToPristine = function(transitionContext)
  {
    transitionTo(statePristine, transitionContext);
  };

  /**
   * Transitions to the Connecting state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToConnecting = function(transitionContext)
  {
    transitionTo(stateConnecting, transitionContext);
  };

  /**
   * Transitions to the Connected state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToConnected = function(transitionContext)
  {
    transitionTo(stateConnected, transitionContext);
  };

  /**
   * Transitions to the Renewing state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToRenewing = function(transitionContext)
  {
    transitionTo(stateRenewing, transitionContext);
  };

  /**
   * Transitions to the Disconnected state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToDisconnected = function(transitionContext)
  {
    transitionTo(stateDisconnected, transitionContext);

    // clear the tokens because we're in a fatal state and we don't want the
    // tokens to be available via getConfig() anymore
    tokenInfo.clearTokens();
  };

  /**
   * Returns a configuration object that can be passed to the SnowflakeService
   * constructor to get an equivalent SnowflakeService object.
   *
   * @returns {Object}
   */
  this.getConfig = function()
  {
    return {
      tokenInfo: tokenInfo.getConfig()
    };
  };

  /**
   * Establishes a connection to Snowflake.
   *
   * @param {Object} options
   */
  this.connect = function(options)
  {
    new OperationConnect(options).validate().execute();
  };

  /**
   * Issues a connect-continue request to Snowflake.
   *
   * @param {Object} [options]
   */
  this.continue = function(options)
  {
    new OperationContinue(options).validate().execute();
  };

  /**
   * Issues a generic request to Snowflake.
   *
   * @param {Object} options
   */
  this.request = function(options)
  {
    new OperationRequest(options).validate().execute();
  };

  /**
   * Terminates the current connection to Snowflake.
   *
   * @param {Object} options
   */
  this.destroy = function(options)
  {
    new OperationDestroy(options).validate().execute();
  };

  /**
   * Creates a new OperationAbstract.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationAbstract(options)
  {
    this.options = options;
  }

  /**
   * Validates the operation options.
   *
   * @returns {Object} the operation.
   */
  OperationAbstract.prototype.validate = function()
  {
    return this;
  };

  /**
   * Executes the operation.
   */
  OperationAbstract.prototype.execute = function(){};

  /**
   * Creates a new OperationConnect.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationConnect(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationConnect, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationConnect.prototype.validate = function()
  {
    // verify that the options object contains a callback function
    var options = this.options;
    Errors.assertInternal(
        (Util.isObject(options) && Util.isFunction(options.callback)));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationConnect.prototype.execute = function()
  {
    currentState.connect(this.options);
  };

  /**
   * Creates a new OperationContinue.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationContinue(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationContinue, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationContinue.prototype.validate = function()
  {
    // verify that the options contain a json object
    var options = this.options;
    Errors.assertInternal(
        Util.isObject(options) && Util.isObject(options.json));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationContinue.prototype.execute = function()
  {
    currentState.continue(this.options);
  };

  /**
   * Creates a new OperationRequest.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationRequest(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationRequest, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationRequest.prototype.validate = function()
  {
    // verify that the options object contains all the necessary information
    var options = this.options;
    Errors.assertInternal(Util.isObject(options));
    Errors.assertInternal(Util.isString(options.method));
    Errors.assertInternal(
        !Util.exists(options.headers) || Util.isObject(options.headers));
    Errors.assertInternal(Util.isString(options.url));
    Errors.assertInternal(
        !Util.exists(options.json) || Util.isObject(options.json));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationRequest.prototype.execute = function()
  {
    currentState.request(this.options);
  };

  /**
   * Creates a new OperationDestroy.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationDestroy(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationDestroy, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationDestroy.prototype.validate = function()
  {
    // verify that the options object contains a callback function
    var options = this.options;
    Errors.assertInternal(Util.isObject(options) &&
        Util.isFunction(options.callback));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationDestroy.prototype.execute = function()
  {
    // delegate to current state
    currentState.destroy(this.options);
  };

  /* All queued operations will be added to this array */
  var operationQueue = [];

  /**
   * Appends a request operation to the queue.
   *
   * @param {Object} options
   */
  this.enqueueRequest = function(options)
  {
    operationQueue.push(new OperationRequest(options));
  };

  /**
   * Appends a destroy operation to the queue.
   *
   * @param {Object} options
   */
  this.enqueueDestroy = function(options)
  {
    operationQueue.push(new OperationDestroy(options));
  };

  /**
   * Executes all the operations in the queue.
   */
  this.drainOperationQueue = function()
  {
    // execute all the operations in the queue
    for (var index = 0, length = operationQueue.length; index < length; index++)
    {
      operationQueue[index].execute();
    }

    // empty the queue
    operationQueue.length = 0;
  };

  this.isConnected = function()
  {
    return currentState === stateConnected;
  };

  this.getServiceName = function()
  {
    return Parameters.getValue(Parameters.names.SERVICE_NAME);
  };

  this.getClientSessionKeepAlive = function()
  {
    return Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE);
  };

  this.getClientSessionKeepAliveHeartbeatFrequency = function()
  {
    return Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY);
  };

  // if we don't have any tokens, start out as pristine
  if (tokenInfo.isEmpty())
  {
    this.transitionToPristine();
  }
  else
  {
    // we're already connected
    this.transitionToConnected();
  }
}
363732
public static void initialize(String token) {
    if (token == null) {
      throw new IllegalArgumentException("Token should be defined.");
    }
    initialize(new ClientProperties(token, null, null));
  }
28150
Observable<ComapiResult<String>> doCreateFbOptInState(@NonNull final String token) {
        return wrapObservable(service.createFbOptInState(AuthManager.addAuthPrefix(token), apiSpaceId, new Object()).map(mapToComapiResult()), log, "Creating fb opt in state.");
    }
371193
public void onStateChange() {
        switch (dataChannel.state()) {
            case CONNECTING:
                break;

            case OPEN: {
                    if (null != callReference) {
                        RespokeCall call = callReference.get();
                        if (null != call) {
                            call.directConnectionDidOpen(this);
                        }
                    }

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        if (null != listenerReference) {
                            Listener listener = listenerReference.get();
                            if (null != listener) {
                                listener.onOpen(RespokeDirectConnection.this);
                            }
                        }
                    }
                });
                }
                break;

            case CLOSING:
                break;

            case CLOSED: {
                    if (null != callReference) {
                        RespokeCall call = callReference.get();
                        if (null != call) {
                            call.directConnectionDidClose(this);
                        }
                    }

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {
                            if (null != listenerReference) {
                                Listener listener = listenerReference.get();
                                if (null != listener) {
                                    listener.onClose(RespokeDirectConnection.this);
                                }
                            }
                        }
                    });
                }
                break;
        }
    }
1295333
@Override
  public void onFailure(WebSocket webSocket, Throwable t, Response response) {
    socketOpen = false;
    if (t instanceof Exception) {
      callback.onError((Exception) t);
    } else {
      callback.onError(new Exception(t));
    }
  }
416370
public synchronized void notifySSLConfigChangeListener(String alias, String state) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "notifySSLConfigChangeListener", new Object[] { alias, state });

        if (alias != null) {
            List<SSLConfigChangeListener> listenerList = sslConfigListenerMap.get(alias);

            if (listenerList != null && listenerList.size() > 0) {
                SSLConfigChangeListener[] listenerArray = listenerList.toArray(new SSLConfigChangeListener[listenerList.size()]);

                for (int i = 0; i < listenerArray.length; i++) {
                    SSLConfigChangeEvent event = null;

                    // get the event associated with the listener
                    event = sslConfigListenerEventMap.get(listenerArray[i]);

                    if (event != null) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                            Tr.debug(tc, "Notifying listener[" + i + "]: " + listenerArray[i].getClass().getName());
                        event.setState(state);
                        SSLConfig changedConfig = sslConfigMap.get(alias);
                        event.setChangedSSLConfig(changedConfig);
                        listenerArray[i].stateChanged(event);

                        if (state.equals(Constants.CONFIG_STATE_DELETED)) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                Tr.debug(tc, "Deregistering event for listener.");
                            sslConfigListenerEventMap.remove(listenerArray[i]);
                        }
                    }
                }

                if (state.equals(Constants.CONFIG_STATE_DELETED)) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Deregistering all listeners for this alias due to alias deletion.");
                    sslConfigListenerMap.remove(alias);
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "notifySSLConfigChangeListener");
    }
206040
@Override
	public WebsocketSender uri(String uri) {
		return new WebsocketFinalizer(cachedConfiguration.bootstrap(b -> HttpClientConfiguration.uri(b, uri)));
	}
233849
def state_listener(self, state):
        '''
        
        '''
        if state == KazooState.SUSPENDED:
            self.set_valid(False)
            self.call_error(self.BAD_CONNECTION)
        elif state == KazooState.LOST and not self.do_not_restart:
            self.threaded_start()
        elif state == KazooState.CONNECTED:
            # This is going to throw a SUSPENDED kazoo error
            # which will cause the sessions to be wiped and re established.
            # Used b/c of massive connection pool issues
            self.zoo_client.stop()