Perform a request.
@param {aria.core.CfgBeans:IOAsyncRequestCfg} request Request object
@param {aria.core.CfgBeans:Callback} callback Internal callback description
@throws
183510
function (request, callback) {
            this.nbXdrRequests += 1;

            this.xdrRequests[request.id] = {
                callback : callback,
                transaction : request.id
            };

            var args = {
                xdr : true,
                method : request.method,
                data : request.data,
                headers : request.headers
            };

            // This might throw an error, propagate it and let the IO know that there was an exception
            this._transport.send(request.url, args, request.id);
        }
202679
public void invokeRequest (ClientObject caller, byte[] serializedAction,
        InvocationService.ResultListener listener)
    {
        NodeRequest request = null;
        try {
            ObjectInputStream oin =
                new ObjectInputStream(new ByteArrayInputStream(serializedAction));
            request = (NodeRequest)oin.readObject();
            _injector.injectMembers(request);
            request.invoke(listener);

        } catch (Exception e) {
            log.warning("Failed to execute node request",
                        "from", (caller == null) ? "self" : caller.who(),
                        "request", request, "serializedSize", serializedAction.length, e);
            listener.requestFailed("Failed to execute node request");
        }
    }
690822
function request(data, callback) {
    var qsdata = (data.qs) ? qs.stringify(data.qs) : '';
    var paramChar = data.path.indexOf('?') >= 0 ? '&' : '?';
    var options = {
      hostname: data.uri,
      path: data.path + paramChar + qsdata,
      method: data.method
    };
    var req;
    var body;

    if ( data.method === 'POST' ) {
      options.path = data.path;
      options.headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Content-Length': qsdata.length
      };
    }

    req = https.request(options, function (response) {
      body = '';
      response.on('data', function (chunk) {
        body += chunk;
      });
      response.on('end', function () {
        try {
          var d = JSON.parse(body);
          // See http://developers.soundcloud.com/docs/api/guide#errors for full list of error codes
          if ( Number(response.statusCode) >= 400 ) {
            callback(d.errors, d);
          } else {
            callback(undefined, d);
          }
        } catch (e) {
          callback(e);
        }
      });
    });

    req.on('error', function (e) {
      callback(e);
    });

    if ( data.method === 'POST' ) {
      req.write(qsdata);
    }

    return req.end();
  }
1291152
function Request(method, args, callback) {
		this.handle.send('layer', [method, args], function (content) {
			callback.apply({}, content);
		});
	}
572395
function Request(opts, callback) {
    this.opts = opts;
    this.callback = callback;

    Object.defineProperty(this, 'method', {
        get: function() {
            return opts.method;
        },
    });

    Object.defineProperty(this, 'path', {
        get: function() {
            return opts.uri;
        },
    });

    /**
     * Parse the body of the request as a JSON object and return it.
     */
    Object.defineProperty(this, 'data', {
        get: function() {
            return opts.body ? JSON.parse(opts.body) : opts.body;
        },
    });

    /**
     * Return the raw body passed to request
     */
    Object.defineProperty(this, 'rawData', {
        get: function() {
            return opts.body;
        },
    });

    Object.defineProperty(this, 'queryParams', {
        get: function() {
            return opts.qs;
        },
    });

    Object.defineProperty(this, 'headers', {
        get: function() {
            return opts.headers || {};
        },
    });
}
569686
function Request(method, url) {
  var self = this;
  Emitter.call(this);
  this._query = this._query || [];
  this.method = method;
  this.url = url;
  this.header = {};
  this._header = {};
  this.on('end', function(){
    var err = null;
    var res = null;

    try {
      res = new Response(self);
    } catch(e) {
      err = new Error('Parser is unable to parse the response');
      err.parse = true;
      err.original = e;
      return self.callback(err);
    }

    self.emit('response', res);

    if (err) {
      return self.callback(err, res);
    }

    if (res.status >= 200 && res.status < 300) {
      return self.callback(err, res);
    }

    var new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
    new_err.original = err;
    new_err.response = res;
    new_err.status = res.status;

    self.callback(new_err, res);
  });
}
281354
function _sendRequest(method, uri, options, callback) {

        method(uri, options)
            .on('success', function(data, response) {
                if (data.result) {
                    callback(null, data.result);
                } else {
                    callback(null, data);
                }
            })
            .on('fail', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request failed'));
                }
            })
            .on('error', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request error'));
                }
            })
            .on('timeout', function(ms) {
                callback(new Error('Request timed out (' + ms + ')'));
            });
    }
