Request a proxy ticket
@param req
@param path
@param callback
@param {Function} retryHandler If this callback is set, it will be called only if request failed due to authentication issue.
556386
function requestPT(path, callback, retryHandler) {
    logger.info('Trying to request proxy ticket from ', proxyPath);
    var startTime = Date.now(); 
    utils.getRequest(path, function(err, response) {
      /* istanbul ignore if */
      logger.access('|GET|' + path + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime));
      if (err) {
        logger.error('Error happened when sending request to: ' + path);
        logger.error(err);
        return callback(err);
      }

      if (response.status !== 200) {
        logger.error('Request fail when trying to get proxy ticket', response);
        if (typeof retryHandler === 'function') return retryHandler(err);

        return callback(new Error('Request fail when trying to get proxy ticket, response status: ' + response.status +
          ', response body: ' + response.body));
      }

      var pt = parseCasResponse(response.body);

      if (pt) {
        logger.info('Request proxy ticket succeed, receive pt: ', pt);
        callback(null, pt);
      } else {
        logger.error('Can\' get pt from get proxy ticket response.');
        logger.error('Request for PT succeed, but response is invalid, response: ', response.body);
        if (typeof retryHandler === 'function') return retryHandler(new Error('Request for PT succeed, but response is invalid, response: ' + response.body));
        return callback(new Error('Request for PT succeed, but the response is invalid, response: ' + response.body));
      }
    });
  }
403637
function callback(err, response, body)
    {
      if (err)
      {
        // if we haven't exceeded the maximum number of retries yet and the
        // server came back with a retryable error code.
        if (numRetries < maxNumRetries && isRetryableError(response, err))
        {
          // increment the number of retries
          numRetries++;

          // use exponential backoff with decorrelated jitter to compute the
          // next sleep time:
          var cap = connectionConfig.getRetryLargeResultSetMaxSleepTime();
          sleep = Util.nextSleepTime(1, cap, sleep);

          // wait the appropriate amount of time before retrying the request
          setTimeout(sendRequest, sleep * 1000);
        }
        else
        {
          // wrap the error into a network error
          err = Errors.createNetworkError(
            ErrorCodes.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT, err);
        }
      }
      // if the response contains xml, build an S3/Blob error from the response
      else if (response.getResponseHeader('Content-Type') ===
        'application/xml')
      {
        err = Errors.createLargeResultSetError(
          ErrorCodes.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE, response);
      }

      // if we have an error, clear the body
      if (err)
      {
        body = null;
      }

      // if a callback was specified, invoke it
      if (Util.isFunction(options.callback))
      {
        options.callback(err, body);
      }
    }
1351812
@Override
  public boolean proxyLoginHandler(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (! isLoginTarget(target)) {
      return false;
    }

    if (isPageRequest(request)) {
      proxySendLoginForm(response);
    } else {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied. Please login.");
    }
    return true;
  }
71072
function getServerHandler(basePath, adapter) {
    basePath = basePath || '/';
    if (basePath.length > 0 && basePath[basePath.length - 1] === '/') {
        basePath = basePath.substring(0, basePath.length - 2);
    }
    return function(req, res, next) {
        return teleport.Promise.resolve().then(function() {
            var params = req.params = req.params || {};
            var path = params.path || params['0'] || '';
            if (path[0] !== '/') {
                path = '/' + path;
            }
            path = basePath + path;
            var query = req.query || {};
            var headers = req.headers || {};
            var data = req.data || req.body || {};
            var overrideKey = 'X-HTTP-Method-Override';
            var method = //
            headers[overrideKey] || query[overrideKey] || //
            req.method || 'get';
            delete query[overrideKey];
            method = method.toLowerCase();
            var options = {
                path : path,
                method : method,
                params : params,
                query : query,
                headers : headers,
                data : data
            };
            return adapter.handle(options);
        }).then(function(result) {
            result = result || {};
            var headers = result.headers || {};
            res.set(headers);
            res.send(result.data || {});
        }, function(err) {
            res.status(500).send({
                error : err.stack,
                params : req.params
            });
        });
    }
}
517614
public PactDslRequestWithPath matchPath(String pathRegex, String path) {
        requestMatchers.addCategory("path").addRule(new RegexMatcher(pathRegex));
        this.path = path;
        return this;
    }
171971
async def retry_get(config, url, *args, **kwargs):
    
    return await _retry_do(config.session.get, url, *args,
                           **_make_headers(config, kwargs))
