pass the transfer details to aspera and receive back a
            populated transfer spec complete with access token
4292
def _create_transfer_spec(self, call_args):
        '''  '''
        _paths = []
        for _file_pair in call_args.file_pair_list:
            _path = OrderedDict()
            if call_args.direction == enumAsperaDirection.SEND:
                _action = "upload_setup"
                _path['source'] = _file_pair.fileobj
                _path['destination'] = _file_pair.key
            else:
                _action = "download_setup"
                _path['source'] = _file_pair.key
                _path['destination'] = _file_pair.fileobj
            _paths.append(_path)

        # Add credentials before the transfer spec is requested.
        delegated_token = self._delegated_token_manager.get_token()
        _response = self._fetch_transfer_spec(_action, delegated_token, call_args.bucket, _paths)

        tspec_dict = json.loads(_response.content)['transfer_specs'][0]['transfer_spec']

        tspec_dict["destination_root"] = "/"

        if (call_args.transfer_config):
            tspec_dict.update(call_args.transfer_config.dict)
            if call_args.transfer_config.is_multi_session_all:
                tspec_dict['multi_session'] = 0
                _remote_host = tspec_dict['remote_host'].split('.')
                # now we append '-all' to the remote host
                _remote_host[0] += "-all"
                tspec_dict['remote_host'] = ".".join(_remote_host)
                logger.info("New remote_host(%s)" % tspec_dict['remote_host'])

        call_args.transfer_spec = json.dumps(tspec_dict)

        return True
814857
def access_token(self):

        '''  '''

        title = '%s.access_token' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # construct request kwargs
        request_kwargs = {
            'url': self.token_endpoint,
            'data': {
                'client_id': self.client_id,
                'client_secret': self.client_secret,
                'grant_type': 'client_credentials'
            }
        }

    # send request
        try:
            current_time = time()
            response = requests.post(**request_kwargs)
        except Exception:
            if self.requests_handler:
                request_kwargs['method'] = 'POST'
                request_object = requests.Request(**request_kwargs)
                return self.requests_handler(request_object)
            else:
                raise

        response_details = self.response_handler.handle(response)

        if response_details['json']:
            self._access_token = response_details['json']['access_token']
            expires_in = response_details['json']['expires_in']
            self.expires_at = current_time + expires_in
            
        return self._access_token
1343034
def get_access_token(self, code, client_id, client_secret):
        ''' 
        
        '''
        headers = {
                'Content-Type' : 'application/json'
                }
        data = {
                'client_id' : client_id,
                'client_secret' : client_secret,
                'code' : code,
                }
        str_data = json.dumps(data)
        response = requests.request(method='POST', url=ACCESS_TOKEN_URL, headers=headers, data=str_data)
        status_code = response.status_code
        if status_code != 200:
            raise ValueError("{} -- {}".format(status_code, response.json()))
        return body['access_token']
750201
def access_token(self, request_token, request_secret):
        """"""
        logging.debug("Getting access token from %s:%d",
                      self.server, self.port)
        self.access_token, self.access_secret = \
            self._token("/oauth/accessToken", request_token, request_secret)
        return self.access_token, self.access_secret
452573
protected function exchangeToken() {
        $result = $this->requestAccessToken();
        if ($result && !empty($result['access_token'])) {
            $this->accessToken = $result['access_token'];
            $this->sessionStorage->write('access_token', $result['access_token']);
            if (!empty($result['refresh_token'])) {
                $this->refreshToken = $result['refresh_token'];
                $this->sessionStorage->write('refresh_token', $result['refresh_token']);
            }
            if (!empty($result['id_token'])) {
                $this->validateIdToken($result['id_token']);

                $this->user = $this->requestUserInfo();
                if ($this->user) {
                    $this->sessionStorage->write('user', $this->user);
                }
            }
        }
    }
777257
def call(call, access_token = false, params = {}, risk_token = false, client_ip = false)
      path = call.start_with?('/') ? call : call.prepend('/')
      url  = URI.parse(api_endpoint + path)

      call = Net::HTTP::Post.new(url.path, {
        'Content-Type' => 'application/json',
        'User-Agent'   => 'WePay Ruby SDK'
      })

      unless params.empty?
        call.body = params.to_json
      end

      if access_token then call.add_field('Authorization', "Bearer #{access_token}"); end
      if @api_version then call.add_field('Api-Version', @api_version); end
      if risk_token then call.add_field('WePay-Risk-Token', risk_token); end
      if client_ip then call.add_field('Client-IP', client_ip); end

      make_request(call, url)
    end
