The common interface for the API functions to cause a net call.
165925
function procPacket(method, path, data, headers, callback) {
  var cookieStr = '';
  var i;
  var req;

  headers = headers || {};

  if(!headers['Content-Type']) {
    headers['Content-Type'] = 'application/json';
  }

  if(data && typeof data !== 'string') {
    data = JSON.stringify(data);
  }

  //deal with global cookies
  for(i in globalCookies) {
    if(globalCookies.hasOwnProperty(i)) {
      cookieStr += i + '=' + globalCookies[i] + ';';
    }
  }

  //only when we built a cookieStr above
  if(cookieStr) {
    //debug help
    if(xmlHTTP && console && typeof console.log === 'function') {
      console.log('Sending Cookie header, but do not expect any cookies in the result - CouchDB uses httpOnly cookies.');
    }

    headers.Cookie = ((headers.Cookie) ? headers.Cookie : '') + cookieStr;
  }

  if(pathPrefix) {
    path = pathPrefix + path;
  }

  //authentication
  if(currAuth.type === exports.AUTH_BASIC && (currAuth.user || currAuth.pass)) {
    headers.Authorization = 'Basic ' + toBase64(currAuth.user + ':' + currAuth.pass);
  }
  else if(currAuth.type === exports.AUTH_COOKIE) {
    if(http && typeof publicThat.getCookie('AuthSession') !== 'string') {
      throw new Error('Trying to use cookie auth, but we never got an AuthSession cookie from the server.');
    }

    headers['X-CouchDB-WWW-Authenticate'] = 'Cookie';
  }

  if(http) {
    // Node.JS http module
    headers['User-Agent'] = 'Sag-JS/0.4'; //can't set this in browsers

    req = http.request(
      {
        method: method,
        host: host,
        port: port,
        path: path,
        headers: headers
      },
      function(res) {
        var resBody = '';

        res.setEncoding('utf8');

        res.on('data', function(chunk) {
          resBody += chunk;
        });

        res.on('end', function() {
          onResponse(res.statusCode, res.headers, resBody, callback);
        });
      }
    );

    req.on('error', function(e) {
      console.log('problem with request: ' + e);
    });

    if(data) {
      req.write(data);
    }

    req.end();
  }
  else if(xmlHTTP) {
    // Browser xhr magik
    xmlHTTP.onreadystatechange = function() {
      var headers = {};
      var rawHeaders;
      var i;

      if(this.readyState === 4 && this.status > 0) {
        rawHeaders = this.getAllResponseHeaders().split('\n');

        for(i in rawHeaders) {
          if(rawHeaders.hasOwnProperty(i)) {
            rawHeaders[i] = rawHeaders[i].split(': ');

            if(rawHeaders[i][1]) {
              headers[rawHeaders[i][0].toLowerCase()] = rawHeaders[i][1].trim();
            }
          }
        }

        onResponse(
          this.status,
          headers,
          (method !== 'HEAD') ? this.response : null,
          callback
        );
      }
    };

    xmlHTTP.open(method, (useSSL ? 'https://' : 'http://') + host + ':' + port + path);

    for(i in headers) {
      if(headers.hasOwnProperty(i)) {
        xmlHTTP.setRequestHeader(i, headers[i]);
      }
    }

    xmlHTTP.send(data || null);
  }
  else {
    throw new Error('coder fail');
  }
}
4395
function CommonOperation(operationFunc, callback) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
  var sliceStart = 2;
  if (azureutil.objectIsFunction(callback)) {
    this._userCallback = callback;
  } else {
    this._userCallback = null;
    sliceStart = 1;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
  this.run = function (cb) {
    if (!cb) cb = this._userCallback;
    operationArguments.push(cb);
    this.status = OperationState.RUNNING;
    operationFunc.apply(null, operationArguments);
    operationArguments = operationFunc = null;
  };
  
  this._fireUserCallback = function () {
    if (this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
    this._userCallback = this._callbackArguments = null;
  };
}
69506
public static Object callN(Callable fun, Scriptable thisObj,
                               Object[] args,
                               Context cx, Scriptable scope)
    {
        return fun.call(cx, scope, thisObj, args);
    }
1362638
public static Object[] call(Method method, Object[][] params,
                              InetSocketAddress[] addrs,
                              UserGroupInformation ticket, Configuration conf)
    throws IOException {

    Invocation[] invocations = new Invocation[params.length];
    for (int i = 0; i < params.length; i++)
      invocations[i] = new Invocation(method, null, params[i]);
    Client client = CLIENTS.getClient(conf);
    try {
    Writable[] wrappedValues =
      client.call(invocations, addrs, method.getDeclaringClass(), ticket);

    if (method.getReturnType() == Void.TYPE) {
      return null;
    }

    Object[] values =
      (Object[])Array.newInstance(method.getReturnType(), wrappedValues.length);
    for (int i = 0; i < values.length; i++)
      if (wrappedValues[i] != null)
        values[i] = ((ObjectWritable)wrappedValues[i]).get();
    
    return values;
    } finally {
      CLIENTS.stopClient(client);
    }
  }
1193603
public void invokeAction (ClientObject caller, byte[] serializedAction)
    {
        NodeAction action = null;
        try {
            ObjectInputStream oin =
                new ObjectInputStream(new ByteArrayInputStream(serializedAction));
            action = (NodeAction)oin.readObject();
            _injector.injectMembers(action);
            action.invoke();
        } catch (Exception e) {
            log.warning("Failed to execute node action",
                        "from", (caller == null) ? "self" : caller.who(),
                        "action", action, "serializedSize", serializedAction.length, e);
        }
    }
608509
private ClientResponseImpl coreCall(Object... paramListIn) {
        VoltTable[] results = null;

        // use local var to avoid warnings about reassigning method argument
        Object[] paramList = paramListIn;

        try {
            if ((m_paramTypes.length > 0) && (m_paramTypes[0] == ParameterSet.class)) {
                assert(m_paramTypes.length == 1);
                paramList = new Object[] { ParameterSet.fromArrayNoCopy(paramListIn) };
            }

            if (paramList.length != m_paramTypes.length) {
                String msg = "PROCEDURE " + m_procedureName + " EXPECTS " + String.valueOf(m_paramTypes.length) +
                    " PARAMS, BUT RECEIVED " + String.valueOf(paramList.length);
                m_statusCode = ClientResponse.GRACEFUL_FAILURE;
                return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
            }

            for (int i = 0; i < m_paramTypes.length; i++) {
                try {
                    paramList[i] = ParameterConverter.tryToMakeCompatible(m_paramTypes[i], paramList[i]);
                    // check the result type in an assert
                    assert(ParameterConverter.verifyParameterConversion(paramList[i], m_paramTypes[i]));
                } catch (Exception e) {
                    String msg = "PROCEDURE " + m_procedureName + " TYPE ERROR FOR PARAMETER " + i +
                            ": " + e.toString();
                    m_statusCode = ClientResponse.GRACEFUL_FAILURE;
                    return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
                }
            }

            try {
                m_procedure.m_runner = this;
                Object rawResult = m_procMethod.invoke(m_procedure, paramList);

                if (rawResult instanceof CompletableFuture<?>) {
                    final CompletableFuture<?> fut = (CompletableFuture<?>) rawResult;

                    fut.thenRun(() -> {
                        //
                        // Happy path. No exceptions thrown. Procedure work is complete.
                        //
                        Object innerRawResult = null;
                        ClientResponseImpl response = null;
                        try {
                            innerRawResult = fut.get();
                        } catch (InterruptedException | ExecutionException e) {
                            assert(false);
                            // this is a bad place to be, but it's hard to know if it's crash bad...
                            innerRawResult = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
                                    new VoltTable[0],
                                    "Future returned from NTProc " + m_procedureName + " failed to complete.",
                                    m_clientHandle);
                        }

                        if (innerRawResult instanceof ClientResponseImpl) {
                            response = (ClientResponseImpl) innerRawResult;
                        }
                        else {
                            try {
                                VoltTable[] r = ParameterConverter.getResultsFromRawResults(m_procedureName, innerRawResult);
                                response = responseFromTableArray(r);
                            } catch (Exception e) {
                                // this is a bad place to be, but it's hard to know if it's crash bad...
                                response = new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
                                        new VoltTable[0],
                                        "Type " + innerRawResult.getClass().getName() +
                                            " returned from NTProc \"" + m_procedureName +
                                            "\" was not an acceptible VoltDB return type.",
                                        m_clientHandle);
                            }
                        }

                        completeCall(response);
                    })
                    .exceptionally(e -> {
                        //
                        // Exception path. Some bit of async work threw something.
                        //
                        SerializableException se = null;
                        if (e instanceof SerializableException) {
                            se = (SerializableException) e;
                        }

                        String msg = "PROCEDURE " + m_procedureName + " THREW EXCEPTION: ";
                        if (se != null) {
                            msg += se.getMessage();
                        } else {
                            msg += e.toString();
                        }
                        m_statusCode = ClientResponse.GRACEFUL_FAILURE;
                        completeCall(ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, se));
                        return null;
                    });

                    return null;
                }
                results = ParameterConverter.getResultsFromRawResults(m_procedureName, rawResult);
            }
            catch (IllegalAccessException e) {
                // If reflection fails, invoke the same error handling that other exceptions do
                throw new InvocationTargetException(e);
            }
        }
        catch (InvocationTargetException itex) {
            //itex.printStackTrace();
            Throwable ex = itex.getCause();
            if (CoreUtils.isStoredProcThrowableFatalToServer(ex)) {
                // If the stored procedure attempted to do something other than linklibrary or instantiate
                // a missing object that results in an error, throw the error and let the server deal with
                // the condition as best as it can (usually a crashLocalVoltDB).
                throw (Error)ex;
            }
            return ProcedureRunner.getErrorResponse(m_procedureName,
                                                    true,
                                                    0,
                                                    m_appStatusCode,
                                                    m_appStatusString,
                                                    null,
                                                    ex);
        }

        return responseFromTableArray(results);
    }
