Start the request to retrieve the access token using client-credentials grant. The optionally provided callback
will be called with the Token when it is available.

@param callback optional callback
@return Future
498269
public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(
            OAuthAsyncRequestCallback<OAuth2AccessToken> callback) {
        final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(null);

        return sendAccessTokenRequestAsync(request, callback);
    }
379931
def access_token():
    """"""
    client = Client.query.filter_by(
        client_id=request.form.get('client_id')
    ).first()

    if not client:
        abort(404)

    if not client.is_confidential and \
            'client_credentials' == request.form.get('grant_type'):
        error = InvalidClientError()
        response = jsonify(dict(error.twotuples))
        response.status_code = error.status_code
        abort(response)

    # Return None or a dictionary. Dictionary will be merged with token
    # returned to the client requesting the access token.
    # Response is in application/json
    return None
1228611
@Override
    void doLogin(String authUrl, final Callback<TokenInfo, Throwable> callback) {
        if (window != null && window.isOpen()) {
            callback.onFailure(new IllegalStateException("Authentication in progress"));
        } else {
            window = openWindow(authUrl, height, width);
            if (window == null) {
                callback.onFailure(new RuntimeException(
                        "The authentication popup window appears to have been blocked"));
            }
            // Workaround to check if the user has closed the auth window,
            // since neither the onclose and onunload events work the expected way in this scenario
            window.setFinished(false);
            new Timer() {
                @Override
                public void run() {
                    if (window.hasFinished())
                        cancel();
                    if (!window.isOpen()) {
                        window.setFinished(true);
                        callback.onFailure(new RuntimeException("User has closed the authentication window."));
                        cancel();
                    }
                }
            }.scheduleRepeating(300);
        }
    }
1270799
public function onReservationKeyReady(callable $callback = null)
    {
        if ($callback === null || is_callable($callback)) {
            $this->on_reservation_key_ready = $callback;
        } else {
            throw new InvalidArgumentException('Callable or NULL expected');
        }
    }
892006
public <T> AskFuture<T> ask(ActorSelection selection, long timeout, AskCallback<T> callback) {
        return askPattern.ask(system().actorOf(selection), timeout, callback);
    }
556462
public ListenableFuture<T> createAsync(final TwilioRestClient client) {
        return Twilio.getExecutorService().submit(new Callable<T>() {
            public T call() {
                return create(client);
            }
        });
    }
957749
public void startAuthorizationProcess(final Context context, ResponseListener listener) {
        authorizationQueue.add(listener);

        //start the authorization process only if this is the first time we ask for authorization
        if (authorizationQueue.size() == 1) {
            try {
                if (preferences.clientId.get() == null) {
                    logger.info("starting registration process");
                    invokeInstanceRegistrationRequest(context);
                } else {
                    logger.info("starting authorization process");
                    invokeAuthorizationRequest(context);
                }
            } catch (Throwable t) {
                handleAuthorizationFailure(t);
            }
        }

        else{
            logger.info("authorization process already running, adding response listener to the queue");
            logger.debug(String.format("authorization process currently handling %d requests", authorizationQueue.size()));
        }
    }
833490
public com.squareup.okhttp.Call getPingAsync(final ApiCallback<String> callback) throws ApiException {

        com.squareup.okhttp.Call call = getPingValidateBeforeCall(callback);
        Type localVarReturnType = new TypeToken<String>() {
        }.getType();
        apiClient.executeAsync(call, localVarReturnType, callback);
        return call;
    }
1216667
public Future<OAuth2AccessToken> getAccessToken(AccessTokenRequestParams params,
            OAuthAsyncRequestCallback<OAuth2AccessToken> callback) {
        return sendAccessTokenRequestAsync(createAccessTokenRequest(params), callback);
    }
1148740
public PermitAllocation getSync(ComplexResourceKey<PermitRequest, EmptyRecord> key) {
    try {
      FutureCallback<PermitAllocation> callback = new FutureCallback<>();

      get(key, callback);
      return callback.get();
    } catch (ExecutionException ee) {
      Throwable t = ee.getCause();
      if (t instanceof RestLiServiceException) {
        throw (RestLiServiceException) t;
      } else {
        throw new RuntimeException(t);
      }
    } catch (InterruptedException ie) {
      throw new RuntimeException(ie);
    }
  }
236791
public StoredCredential setAccessToken(String accessToken) {
    lock.lock();
    try {
      this.accessToken = accessToken;
    } finally {
      lock.unlock();
    }
    return this;
  }
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();
        }
    }
770671
public ClientCredentialsRequest.Builder clientCredentials() {
    return new ClientCredentialsRequest.Builder(clientId, clientSecret)
            .setDefaults(httpManager, scheme, host, port)
            .grant_type("client_credentials");
  }