1020388
function request(svc, operation, params, next, extra) {
    var world = this;

    if (!svc) svc = this.service;
    if (typeof svc === 'string') svc = this[svc];

    svc[operation](params, function(err, data) {
      world.response = this;
      world.error = err;
      world.data = data;

      try {
        if (typeof next.condition === 'function') {
          var condition = next.condition.call(world, world);
          if (!condition) {
            next.fail(new Error('Request success condition failed'));
            return;
          }
        }

        if (extra) {
          extra.call(world, world.response);
          next.call(world);
        }
        else if (extra !== false && err) {
          world.unexpectedError(world.response, next);
        } else {
          next.call(world);
        }
      } catch (err) {
        next.fail(err);
      }
    });
  }
977373
def __request(self, method, url, request_args, headers=None, stream=False):
        
        func = getattr(self.client, method)
        headers = headers if headers else {}
        response = None
        try:
            logger.info("performing request %s", url)
            response = func(url, stream=stream, headers=headers,
                            **request_args)
        except requests.RequestException as err:
            logger.error("request %s failed [%s]", url, err)
            raise err

        # Handle error responses
        if response.status_code >= 400:
            logger.error("request %s failed [%d,%s]",
                         url,
                         response.status_code,
                         response.content.decode('utf-8'))
            raise V20Error(response.status_code,
                           response.content.decode('utf-8'))
        return response
690323
function RequestWrapper(req) {
  this.request = req;
  this.method = req.method;
  this.url = req.url;
  this.body = req._data;
  this.headers = req._header;
}
102250
function Request(reqBytes){
  var parsed;
  var err

  try {
    parsed = types.Request.decode(reqBytes);
  } catch (e) {
    err = e;
  }


  //Check for request errors here
  if(err){
    this.BadRequest = true;
    this.errCode = types.CodeType.EncodingError;
    this.errMsg = "The request failed to be decoded"
  } else if(!types.methodLookup[parsed.type]){
    //Request type not recognized
    //Make a request object for the error
    this.BadRequest = true;
    this.errCode = types.CodeType.UnknownRequest;
    this.errMsg = "The request type was not understood"
  } else {

    this.BadRequest = false; 
    this.type = parsed.type;
    this.method = types.methodLookup[this.type];
    this.data = parsed.data.buffer.slice(parsed.data.offset);
    this.dataLength = parsed.data.limit - parsed.data.offset;
    this.dataLittle = parsed.data.littleEndian;
    this.key = parsed.key;
    this.value = parsed.value;
  }
}
1275628
function(callback) {
        var self = this;

        var auth_post_data = querystring.stringify({
            'grant_type': 'client_credentials'
        });

        return new Promise(function(resolve, reject){
            self.client.methods.authentication_oauth(_.extend({}, self.requestOptions, {
                data: auth_post_data,
                headers: _.extend({}, self.requestOptions.headers, {
                    'Authorization': _getBasicAuthHash(self.config.clientId, self.config.clientApiKey),
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(auth_post_data)
                })
            }), function(data) {
                // Authorization succeeded
                if (data.token_type && data.access_token) {
                    _.extend(self.requestOptions.headers, {
                        'Authorization': data.token_type + ' ' + data.access_token
                    });
                    // Multiplying expires_in (seconds) by 1000 since JS getTime() is expressed in ms
                    self.authorizationExpireTime = new Date().getTime() + ( data.expires_in * 1000 );
                    resolve(data);
                    if (_.isFunction(callback)) {
                        callback(data);
                    }
                } else {
                    reject(data);
                }
            }).on('error', function (err) { reject(err.message) });
        });
    }