413310
public void modifyTransferSpec(AsperaConfig sessionDetails, TransferSpecs transferSpecs) {
		for(TransferSpec transferSpec : transferSpecs.transfer_specs) {
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getTargetRateKbps())))transferSpec.setTarget_rate_kbps(sessionDetails.getTargetRateKbps());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getTargetRateCapKbps())))transferSpec.setTarget_rate_cap_kbps(sessionDetails.getTargetRateCapKbps());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMinRateCapKbps())))transferSpec.setMin_rate_cap_kbps(sessionDetails.getMinRateCapKbps());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMinRateKbps())))transferSpec.setMin_rate_kbps(sessionDetails.getMinRateKbps());
			if (!StringUtils.isNullOrEmpty(sessionDetails.getRatePolicy()))transferSpec.setRate_policy(sessionDetails.getRatePolicy());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.isLockMinRate())))transferSpec.setLock_min_rate(sessionDetails.isLockMinRate());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.isLockTargetRate())))transferSpec.setLock_target_rate(sessionDetails.isLockTargetRate());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.isLockRatePolicy())))transferSpec.setLock_rate_policy(sessionDetails.isLockRatePolicy());
			if (!StringUtils.isNullOrEmpty(sessionDetails.getDestinationRoot()))transferSpec.setDestination_root(sessionDetails.getDestinationRoot());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMultiSession())))transferSpec.setMulti_session(sessionDetails.getMultiSession());
			if (!StringUtils.isNullOrEmpty(String.valueOf(sessionDetails.getMultiSessionThreshold())))transferSpec.setMulti_session_threshold(sessionDetails.getMultiSessionThreshold());
		}
	}
1203872
def transfer(self):
        
        result = self.client.get('/account/transfer')

        if not 'used' in result:
            raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!')

        return MappedObject(**result)
474184
def get_ams_access_token(accountname, accountkey):
    '''
    '''
    accountkey_encoded = urllib.parse.quote(accountkey, safe='')
    body = "grant_type=client_credentials&client_id=" + accountname + \
	"&client_secret=" + accountkey_encoded + " &scope=urn%3aWindowsAzureMediaServices"
    return do_ams_auth(ams_auth_endpoint, body)
746981
async function transfer (nameId, account, options = {}) {
  const opt = R.merge(this.Ae.defaults, options)

  const nameTransferTx = await this.nameTransferTx(R.merge(opt, {
    nameId,
    accountId: await this.address(),
    recipientId: account
  }))

  return this.send(nameTransferTx, opt)
}
503461
def from_response(self, response_data):
        ''' 

        '''
        return HSAccessTokenAuth(
            response_data['access_token'],
            response_data['token_type'], 
            response_data['refresh_token'],
            response_data['expires_in'], 
            response_data.get('state') # Not always here
        )
