Execute HTTP method on path with data
170229
private function run($path, $options)
    {
        $method  = $options['method'];
        $data    = isset($options['data'])    ? $options['data']    : null;
        $params  = isset($options['params'])  ? $options['params']  : null;
        $headers = isset($options['headers']) ? $options['headers'] : array();
        $body    = !empty($data)              ? json_encode($data)  : null;

        // Arrays in constants are in PHP 5.6+
        $allowedHeaders = array(
            'If-None-Match',    // Pairs with `ETag` response header.
            'If-Modified-Since' // Pairs with `Last-Modified` response header.
        );

        $headers = $this->filterOptions($headers, $allowedHeaders);
        $headers['User-Agent']   = $this->userAgent;
        $headers['Content-Type'] = 'application/json';

        if (!empty($headers['If-Modified-Since']) && $headers['If-Modified-Since'] instanceof DateTime) {
            $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s \G\M\T', $headers['If-Modified-Since']->getTimestamp());
        }

        $response = $this->requester->run(array(
            'url'     => self::URL . $this->slug . $path,
            'method'  => $method,
            'params'  => $params,
            'body'    => $body,
            'userpwd' => "$this->email:$this->apiKey",
            'headers' => $headers
        ));

        return $response;
    }
998873
def make_request(method, path, options, raw=false)
      options.merge!({:key => api_key, :id => api_id })

      response = connection(raw).send(method) do |request|
        case method
        when :get, :delete
          request.url(path, options)
        when :post, :put
          request.path = path
          request.body = options unless options.empty?
        end
      end
      return response if raw
      return response.body
    end
501154
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException
    {
    }
591265
def put(path, data, options = {})
      uri = build_uri(path, options)

      request = Net::HTTP::Put.new(uri.request_uri)
      set_authorisation_header(request)
      request.set_form_data(data)

      response = https_client(uri).request(request)
    end
1299500
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        Resource resource = getResource(pathInContext);
        if (resource==null)
            return;

        // Is the method allowed?
        if (!isMethodAllowed(request.getMethod()))
        {
            if(log.isDebugEnabled())log.debug("Method not allowed: "+request.getMethod());
            if (resource.exists())
            {
                setAllowHeader(response);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            return;
        }

        // Handle the request
        try
        {
            if(log.isDebugEnabled())log.debug("PATH="+pathInContext+" RESOURCE="+resource);
            
            // check filename
            String method=request.getMethod();
            if (method.equals(HttpRequest.__GET) ||
                method.equals(HttpRequest.__POST) ||
                method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, pathParams, resource);  
            else if (method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(response, pathInContext);
            else if (method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__TRACE))
                handleTrace(request, response);
            else
            {
                if(log.isDebugEnabled())log.debug("Unknown action:"+method);
                // anything else...
                try{
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                }
                catch(Exception e) {LogSupport.ignore(log,e);}
            }
        }
        catch(IllegalArgumentException e)
        {
            LogSupport.ignore(log,e);
        }
        finally
        {
            if (resource!=null && !(resource instanceof CachedResource))
                resource.release();
        }
    }
1326246
function Method(method, path) {
    return function (target, propertyKey, descriptor) {
        path = (path != undefined) ? path : propertyKey;
        method = method.toLowerCase();
        let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
        m.methodMountpoints.push({ "path": U.UrlJoin("/", path), "httpMethod": method });
        m.explicitlyDeclared = true;
    };
}
260284
function(header, path, method, transport) {
      transport = transport || 'http';
      if (transport !== 'http' && transport !== 'ws') {
        throw new CError('unknown transport').log();
      }
      var plain = true,
          self = this;
      method = method || 'GET';
      // prepare request
      if (!this.request || this.path !== path || this.method !== method) {
        var url = util.format('%s%s', this.urlBase, path);
        if (transport === 'http') {
          this.request = agent(method, url);
          // set timeout for request
          if (this.requestTimeout && this.requestTimeout > 0) {
            this.request.timeout(this.requestTimeout);
          }
          // set content type
          this.request.type('json');
        } else {
          var ws = getWebsocketPlugin();
          if (!ws) {
            throw new CError('websocket plugin not loaded');
          }
          this.request = ws.wsclient.primusagent(method, url, {
            timeout: this.requestTimeout
          });
        }
      }
      if (!this.request) {
        throw new CError('no request available').log();
      }
      // set headers
      if (header) {
        this.headers[authHeaderKey] = header.encode();
        _.each(this.headers, function(value, key) {
          self.request.set(key, value);
        });
        plain = (header.getMode() === 'auth-plain');
      }
      // compose query if required
      if (this._pendingQuery) {
        _.forEach(this._pendingQuery, function(value) {
          if (plain || self._noAuthHeader) {
            if (!_.isObject(value)) {
              throw new CError('wrong query format').log();
            }
            self.request.query(value);
          } else {
            // encrypt query in Base64url
            if (!_.isObject(value)) {
              throw new CError('wrong query format').log();
            }
            _.forEach(value, function(item, property) {
              value[property] = header.encoder.encryptAes(item.toString(), header.getSecret(), 'url');
            });
            self.request.query(value);
          }
        });
      }
      // compose body if required
      if (this._pendingContent) {
        var content = {},
            _content = {};
        if (plain || this._noAuthHeader) {
          _.forEach(this._pendingContent, function(value) {
            if (!_.isObject(value)) {
              throw new CError('wrong body format').log();
            }
            self.request.send(value);
          });
          log.info('%s on request -> write plaintext body', app.name);
        } else {
          if (!header) {
            throw new CError('missing header').log();
          }
          _.forEach(this._pendingContent, function(value) {
            if (!_.isObject(value)) {
              throw new CError('wrong body format').log();
            }
            _.extend(_content, value);
          });
          content[my.config.encryptedBodyName] = header.cryptContent(_content);
          // sign the body
          if (my.config.signBody) {
            content[my.config.encryptedSignatureName] = header.generateSignature(_content);
          }
          log.info('%s on request -> write encrypted body', app.name);
          self.request.send(content);
        }
      }
    }