1019791
def request(self, method, url, proxies=None, **kwargs):
        
        if not self._tried_get_pac:
            self.get_pac()

        # Whether we obtained or are trying to obtain a proxy from the PAC.
        # PAC is not in use if this request has proxies provided as a parameter, or if the session has disabled PAC.
        using_pac = proxies is None and self._proxy_resolver and self.pac_enabled

        if using_pac:
            proxies = self._proxy_resolver.get_proxy_for_requests(url)

        while True:
            proxy_url = list(proxies.values())[0] if proxies else None
            try:
                response = super(PACSession, self).request(method, url, proxies=proxies, **kwargs)
            except Exception as request_exc:
                # Use PAC's proxy failover rules if the proxy used for the request is from the PAC,
                # and this exception represents a proxy failure.
                if using_pac and proxy_url and self._exc_proxy_failure_filter(request_exc):
                    try:
                        proxies = self.do_proxy_failover(proxy_url, url)
                        continue
                    except ProxyConfigExhaustedError:
                        # No failover option, not even DIRECT. Bubble up original exception.
                        self._proxy_resolver.unban_all()
                raise request_exc  # In PY2, just saying 'raise' may re-raise ProxyConfigExhaustedError.

            # Use PAC's proxy failover rules if the proxy used for the request is from the PAC,
            # and this response represents a proxy failure.
            if using_pac and proxy_url and self._response_proxy_failure_filter(response):
                try:
                    proxies = self.do_proxy_failover(proxy_url, url)
                    continue
                except ProxyConfigExhaustedError:
                    # No failover option, not even DIRECT. Return response as-is.
                    self._proxy_resolver.unban_all()
                    return response

            return response
325711
function(remotePath, callback) {
            client
                .stat(remotePath)
                .then(function(stat) {
                    __executeCallbackAsync(callback, [null, __convertStat(stat)]);
                })
                .catch(callback);
        }
860469
function request(client, path, callback) {
  var key = SyncLock.generateKey(client.username);
  var id = client.id;

  // Try to set this key/value pair, but fail if the path for the key already exists.
  redis.hsetnx(key, path, id, function(err, reply) {
    if(err) {
      log.error({err: err, client: client}, 'Error trying to set redis key with hsetnx');
      return callback(err);
    }

    if(reply === 1) {
      // Success, we have the lock (path for the key was set). Return a new SyncLock instance
      var lock = new SyncLock(key, id, path);
      log.debug({client: client, syncLock: lock}, 'Lock acquired.');
      return callback(null, lock);
    }

    // Path for key was not set (held by another client). See if the lock owner would be
    // willing to let us take it. We'll wait a bit for a reply, and if
    // we don't get one, assume the client holding the lock, or its server,
    // has crashed, and the lock is OK to take.

    // Act if we don't hear back from the lock owner in a reasonable
    // amount of time, and set the lock ourselves.
    var waitTimer = setTimeout(function() {
      redis.removeListener('lock-response', client._handleLockResponseFn);
      client._handleLockResponseFn = null;

      redis.hset(key, path, id, function(err) {
        if(err) {
          log.error({err: err, client: client}, 'Error setting redis lock key.');
          return callback(err);
        }

        var lock = new SyncLock(key, id, path);
        log.debug({client: client, syncLock: lock}, 'Lock request timeout, setting lock manually.');
        callback(null, lock);
      });
    }, CLIENT_TIMEOUT_MS);
    waitTimer.unref();

    // Listen for a response from the client holding the lock
    client._handleLockResponseFn = function(message) {
      handleLockResponse(message, key, path, client, waitTimer, callback);
    };
    redis.on('lock-response', client._handleLockResponseFn);

    // Ask the client holding the lock to give it to us
    log.debug({client: client}, 'Requesting lock override for ' + path);
    redis.publish(Constants.server.lockRequestChannel, JSON.stringify({key: key, id: id, path: path}));
  });
}
1203587
function _proxyRequest(json, callback) {
	  var rollbarProxy = new RollbarProxy();
	  rollbarProxy.sendJsonPayload(
	    json,
	    function(_msg) { /* do nothing */ }, // eslint-disable-line no-unused-vars
	    function(err) {
	      callback(new Error(err));
	    }
	  );
	}
