Asynchronously attempt to acquire an OAuth Access Token

@param cb called when AccessToken is acquired. Always called
on a background thread suitable for networking.
166573
protected void acquireAccessToken(final OAuthCallback cb) {
        if (isAccessTokenCached()) {
            // Execute the callback immediately with cached OAuth credentials
            if (VERBOSE) Log.d(TAG, "Access token cached");
            if (cb != null) {
                // Ensure networking occurs off the main thread
                // TODO: Use an ExecutorService and expose an application shutdown method to shutdown?
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        cb.onSuccess(getRequestFactoryFromCachedCredentials());
                    }
                }).start();
            }
        } else if (mOauthInProgress && cb != null) {
            // Add the callback to the queue for execution when outstanding OAuth negotiation complete
            mCallbackQueue.add(cb);
            if (VERBOSE) Log.i(TAG, "Adding cb to queue");
        } else {
            mOauthInProgress = true;
            // Perform an OAuth Client Credentials Request
            // TODO: Replace with new Thread()
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    TokenResponse response = null;
                    try {
                        if (VERBOSE)
                            Log.i(TAG, "Fetching OAuth " + mConfig.getAccessTokenRequestUrl());
                        response = new ClientCredentialsTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl(mConfig.getAccessTokenRequestUrl()))
                                .setGrantType("client_credentials")
                                .setClientAuthentication(new BasicAuthentication(mConfig.getClientId(), mConfig.getClientSecret()))
                                .execute();
                    } catch (IOException e) {
                        // TODO: Alert user Kickflip down
                        //       or client credentials invalid
                        if (cb != null) {
                            postExceptionToCallback(cb, e);
                        }
                        e.printStackTrace();
                    }
                    if (response != null) {
                        if (VERBOSE)
                            Log.i(TAG, "Got Access Token " + response.getAccessToken().substring(0, 5) + "...");
                        storeAccessToken(response);
                        mOauthInProgress = false;
                        if (cb != null)
                            cb.onSuccess(getRequestFactoryFromAccessToken(mStorage.getString(ACCESS_TOKEN_KEY, null)));
                        executeQueuedCallbacks();
                    } else {
                        mOauthInProgress = false;
                        Log.w(TAG, "Failed to get Access Token");
                    }
                    return null;
                }
            }.execute();
        }
    }
554361
public void write_attribute_asynch(final DeviceProxy deviceProxy,
	    final DeviceAttribute[] attribs, final CallBack cb) throws DevFailed {
        final int id = write_attribute_asynch(deviceProxy, attribs);
        ApiUtil.set_async_reply_model(id, CALLBACK);
        ApiUtil.set_async_reply_cb(id, cb);

        // if push callback, start a thread to do it
        if (ApiUtil.get_asynch_cb_sub_model() == PUSH_CALLBACK) {
            final AsyncCallObject aco = ApiUtil.get_async_object(id);
            new CallbackThread(aco).start();
        }
    }
132577
@Override
    public void registerEarlyRead(InterChannelCallback cb) {
        // LI4335.2
        if (null == cb) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "registerEarlyRead: Invalid null callback as input.");
            }
            throw new IllegalArgumentException("Callback is null");
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "App channel requesting early response read on " + getVC());
        }
        this.bEarlyReads = true;
        startEarlyRead(cb, true);
    }
616343
@Override
    public synchronized void processAuthorize(WebSocketChannel channel, String authorizeToken) {
        nextHandler.processAuthorize(channel, authorizeToken); 
    }
440021
@Override
    public void getOAuthRequestTokenAsync() {
        getDispatcher().invokeLater(new AsyncTask(OAUTH_REQUEST_TOKEN, listeners) {
            @Override
            public void invoke(List<TwitterListener> listeners) throws TwitterException {
                RequestToken token = twitter.getOAuthRequestToken();
                for (TwitterListener listener : listeners) {
                    try {
                        listener.gotOAuthRequestToken(token);
                    } catch (Exception e) {
                        logger.warn("Exception at getOAuthRequestTokenAsync", e);
                    }
                }
            }
        });
    }
230991
def add_synchronous_cb(self, cb):
        '''
        
        '''
        if self.connection.synchronous or self._synchronous:
            wrapper = SyncWrapper(cb)
            self._pending_events.append(wrapper)
            while wrapper._read:
                # Don't check that the channel has been closed until after
                # reading frames, in the case that this is processing a clean
                # channel closed. If there's a protocol error during
                # read_frames, this will loop back around and result in a
                # channel closed exception.
                if self.closed:
                    if self.close_info and \
                            len(self.close_info['reply_text']) > 0:
                        raise ChannelClosed(
                            "channel %d is closed: %s : %s",
                            self.channel_id,
                            self.close_info['reply_code'],
                            self.close_info['reply_text'])
                    raise ChannelClosed()
                self.connection.read_frames()

            return wrapper._result
        else:
            self._pending_events.append(cb)