230141
protected RestResponse request(final String path, final String method, Map<String, Object> paramList)
            throws IOException, AppPlatformException {
        if (paramList == null) {
            paramList = Collections.emptyMap();
        }

        final HttpUriRequest request = setupRequest(path, method, paramList);
        return performRequest(request);
    }
964372
def execute
      # Here is the order of operations:
      # -> setting @data_sent
      # -> executing before_request_execution callback
      # -> executing the HTTP request
      # -> setting @response
      # -> setting @data_received
      # -> executing after_request_execution callback

      # Setting @data_sent
      params = Rack::Utils.parse_nested_query(URI.parse(@http_request.path).query)
      # Since that's how it will be interpreted anyway on the server, we merge the POST params to the GET params,
      # but it's not supposed to happen: either every params is prepared for GET/query params, or as POST body
      params.merge!(Rack::Utils.parse_nested_query(@http_request.body.to_s))

      # About: Hash[{}.map{|k,v| [k, v.join] }]
      # it transforms the following hash:
      # {"accept"=>["*/*"], "user-agent"=>["TheBigDB RubyWrapper/X.Y.Z"], "host"=>["computer.host"]}
      # into the following hash:
      # {"accept"=>"*/*", "user-agent"=>"TheBigDB RubyWrapper/X.Y.Z", "host"=>"computer.host"}
      # which is way more useful and cleaner.
      @data_sent = {
        "headers" => Hash[@http_request.to_hash.map{|k,v| [k, v.join] }],
        "host" => @http.address,
        "port" => @http.port,
        "path" => URI.parse(@http_request.path).path,
        "method" => @http_request.method,
        "params" => params
      }

      # Executing callback
      TheBigDB.before_request_execution.call(self)

      # Here is where the request is actually executed
      @http_response = TheBigDB.http_request_executor.call(@http, @http_request)

      # Setting @response
      begin
        # We parse the JSON answer and return it.
        @response = JSON(@http_response.body)
      rescue JSON::ParserError => e
        @response = {"status" => "error", "error" => {"code" => "0000", "description" => "The server gave an invalid JSON body:\n#{@http_response.body}"}}
      end

      # Setting @data_received
      @data_received = {
        "headers" => Hash[@http_response.to_hash.map{|k,v| [k, v.join] }],
        "content" => @response
      }

      # Executing callback
      TheBigDB.after_request_execution.call(self)

      # Raising exception if asked
      if TheBigDB.raise_on_api_status_error and @response["status"] == "error"
        raise ApiStatusError.new(@response["error"]["code"])
      end

      self
    end
871988
def send(path, method, content = '')

      uri = BASE_URI + path
      response = @client.fetch_protected_resource(
        :uri => uri,
        :method => method,
        :body  => content,
        :headers => {'Content-type' => 'application/json'}
      )

      check_for_errors(response)

      return response
    end