530073
def get(self, relpath=None, params=None):
    
    for retry in xrange(self.retries + 1):
      if retry:
        time.sleep(self.retry_sleep)
      try:
        return self.invoke("GET", relpath, params)
      except (socket.error, urllib2.URLError) as e:
        if "timed out" in str(e).lower():
          log_message = "Timeout issuing GET request for %s." \
              % (self._join_uri(relpath), )
          if retry < self.retries:
            log_message += " Will retry."
          else:
            log_message += " No retries left."
          LOG.warn(log_message, exc_info=True)
        else:
          raise
    else:
      raise e
1022945
function(args, connectionInfo, retryCounter) {
  if ( !(args && args.handle && args.handle.value) ) {
    return Promise.reject('missing required arguments for fetchProductByHandle()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/products';
  // this is an undocumented implementation by Vend
  // the response has to be accessed like: result.products[0]
  // which is lame ... TODO: should we unwrap it within the SDK?

  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  log.debug('Requesting vend product ' + vendUrl);
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.debug('GET ' + vendUrl);
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Accept': 'application/json'
    },
    qs: {
      handle: args.handle.value
    }
  };

  return utils.sendRequest(options, args, connectionInfo, fetchProductByHandle, retryCounter);
}
297362
function(path, callback) {
      if (inNodeJS) {
        this.serverSideFetch(path, callback);
      } else {
        //CORS only works in IE8/9 across the same protocol
        //You must have your server on HTTPS to talk to Google, or it'll fall back on injection
        var protocol = this.endpoint.split("//").shift() || "http";
        if (supportsCORS && (!inLegacyIE || protocol === location.protocol)) {
          this.xhrFetch(path, callback);
        } else {
          this.injectScript(path, callback);
        }
      }
    }
37599
function(path, callback) {
      //support IE8's separate cross-domain object
      var xhr = inLegacyIE ? new XDomainRequest() : new XMLHttpRequest();
      xhr.open("GET", this.endpoint + path);
      var self = this;
      xhr.onload = function() {
        try {
          var json = JSON.parse(xhr.responseText);
        } catch (e) {
          console.error(e);
        }
        callback.call(self, json);
      };
      xhr.send();
    }
654357
function(err) {
                // If we aborted, ignore it
                if (req.wasAborted) {
                    return;
                }

                if (err && err.status === 401 && that._shouldAutoLogin()) {
                    // If we had an authorization error, we'll try and login
                    // again, but only once
                    that.sessionKey = null;
                    that.login(function(err, success) {
                        // If we've already aborted the request,
                        // just do nothing
                        if (req.wasAborted) {
                            return;
                        }

                        if (err) {
                            // If there was an error logging in, send it through
                            callback(err);
                        }
                        else {
                            // Relogging in was successful, so we execute
                            // our task again.
                            task(callback);
                        }
                    });
                }
                else {
                    callback.apply(null, arguments);
                }
            }
1085153
function execute(req, res) {
  var proxy = req.exec ? req.exec.proxy : this.proxy;
  res.send(null, proxy(req, res));
}
889939
def _request(self, url, method='GET', params=None):
        """"""
        self.connected = True
        retry_counter = 0

        method = method.lower()
        func = getattr(self.client, method)
        params, _ = _transparent_params(params)

        def _send(retry_counter):
            requests_args = {}
            for k, v in self.client_args.items():
                # Maybe this should be set as a class
                # variable and only done once?
                if k in ('timeout', 'allow_redirects', 'verify'):
                    requests_args[k] = v

            while self.connected:
                try:
                    if method == 'get':
                        requests_args['params'] = params
                    else:
                        requests_args['data'] = params

                    response = func(url, **requests_args)
                except requests.exceptions.Timeout:
                    self.on_timeout()
                else:
                    if response.status_code != 200:
                        self.on_error(response.status_code, response.content)

                    if self.retry_count and \
                       (self.retry_count - retry_counter) > 0:
                        time.sleep(self.retry_in)
                        retry_counter += 1
                        _send(retry_counter)

                    return response

        while self.connected:
            response = _send(retry_counter)

            for line in response.iter_lines(self.chunk_size):
                if not self.connected:
                    break
                if line:
                    try:
                        if is_py3:
                            line = line.decode('utf-8')
                        data = json.loads(line)
                    except ValueError:  # pragma: no cover
                        self.on_error(response.status_code,
                                      'Unable to decode response, \
                                      not valid JSON.')
                    else:
                        if self.on_success(data):  # pragma: no cover
                            for message_type in self.handlers:
                                if message_type in data:
                                    handler = getattr(self,
                                                      'on_' + message_type,
                                                      None)
                                    if handler \
                                       and callable(handler) \
                                       and not handler(data.get(message_type)):
                                        break

        response.close()