646480
function send(message, callback) {
  const suppliedCallback = callback || function () {};
  if (!message) {
    return suppliedCallback(new Error('No message'));
  }
  const requestParams = {
    url: this.webhook,
    body: extend(this.options, { text: message }),
    json: true
  };
  return request.post(requestParams, function (err, res, body) {
    if (err || body !== 'ok') {
      return suppliedCallback(err || new Error(body));
    }
    return suppliedCallback(null, body);
  });
}
1078585
function request(ipc, name, args) {

		// check online
		if (!ipc.root.online) {
			ipc.root.emit('error', new Error("Could not make a request, channel is offline"));
			return;
		}

		// store callback for later
		var callback = args.pop();

		// check that a callback is set
		if (typeof callback !== 'function') {
			ipc.root.emit('error', new TypeError("No callback specified"));
			return;
		}

		// send request to remote
		ipc.send('call', [name, args], function (sucess, content) {
			if (sucess) {
				callback.apply({
					error: null
				}, content);
			} else {
				callback.apply({
					error: helpers.object2error(content)
				}, []);
			}
		});
	}
832408
function APIRequest(method, url) {
	var data, callback, opts, req, headers = messageHeaders(this);
	callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

	if (isNode) {
		opts = URL.parse(url);
		opts.method = method;
		opts.headers = headers;

		req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
			var chunks = [];
			res.on('data', function(c) { chunks[chunks.length] = c; });
			res.once('end', function() {
				chunks = Buffer.concat(chunks);
				Zlib.gunzip(chunks, function(err, uc) {
					if (!err) uc = uc.toString();
					try { res.body = JSON.parse(uc || chunks); } catch(e) {}
					return callback(null, res);
				});
			});
		});
		if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
		if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
		if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
		req.end();

		return req.once('error', function(e) { return callback(e.message); });
	}

	req = new XMLHttpRequest();
	req.open(method.toUpperCase(), url, true);
	for (var key in headers) {
		req.setRequestHeader(key, headers[key]);
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			req.statusCode = req.status;
			req.statusMessage = req.statusText;
			try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
			callback(null, req);
		}
	};
	if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
	if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
	req.send(null);
}
534831
protected void deliveryAsyncResult(Request request, HttpCallback<?> callback) {
        Util.log("onDelivery:" + request.url().toString());
        final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback;

        //Call start
        callStart(resCallBack, request);

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                Util.log("onFailure:" + call.request().toString());
                callFailure(resCallBack, call.request(), null, e);
                callFinish(resCallBack);
            }

            public void onResponse(Call call, Response response) {
                try {
                    Object ret = null;
                    final String string = response.body().string();
                    final boolean haveValue = !TextUtils.isEmpty(string);

                    Util.log("onResponse:Code:%d Body:%s.", response.code(), (haveValue ? string : "null"));

                    if (haveValue) {
                        ret = mResolver.analysis(string, resCallBack.getClass());
                    }

                    callSuccess(resCallBack, ret, response.code());
                } catch (Exception e) {
                    Util.log("onResponse Failure:" + response.request().toString());
                    callFailure(resCallBack, response.request(), response, e);
                }
                callFinish(resCallBack);
            }
        });
    }