1285071
public void askSubscribers( Actor sender, String topic, Object message, Callback cb ) {
        List<ReceiverActor> subscriber = topic2Subscriber.get(topic);
        if ( subscriber != null ) {
            List<IPromise> results = subscriber.stream()
                    .filter(subs -> !subs.equals(sender))
                    .map(subs -> subs.receiveAsk(topic, message))
                    .collect(Collectors.toList());
            try {
                all((List) results).await(5000); // is non-blocking
            } catch (Exception ex) {
                // timeout goes here
                Log.Info(this, "timeout in broadcast");
            }
            results.forEach( promise -> cb.pipe(promise.get()));
            cb.finish(); // important to release callback mapping in remoting !
        }
    }
445281
protected Future<OAuth2AccessToken> sendAccessTokenRequestAsync(OAuthRequest request,
            OAuthAsyncRequestCallback<OAuth2AccessToken> callback) {

        return execute(request, callback, new OAuthRequest.ResponseConverter<OAuth2AccessToken>() {
            @Override
            public OAuth2AccessToken convert(Response response) throws IOException {
                return getApi().getAccessTokenExtractor().extract(response);
            }
        });
    }
600839
@Override
  public void onConnect(URI serverHost) throws IOException {
    if (!StringUtils.isEmpty(accessToken)) {
      return; //No need to be called if accessToken is active.
    }

    try {
      getLog().info("Getting Oauth2 access token.");
      OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString())
          .setGrantType(GrantType.PASSWORD)
          .setClientId(clientId)
          .setClientSecret(clientSecret)
          .setUsername(userId)
          .setPassword(password + securityToken).buildQueryMessage();
      OAuthClient client = new OAuthClient(new URLConnectionClient());
      OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);

      accessToken = response.getAccessToken();
      setCurServerHost(new URI(response.getParam("instance_url")));
    } catch (OAuthProblemException e) {
      throw new NonTransientException("Error while authenticating with Oauth2", e);
    } catch (OAuthSystemException e) {
      throw new RuntimeException("Failed getting access token", e);
    } catch (URISyntaxException e) {
      throw new RuntimeException("Failed due to invalid instance url", e);
    }
  }
295270
@SuppressWarnings("unchecked")
  public <C extends CDACallback<SynchronizedSpace>> C fetch(C callback) {
    return (C) Callbacks.subscribeAsync(observe(), callback, client);
  }
197099
public void attachSession(List<ServiceInstanceToken> instanceTokens, final AttachSessionCallback cb, Object context){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.AttachSession);

        String sessionId = connection.getSessionId();
        AttachSessionProtocol protocol = new AttachSessionProtocol(instanceTokens, sessionId);
        ProtocolCallback pcb = new ProtocolCallback(){

            @Override
            public void call(boolean result, Response response,
                    ErrorCode error, Object ctx) {
                Map<ServiceInstanceToken, ItemResult> items = ((AttachSessionResponse)response).getAttachingResult();
                cb.call(result, items, error, ctx);
            }

        };

        connection.submitCallbackRequest(header, protocol, pcb, context);
    }