69636
function api_act() {
    var argsarr = new Array(arguments.length)
    for (var l = 0; l < argsarr.length; ++l) {
      argsarr[l] = arguments[l]
    }

    var self = this
    var spec = Common.build_message(self, argsarr, 'reply:f?', self.fixedargs)
    var msg = spec.msg
    var reply = spec.reply

    if (opts.$.debug.act_caller || opts.$.test) {
      msg.caller$ =
        '\n    Action call arguments and location: ' +
        (new Error(Util.inspect(msg).replace(/\n/g, '')).stack + '\n')
          .replace(/Error: /, '')
          .replace(/.*\/gate-executor\.js:.*\n/g, '')
          .replace(/.*\/seneca\.js:.*\n/g, '')
          .replace(/.*\/seneca\/lib\/.*\.js:.*\n/g, '')
    }

    do_act(self, msg, reply)
    return self
  }
1221215
def call(symbol, **kwargs):
    
    LOG.info("API method %s called with args: %s", symbol, str(kwargs))

    # TODO(PH, JK) improve the way api function modules are loaded
    from . import all  # noqa
    if not is_call_registered(symbol):
        message = 'Did not find any method registered by symbol %s' % symbol
        raise MethodNotFound(message)

    if not symbol.startswith('core') and not CORE_MANAGER.started:
        raise CoreNotStarted(desc='CoreManager is not active.')

    call = get_call(symbol)
    try:
        return call(**kwargs)
    except BGPSException as r:
        LOG.error(traceback.format_exc())
        raise r
    except Exception as e:
        LOG.error(traceback.format_exc())
        raise ApiException(desc=str(e))