1246288
function Request (method, args, attempts, proxyCondition) {
    // constraint
    attempts = attempts || 0;
    if (attempts > 10)
        throw `Maximum number of request attempts exceeded (10 total) for "${args.url}"`;
    // workflow
    if (!args.url) throw 'URL undefined in smappi-cl/lib/request';
    args.data = args.data || {}; // for POST/PUT
    args.params = args.params || {}; // for GET
    args.headers = args.headers || {};
    args.options = args.options || {};
    if (!args.options.hasOwnProperty('followLocation')) {
        args.options.followLocation = true;
    }
    if (args.options.proxy == false) {
        args.proxy = null;
    } else {
        if (proxyCondition && !proxy.isActive()) {
            // if not disable proxy (for internal request, see proxy.js)
            // and there proxyCondition
            // and not active proxy
            proxy.next(); // then activate proxy if used withProxy!
        }
        args.proxy = proxy.currentHref();
    }
    args.method = method;
    if (!args.options.async) { // Synchronous
        var contentFile = ".smappi-request-content-" + process.pid;
        var syncFile = ".smappi-request-sync-" + process.pid;
        fs.writeFileSync(syncFile, "", "utf8");
        // The async request the other Node process executes
        // Start the other Node Process, executing this string
        // console.log(process.argv[0], __dirname + '/worker.js', process.pid, "'" + JSON.stringify(args) + "'");
        var syncProc = spawn(process.argv[0], [
            __dirname + '/worker.js',
            process.pid,
            JSON.stringify(args)
        ]);
        while (fs.existsSync(syncFile)) {
            // Wait while the sync file is empty
        }
        var resp = JSON.parse(fs.readFileSync(contentFile, 'utf8'));
        // Kill the child process once the file has data
        syncProc.stdin.end();
        // Remove the temporary file
        fs.unlinkSync(contentFile);
        let retry = () => {
            // if use proxy and request is broken, then turn next
            if (args.options.proxy !== false) {
                proxy.skip(); // skip current
                proxy.next();
            }
            return new Request(method, args, attempts + 1, proxyCondition);
        }
        if (resp.err) {
            if (Object.keys(resp.err).length) {
                let errStr = JSON.stringify(resp.err);
                if (resp.err.options && resp.err.options.command == 'connect') {
                    let postScriptum = '';
                    if (resp.err.options.proxy)
                        postScriptum = ' (probably proxy is wrong)';
                    logger.error(`Problem while connect for "${args.url}"${postScriptum}. Request will be retry. ERR: ${errStr}`);
                    return retry();
                } else if (resp.err.code == 'ECONNRESET') {
                    logger.error(`Connection problems for "${args.url}". Request will be retry. ERR: ${errStr}`);
                    return retry();
                } else if (resp.err.code == 'ETIMEOUT' || resp.err.code == 'ETIMEDOUT') {
                    logger.error(`Connection timeout exceeded for "${args.url}". Request will be retry. ERR: ${errStr}`);
                    return retry();
                } else if (resp.err.code == 'ENOTFOUND' && resp.err.syscall == 'getaddrinfo') {
                    let msg = `Host "${resp.err.hostname}" not found. Please verify A-record for this domain.`;
                    logger.error(msg);
                    throw msg;
                } else {
                    throw errStr;
                }
            } else if (args.proxy && resp.ctx == 'request') {
                return retry(); // Otherwise retry again
            } else if (resp.message) {
                throw resp.message;
            } else {
                throw 'Problem with connection in smappi-cl/lib/request';
            }
        } else {
            if ([301, 302].indexOf(resp.status) != -1) {
                if (args.options.followLocation) {
                    let location = url.parse(resp.headers.location);
                    if (!location.protocol) {
                        let srcUrl = url.parse(args.url);
                        // add protocol for location without proto, example "//smappi.org/path/to" or relative path "/path/to"
                        location.protocol = srcUrl.protocol;
                        if (!location.href.startsWith('//')) { // relative, not shortcut proto
                            // relative path to current hostname, example "/path/to"
                            location.hostname = srcUrl.hostname;
                        }
                    }
                    args.url = location.format();
                    return new Request(method, args, attempts + 1, proxyCondition);
                }
            }
            let response = new Response(resp, args.url);
            // console.log('RequestResponse check condition', args.url, response.status, !proxyCondition || proxyCondition(response))
            if (!proxyCondition || proxyCondition(response)) {
                // If not proxyCondition or proxyCondition is success
                // return Response
                return response;
            } else {
                return retry(); // Otherwise retry again
            }
        }
    } else {
        throw 'Temporary! Not Implemented Smappi CL Async Requests';
    }
}