419021
function requestWithTokenCheck (defOptions, credentials, token, options, callback) {
  var returnedPromise;
  
  options.headers = options.headers || {};
  extend(true, options, defOptions);
  
  if (Date.now() - token.Timestamp > tokenUpdateTime) {
    returnedPromise = signIn(defOptions, credentials).then(function (data) {
      if (data[0].statusCode !== 200) {
        throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`);
      } else {
        token.AuthenticationToken = data[0].body.AuthenticationToken;
        token.Timestamp = Date.now();
        options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
        return request(options);
      }
    });
  } else {
    options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
    returnedPromise = request(options);
  }
  
  returnedPromise.nodeify(callback);
  return returnedPromise;
}
912372
function getAccessToken(authCode, callback) {
	debug('Getting access token');
	var responseJSON;
	if (refreshToken.length > 0) {
		request.post(psnURL.oauth, {form:{ // Refreshing the token with refresh_token to avoid login again
				 'grant_type'	: 'refresh_token'
				,'client_id'	: psnVars.client_id
				,'client_secret': psnVars.client_secret
				,'refresh_token': refreshToken
				,'redirect_uri'	: psnVars.redirectURL_oauth
				,'state' 		: 'x'
				,'scope'		: psnVars.scope_psn
				,'duid' 		: psnVars.duid
			}}, function (error, response, body) {
				responseJSON = JSON.parse(body);
				if (!error) {
					if ('access_token' in responseJSON && !('error' in responseJSON)) {
						accessToken = responseJSON.access_token;
						refreshToken = responseJSON.refresh_token;
						debug('access_token obtained by using refresh_token: ' + accessToken)
						if (typeof callback === "function") callback();
					}
					else {
						debug('ERROR: ' + responseJSON)
					}
				}
				else {
					debug('ERROR: ' + error)
				}
		})
	}
	else {
		debug('Login for the first time');
		request.post(psnURL.oauth, {form:{ // Firts time login
				 'grant_type'	: 'authorization_code'
				,'client_id'	: psnVars.client_id
				,'client_secret': psnVars.client_secret
				,'code' 		: authCode
				,'redirect_uri'	: psnVars.redirectURL_oauth
				,'state' 		: 'x'
				,'scope'		: psnVars.scope_psn
				,'duid' 		: psnVars.duid
			}}, function (error, response, body) {
				responseJSON = JSON.parse(body);
				if (!error) {
					if ('access_token' in responseJSON && !('error' in responseJSON)) {
						accessToken = responseJSON.access_token;
						refreshToken = responseJSON.refresh_token;
						clearInterval(refreshInterval);
						refreshInterval = setInterval(function() {
							getAccessToken('', function() {
								debug('access_token refreshed after 59 minutes')
							})
						}, (responseJSON.expires_in - 60) * 1000) // 59 minutes
						debug('access_token/refresh_token obtained: ' + body);
						if (typeof callback === "function") callback();
					}
					else {
						debug('ERROR: ' + JSON.stringify(responseJSON))
					}
				}
				else {
					debug('ERROR: ' + JSON.stringify(error))
				}
		})	
	}
}
988985
@Override
	public Token retrieveToken() {

		log.debug("DefaultTokenProvider retrieveToken()");

		try {

			SSLContext sslContext;
			/*
			 * If SSL cert checking for endpoints has been explicitly disabled,
			 * register a new scheme for HTTPS that won't cause self-signed
			 * certs to error out.
			 */
			if (SDKGlobalConfiguration.isCertCheckingDisabled()) {
				if (log.isWarnEnabled()) {
					log.warn("SSL Certificate checking for endpoints has been " + "explicitly disabled.");
				}
				sslContext = SSLContext.getInstance("TLS");
				sslContext.init(null, new TrustManager[] { new TrustingX509TrustManager() }, null);
			} else {
				sslContext = SSLContexts.createDefault();
			}

			SSLConnectionSocketFactory sslsf = new SdkTLSSocketFactory(sslContext, new DefaultHostnameVerifier());

			HttpClientBuilder builder = HttpClientBuilder.create();	
			if (httpClientSettings != null){
				DefaultTokenManager.addProxyConfig(builder, httpClientSettings);
			}

			HttpClient client = builder.setSSLSocketFactory(sslsf).build();

			HttpPost post = new HttpPost(iamEndpoint);
			post.setHeader("Authorization", BASIC_AUTH);
			post.setHeader("Content-Type", CONTENT_TYPE);
			post.setHeader("Accept", ACCEPT);

			List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
			urlParameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
			urlParameters.add(new BasicNameValuePair("response_type", RESPONSE_TYPE));
			urlParameters.add(new BasicNameValuePair("apikey", apiKey));

			post.setEntity(new UrlEncodedFormEntity(urlParameters));

			final HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() != 200) {
				log.info("Response code= " + response.getStatusLine().getStatusCode()
						+ ", Reason= " + response.getStatusLine().getReasonPhrase()
						+ ".Throwing OAuthServiceException");
				OAuthServiceException exception = new OAuthServiceException("Token retrieval from IAM service failed");
				exception.setStatusCode(response.getStatusLine().getStatusCode());
				exception.setStatusMessage(response.getStatusLine().getReasonPhrase());
				throw exception;
			}

			final HttpEntity entity = response.getEntity();
			final String resultStr = EntityUtils.toString(entity);

			final ObjectMapper mapper = new ObjectMapper();

			final Token token = mapper.readValue(resultStr, Token.class);

			return token;

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}

		return null;

	}
956700
protected synchronized void requestCallback(Token tokenToPrePrepare)
                    throws ObjectManagerException
    {
        throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]);
    }