881868
def call(self, func, *api_args, **api_kwargs):
        """"""
        if not isinstance(func, str) or (func == ''):
            msg = ('Invalid input for API name, should be a'
                   'string, type: %s specified.') % type(func)
            return self._construct_api_name_error(msg)

        # Create client socket
        try:
            cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as err:
            return self._construct_socket_error(1, error=six.text_type(err))

        try:
            # Set socket timeout
            cs.settimeout(self.timeout)
            # Connect SDK server
            try:
                cs.connect((self.addr, self.port))
            except socket.error as err:
                return self._construct_socket_error(2, addr=self.addr,
                                                    port=self.port,
                                                    error=six.text_type(err))

            # Prepare the data to be sent and switch to bytes if needed
            api_data = json.dumps((func, api_args, api_kwargs))
            api_data = api_data.encode()

            # Send the API call data to SDK server
            sent = 0
            total_len = len(api_data)
            got_error = False
            try:
                while (sent < total_len):
                    this_sent = cs.send(api_data[sent:])
                    if this_sent == 0:
                        got_error = True
                        break
                    sent += this_sent
            except socket.error as err:
                return self._construct_socket_error(5,
                                                    error=six.text_type(err))

            if got_error or sent != total_len:
                return self._construct_socket_error(3, sent=sent,
                                                    api=api_data)

            # Receive data from server
            return_blocks = []
            try:
                while True:
                    block = cs.recv(4096)
                    if not block:
                        break
                    block = bytes.decode(block)
                    return_blocks.append(block)
            except socket.error as err:
                # When the sdkserver cann't handle all the client request,
                # some client request would be rejected.
                # Under this case, the client socket can successfully
                # connect/send, but would get exception in recv with error:
                # "error: [Errno 104] Connection reset by peer"
                return self._construct_socket_error(6,
                                                    error=six.text_type(err))
        finally:
            # Always close the client socket to avoid too many hanging
            # socket left.
            cs.close()

        # Transform the received stream to standard result form
        # This client assumes that the server would return result in
        # the standard result form, so client just return the received
        # data
        if return_blocks:
            results = json.loads(''.join(return_blocks))
        else:
            results = self._construct_socket_error(4)
        return results