1190456
function _getToken(opts, cb) {
    assert.string(opts.indexName, 'opts.indexName'); // used for error messages
    assert.string(opts.realm, 'opts.realm');
    assert.optionalString(opts.service, 'opts.service');
    assert.optionalArrayOfString(opts.scopes, 'opts.scopes');
    assert.optionalString(opts.username, 'opts.username');
    assert.optionalString(opts.password, 'opts.password');
    // HTTP client opts:
    assert.object(opts.log, 'opts.log');
    assert.optionalObject(opts.agent, 'opts.agent');
    // assert.optional object or bool(opts.proxy, 'opts.proxy');
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.userAgent, 'opts.userAgent');
    var log = opts.log;

    // - add https:// prefix (or http) if none on 'realm'
    var tokenUrl = opts.realm;
    var match = /^(\w+):\/\//.exec(tokenUrl);
    if (!match) {
        tokenUrl = (opts.insecure ? 'http' : 'https') + '://' + tokenUrl;
    } else if (['http', 'https'].indexOf(match[1]) === -1) {
        return cb(new Error(fmt('unsupported scheme for ' +
            'WWW-Authenticate realm "%s": "%s"', opts.realm, match[1])));
    }

    // - GET $realm
    //      ?service=$service
    //      (&scope=$scope)*
    //      (&account=$username)
    //   Authorization: Basic ...
    var headers = {};
    var query = {};
    if (opts.service) {
        query.service = opts.service;
    }
    if (opts.scopes && opts.scopes.length) {
        query.scope = opts.scopes;  // intentionally singular 'scope'
    }

    if (opts.username) {
        query.account = opts.username;
        _setAuthHeaderFromAuthInfo(headers, {
            username: opts.username,
            password: opts.password
        });
    }
    if (Object.keys(query).length) {
        tokenUrl += '?' + querystring.stringify(query);
    }
    log.trace({tokenUrl: tokenUrl}, '_getToken: url');

    var parsedUrl = mod_url.parse(tokenUrl);
    var client = new DockerJsonClient({
        url: parsedUrl.protocol + '//' + parsedUrl.host,
        log: log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !opts.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    });
    client.get({
        path: parsedUrl.path,
        headers: headers
    }, function (err, req, res, body) {
        client.close();
        if (err) {
            if (err.statusCode === 401) {
                // Convert *all* 401 errors to use a generic error constructor
                // with a simple error message.
                var errMsg = _getRegistryErrorMessage(err);
                return cb(new errors.UnauthorizedError(errMsg));
            }
            return cb(err);
        } else if (!body.token) {
            return cb(new errors.UnauthorizedError(err, 'authorization ' +
                'server did not include a token in the response'));
        }
        cb(null, body.token);
    });
}
43471
function(cb) {
        var timeout;
        this.chain(function(next) {
            function evaluate() {
                var ccb = cb.bind(api);
                var result = ccb();
                if (result) {
                    clearInterval(poll);
                    if (timeout !== undefined) clearTimeout(timeout);
                    next();
                }
            }
            var api = this;
            var poll = setInterval(evaluate, api._untilInterval || 30);
            // to set a timeout for condition to be met, set the _untilTimeout property to ms value
            if (api.untilTimeout) {
                timeout = setTimeout(function() {
                    if (poll !== undefined) {
                        clearInterval(poll);
                        // to catch timeout of until conditions, set onUntilTimeout handler
                        if (api.onUntilTimeout) api.onUntilTimeout(next);
                        // otherwise execution flow simply continues as if condition was met
                        else next();
                    }
                }, api.untilTimeout);
            }
        });
        return this;
    }
176048
protected synchronized void retrieveToken() {

		log.debug("OAuthTokenManager.retrieveToken");

		if (token == null || (Long.valueOf(token.getExpiration()) < System.currentTimeMillis() / 1000L)) {

			log.debug("Token is null, retrieving initial token from provider");
			boolean tokenRequest = true;
			int retryCount = 0;

			while (tokenRequest && retryCount < this.iamMaxRetry) {
				try {
					++retryCount;
					token = provider.retrieveToken();
					tokenRequest = false;
				} catch (OAuthServiceException exception) {
					log.debug("Exception retrieving IAM token. Returned status code " + exception.getStatusCode()
							+ "Retry attempt " + retryCount);
					tokenRequest = shouldRetry(exception.getStatusCode()) ? true : false;
					if (!tokenRequest || retryCount == this.iamMaxRetry)
						throw exception;
				}
			}

			if(null == token) throw new OAuthServiceException("Null token returned by the Token Provider");

			cacheToken(token);
		}
	}
1210872
@Override
    public java.util.concurrent.Future<CreateAccessKeyResult> createAccessKeyAsync(
            com.amazonaws.handlers.AsyncHandler<CreateAccessKeyRequest, CreateAccessKeyResult> asyncHandler) {

        return createAccessKeyAsync(new CreateAccessKeyRequest(), asyncHandler);
    }
804858
public function onConnected($cb)
    {
        if ($this->state === self::CONN_STATE_HANDSHAKED_ERROR) {
            $cb($this);
        } elseif ($this->state === self::CONN_STATE_HANDSHAKED_OK) {
            $cb($this);
        } else {
            if (!$this->onConnected) {
                $this->onConnected = new StackCallbacks();
            }

            $this->onConnected->push($cb);
        }
    }
1133870
public Credential setAccessToken(String accessToken) {
    lock.lock();
    try {
      this.accessToken = accessToken;
    } finally {
      lock.unlock();
    }
    return this;
  }