540197
function send(httpMethod, path, req) {
    req = req || {};
    httpMethod = httpMethod.toUpperCase();

    var deferred = Q.defer();
    var url = baseUrl + path;
    var data = req.data || {};          // separate out data from request
    delete req.data;

    var isAdmin = req.caller && req.caller.role === 'admin';
    delete req.caller;

    var id = req._id || data._id;       // get id from request or data
    if (req._id) { delete req._id; }    // delete id from request so no dupe

    var session = cls.getNamespace('appSession');
    var caller = session && session.active && session.get('caller');
    if (caller && !isAdmin) {
        _.extend(req, {                 // onBehalfOf used by API to know who is the caller
            onBehalfOfType: caller.type,
            onBehalfOfId:   caller._id + '',
            onBehalfOfRole: caller.role,
            onBehalfOfName: caller.name
        });
    }

    _.each(req, function (val, key) {
        if (!_.isString(val)) { req[key] = JSON.stringify(val); }
    });

    // replace the ID portion of the URL
    url = id ?
        url.replace('{_id}', id + '') :
        url.replace('/{_id}', '');

    var reqConfig = {
        headers:    headers,
        url:        url,
        method:     httpMethod,
        qs:         _.isEmpty(req) ? undefined : req,
        json:       _.isEmpty(data) ? true : data
    };

    // if baseUrl not there yet, wait for 100 seconds until it is (i.e. during system startup)
    if (!baseUrl) {
        setTimeout(function () {
            makeRequest(reqConfig, deferred);
        }, 100);
    }
    else {
        makeRequest(reqConfig, deferred);
    }

    return deferred.promise;
}
443769
function onProcCallGet(method, path, args) {
    // log('onProcCallGet('+JSON.stringify(arguments));
    let pathSplit = path.split('/');
    const serviceid = pathSplit.shift();
    const propname = pathSplit.join('/');

    const bInfo = (args.info === 'true');

    if (serviceid == '') { // access 'admin/' => service list
        let re = {net: {}, server_status: {}};
        if (bInfo) {
            re._info = {leaf: false};
        }
        re.net = ipv4.getMACs();

        re.id = {};
        if (bInfo) {
            re.net._info = {
                leaf: false,
                doc: {short: 'Mac address of recognized network peers'},
            };
            re.server_status._info={
                leaf: true,
                doc: {short: 'Check server memory/swap status'},
            };
            re.id._info = {leaf: true, doc:{short: 'Get unique ID of this PicoGW'}};
        }

        return re;
    }

    if (propname == '') { // access 'admin/serviceid/' => property list
        let ret;
        switch (serviceid) {
        case 'net':
            const macs = ipv4.getMACs();
            // log(JSON.stringify(macs));
            ret = macs;
            for (const [mac, macinfo] of Object.entries(macs)) {
                if (bInfo) {
                    ret[mac]._info = {
                        leaf: true,
                        doc: {short: (macinfo.ip || 'IP:null')},
                    };
                }
            }
            return ret;
        case 'server_status':
            return new Promise((ac, rj)=>{
                exec('vmstat', (err, stdout, stderr) => {
                    if (err) {
                        ac({error: 'Command execution failed.',
                            result: err});
                    } else if (stdout !== null) {
                        ac({success: true, result: stdout.split('\n')});
                    } else {
                        ac({error: 'Command execution failed.',
                            result: stderr});
                    }
                });
            });
        case 'id':
            return {id:exports.getMyID()};
        }
        return {error: 'No such service:'+serviceid};
    }

    switch (serviceid) {
    case 'net':
        const m = ipv4.getMACs()[propname];
        if (m == undefined) {
            return {error: 'No such mac address:'+propname};
        }
        return m;
    }
    return {error: 'No such service:'+serviceid};
}
1067293
function httpRequest(path, req, options)
{
    return new Promise(function(resolve, reject) {
        req = extend({}, defaults, req, options);
        req.url += path;

        request(req, function(error, response, body) {
            if (error || !(/^2/.test('' + response.statusCode)) || /action=".?login.lua"/.test(body)) {
                if (/action=".?login.lua"/.test(body)) {
                    // fake failed login if redirected to login page without HTTP 403
                    response.statusCode = 403;
                }
                reject({
                    error: error,
                    response: response,
                    options: req
                });
            }
            else {
                resolve(body.trim());
            }
        });
    });
}
433265
protected function execute($path, $method, $queryParams, $httpBody = null, $headers = array())
    {
        $attempts = $this->attempts;
        $response = $this->apiClient->call($path, $method, $queryParams, $httpBody, $headers);

        while ($response->getCode() == 202 && $attempts > 0) {
            $this->delay($response);
            $attempts--;
            $response = $this->apiClient->call($path, $method, $queryParams, $httpBody, $headers);
        }

        return $response;
    }
1206359
def request(method, path, options = {})
      options = options.dup

      raw = raw? || options.delete(:raw)
      params(options)
      response = connection.send method, path, (@raw_body || @params), @headers
      raw ? response : @scopeable.parse(response)
    end
967384
def execute(method, *args)
      new_args = args

      @pre_request.each do |middleware|
        new_args = middleware.call(*new_args)
      end

      path = new_args.empty? ? '' : new_args.shift

      req = proc do ||
        @resource[path].send(method, *new_args)
      end

      post = proc do |result|
        @post_request.each do |middleware|
          result = middleware.call(result)
        end

        result
      end

      Concurrent::Promise.new(&req).on_success(&post)
    end
854495
def request(http_method, path, params)
      response = connection.send(http_method, path, params)
      response.body
    end