919365
def make_api_call(self, method, url, json_params=None):
        

        url = self.BRANCH_BASE_URI+url

        if self.verbose is True:
            print("Making web request: {}".format(url))

        if json_params is not None:
            encoded_params = json.dumps(json_params)
            headers = {'Content-Type': 'application/json'}
        else:
            encoded_params = None
            headers = {}

        if encoded_params is not None and self.verbose is True:
            print("Params: {}".format(encoded_params))

        request = Request(url, encoded_params.encode('utf-8'), headers)
        request.get_method = lambda: method
        response = urlopen(request).read()
        return json.loads(response.decode('utf-8'))
497745
public void invoke(Object service,
                       AbstractHessianInput in,
                       AbstractHessianOutput out)
        throws Exception
    {
        ServiceContext context = ServiceContext.getContext();

        // backward compatibility for some frameworks that don't read
        // the call type first
        in.skipOptionalCall();

        // Hessian 1.0 backward compatibility
        String header;
        while ((header = in.readHeader()) != null) {
            Object value = in.readObject();

            context.addHeader(header, value);
        }

        String methodName = in.readMethod();
        int argLength = in.readMethodArgLength();

        Method method;

        method = getMethod(methodName + "__" + argLength);

        if (method == null)
            method = getMethod(methodName);

        if (method != null) {
        }
        else if ("_hessian_getAttribute".equals(methodName)) {
            String attrName = in.readString();
            in.completeCall();

            String value = null;

            if ("java.api.class".equals(attrName))
                value = getAPIClassName();
            else if ("java.home.class".equals(attrName))
                value = getHomeClassName();
            else if ("java.object.class".equals(attrName))
                value = getObjectClassName();

            out.writeReply(value);
            out.close();
            return;
        }
        else if (method == null) {
            out.writeFault("NoSuchMethodException",
                escapeMessage("The service has no method named: " + in.getMethod()),
                null);
            out.close();
            return;
        }

        Class<?>[] args = method.getParameterTypes();

        if (argLength != args.length && argLength >= 0) {
            out.writeFault("NoSuchMethod",
                escapeMessage("method " + method + " argument length mismatch, received length=" + argLength),
                null);
            out.close();
            return;
        }

        Object[] values = new Object[args.length];

        for (int i = 0; i < args.length; i++) {
            // XXX: needs Marshal object
            values[i] = in.readObject(args[i]);
        }

        Object result = null;

        try {
            result = method.invoke(service, values);
        } catch (Exception e) {
            Throwable e1 = e;
            if (e1 instanceof InvocationTargetException)
                e1 = ((InvocationTargetException) e).getTargetException();

            log.log(Level.FINE, this + " " + e1.toString(), e1);

            out.writeFault("ServiceException",
                escapeMessage(e1.getMessage()),
                e1);
            out.close();
            return;
        }

        // The complete call needs to be after the invoke to handle a
        // trailing InputStream
        in.completeCall();

        out.writeReply(result);

        out.close();
    }