748055
public TransferSpecs getTransferSpec(FASPConnectionInfo faspConnectionInfo, String localFileName, String remoteFileName, String direction)
			throws SdkClientException, AmazonServiceException {
		log.trace("AsperaTransferManager.getTransferSpec >> start " + System.nanoTime());
		TransferSpecs transferSpecs = null;
		
		URL ats_url = null;
		try {
			ats_url = new URL(faspConnectionInfo.getAtsEndpoint());
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		URI ats_uri = null;
		try {
			ats_uri = ats_url.toURI();
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		log.trace("AsperaTransferManager.getTransferSpec >> retrieve delegate token " + System.nanoTime());
		Token token = new Token().withDelegate_token(tokenManager.getToken());
		log.trace("AsperaTransferManager.getTransferSpec << retrieve delegate token " + System.nanoTime());
		
		log.trace("AsperaTransferManager.getTransferSpec >> prepare transfer request " + System.nanoTime());
		StorageCredentials storageCredentials = new StorageCredentials().withType("token")
				.withToken(token);
		Node node = new Node().withStorage_credentials(storageCredentials);
		Aspera aspera = new Aspera().withNode(node);
		Tags tags = new Tags().withAspera(aspera);
		List<Path> paths = new ArrayList<Path>();
		Path path = new Path().withSource(localFileName)
				.withDestination(remoteFileName);
		paths.add(path);
		List<TransferRequest> transferRequests = new ArrayList<TransferRequest>();
		TransferRequest transferRequest = new TransferRequest().withPaths(paths).withDestination_root("")
				.withTags(tags).withRemote_host(ats_uri.getHost());
		transferRequests.add(transferRequest);
		AsperaTransferSpecRequest transferSpecRequest = new AsperaTransferSpecRequest()
				.withTransfer_requests(transferRequests);

		ObjectMapper mapper = new ObjectMapper();

		String jsonTransferRequest = null;
		try {
			jsonTransferRequest = mapper.writeValueAsString(transferSpecRequest);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		log.trace("AsperaTransferManager.getTransferSpec << prepare transfer request " + System.nanoTime());

		// Post transfer spec request
		// TODO need to manage retries.
		try {
			log.trace("AsperaTransferManager.getTransferSpec >> prepare post request " + System.nanoTime());
			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());

			HttpClient client = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();

			HttpPost post = new HttpPost(faspConnectionInfo.getAtsEndpoint() + "/files/" + direction + "_setup");
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");
			String authStr = faspConnectionInfo.getAccessKeyId() + ":" + faspConnectionInfo.getAccessKeySecret();
			post.setHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(authStr.getBytes("UTF-8")));
			post.setHeader("Accept", "application/json");
			post.setHeader("X-Aspera-Storage-Credentials",
					"{\"type\": \"token\", \"token\" : {\"delegated_refresh_token\":\"" + tokenManager.getToken() + "\"}}");

			StringEntity transferParams = new StringEntity(jsonTransferRequest);
			transferParams.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

			post.setEntity(transferParams);
			log.trace("AsperaTransferManager.getTransferSpec << prepare post request " + System.nanoTime());

			log.trace("AsperaTransferManager.getTransferSpec >> post request " + System.nanoTime());
			final HttpResponse response = client.execute(post);
			log.trace("AsperaTransferManager.getTransferSpec << post request " + System.nanoTime());

			if (response.getStatusLine().getStatusCode() != 200) {
				log.info("Response code= " + response.getStatusLine().getStatusCode() + ", Reason= "
						+ response.getStatusLine().getReasonPhrase() + ".Throwing AsperaTransferException");
				AsperaTransferException exception = new AsperaTransferException("Failed to get Aspera Transfer Spec");
				exception.setStatusCode(response.getStatusLine().getStatusCode());
				exception.setStatusMessage(response.getStatusLine().getReasonPhrase());
				throw exception;
			}

			final HttpEntity entity = response.getEntity();
			final String resultStr = EntityUtils.toString(entity);
			
			log.trace("AsperaTransferManager.getTransferSpec >> mapping transfer spec " + System.nanoTime());
			transferSpecs = mapper.readValue(resultStr, TransferSpecs.class);
			log.trace("AsperaTransferManager.getTransferSpec << mapping transfer spec " + System.nanoTime());

		} 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();
		}

		log.trace("AsperaTransferManager.getTransferSpec << end " + System.nanoTime());
		return transferSpecs;
	}
65076
def get_token(params, access_token_opts={})
      params = params.merge(:parse => :json)
      access_token_opts = access_token_opts.merge({:header_format => "OAuth2 %s", :param_name => "access_token"})
      
      @token = super(params, access_token_opts)
    end
515101
def complete_request(self, account_id, request_id, **params):
        """"""
        response = self._post(
            'v2', 'accounts', account_id, 'transactions', request_id,
            'complete', data=params)
        return self._make_api_object(response, APIObject)
378790
def do_get(endpoint, access_token):
    '''
    '''
    headers = {"Authorization": 'Bearer ' + access_token}
    headers['User-Agent'] = get_user_agent()
    return requests.get(endpoint, headers=headers).json()
1048551
def transfer_asset(asset_id: nil,
                       amount: nil,
                       script: nil, address: nil,
                       provider: nil, unspent_outputs: nil, change_address: nil)
      raise ArgumentError, "AssetID must be provided" if !asset_id
      raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address
      raise ArgumentError, "Both `script` and `address` cannot be specified" if script && address
      raise ArgumentError, "Amount must be greater than zero" if !amount || amount <= 0

      provider = Provider.new{|atxbuilder| unspent_outputs } if unspent_outputs
      change_address = AssetAddress.parse(change_address) if change_address

      asset_id = AssetID.parse(asset_id)
      script ||= AssetAddress.parse(address).script

      self.transferred_assets << {asset_id: asset_id, amount: amount, script: script, provider: provider, change_address: change_address}
    end
776140
def transfer_funds(self, from_, to, amount):
        
        return self.make_api_request(
            'Account',
            'transferFunds',
            utils.get_kwargs(locals()),
            model=models.TransferResponse,
        )