1338864
public static <ReqT, RespT> RespT blockingUnaryCall(ClientCall<ReqT, RespT> call, ReqT req) {
    try {
      return getUnchecked(futureUnaryCall(call, req));
    } catch (RuntimeException e) {
      throw cancelThrow(call, e);
    } catch (Error e) {
      throw cancelThrow(call, e);
    }
  }
455552
def request(self, method, apikey, *args, **kwargs):
        
        dry_run = kwargs.get('dry_run', False)
        return_dry_run = kwargs.get('return_dry_run', False)
        if return_dry_run:
            args[-1]['--dry-run'] = True

        try:
            func = getattr(self.endpoint, method)
            return func(apikey, *args)
        except (socket.error, requests.exceptions.ConnectionError):
            msg = 'Gandi API service is unreachable'
            raise APICallFailed(msg)
        except xmlrpclib.Fault as err:
            msg = 'Gandi API has returned an error: %s' % err
            if dry_run:
                args[-1]['--dry-run'] = True
                ret = func(apikey, *args)
                raise DryRunException(msg, err.faultCode, ret)
            raise APICallFailed(msg, err.faultCode)
        except TypeError as err:
            msg = 'An unknown error has occurred: %s' % err
            raise APICallFailed(msg)
746701
function (name) {
			return function (args, onDone) {
				
				if (typeof args === 'function') {
					onDone = args;
					args = {};
				}
				
				console.log('calling API [' + name + ']...');
				
				// NOTE: by default callbacks are always kept
				SR.sendEvent(name, args, function (result) {
					if (result.err) {
						console.error(result.err);
						return SR.safeCall(onDone, result.err);
					}
					
					SR.safeCall(onDone, null, result.result);
				}, undefined, true);
			}
		}
7294
public static <ReqT, RespT> void asyncUnaryCall(
      ClientCall<ReqT, RespT> call, ReqT req, StreamObserver<RespT> responseObserver) {
    asyncUnaryRequestCall(call, req, responseObserver, false);
  }
1329292
function helpDefine(_api, _name, _fun) {
      var api = APIS[_api];

      Utils.assert(!!api, 'Invalid api name $1', _api);

      if(_name) {
        api[_name] = Utils.override(api[_name], _fun);
      } else {
        Utils.extendOverriden(api, _fun);
      }
    }
1073126
@Override
  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> method,
      CallOptions callOptions) {
    return interceptorChannel.newCall(method, callOptions);
  }