Call a webService

If the webService is local, make the call without
doing any HTTP call
764793
public function call($webServiceName, $inputData=null,
                              $version=null)
    {
        if (is_null($version)) {
            $version = $this->getVersion();
        }

        //Create unique token to identify the call
        $token = uniqid("CALL_");
        if ($this->isSymfony()) {
            $eventDispatcher = $this->symfonyContainer->get("event_dispatcher");
        }

        /*
         * Throw initial event before executing
         * the call, remote or local
         */
        if (($inputData instanceof BaseStore) && $this->isSymfony()) {
            $event = new WebServiceCallingEvent($token, $webServiceName, $inputData, $version,
                                                $this->_connectionTimeout, $this->_timeOut,
                                                $this->_proxy, $this->_proxyPort);
            $eventDispatcher->dispatch("puremachine.webservice.calling", $event);
        }

        //check if the service is local
        if ($this->isSymfony() && $this->symfonyContainer->has('pureMachine.sdk.webServiceManager')) {
            $WebServiceManager = $this->symfonyContainer->get('pureMachine.sdk.webServiceManager');

            if ($WebServiceManager->getSchema($webServiceName)) {
                $return = $WebServiceManager->localCall($webServiceName, $inputData, $version);

                /*
                 * Throw post event after executing
                 * the local call
                 */
                if (($return instanceof BaseStore) && $this->isSymfony()) {
                    $event = new WebServiceCalledEvent($token, $webServiceName, $return, $version, true);
                    $eventDispatcher->dispatch("puremachine.webservice.called", $event);
                }

                return $return;
            }
        }

        //We did not found the webService in local, we do it remotely.
        $return = $this->remoteCall($webServiceName, $inputData, $version);

        /*
         * Throw post event after executing
         * the local call
         */
        if (($return instanceof BaseStore) && $this->isSymfony()) {
            $event = new WebServiceCalledEvent($token, $webServiceName, $return, $version, false);
            $eventDispatcher->dispatch("puremachine.webservice.called", $event);
        }

        return $return;
    }
835725
public static Response call(String server, String service, boolean suppress, String... params) {
        try {
            URL url = new URL(server + '/' + service);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
            for (String param: params) {
                _logger.fine(param);
                pw.print(param); pw.print('&');
            }
            pw.close();
            InputStream in = connection.getInputStream();
            try {
                byte[] bytes = Bytes.read(in);
                try {
                    Response response = _mapper.readValue(bytes, Response.class).setResponseBody(bytes);
                    if (response.params == null) {
                        throw new ServiceException("***ProtocolErrorMissingParams");
                    } else if (!suppress) {
                        String message = response.params.get(Service.FAILURE_MESSAGE);
                        if (message != null && message.length() > 0) {
                            throw new RemoteServiceException(message);
                        }
                    }
                    return response;
                } catch (JsonProcessingException x) {
                    _logger.log(Level.WARNING, new String(bytes, "UTF-8"));
                    throw x;
                }
            } finally {
                in.close();
            }
        } catch (RuntimeException x) {
            throw x;
        } catch (Exception x) {
            throw new ServiceException("***RemoteServiceCallFailure", x);
        }
    }
238176
private WebServer loadWebServer() {
        WebServer webServer = null;
        if (!Utils.isEmpty(getParamString("webserver_class"))) {
            try {
                Class<?> serviceClass = Class.forName(getParamString("webserver_class"));
                Method instanceMethod = serviceClass.getMethod("instance", (Class<?>[])null);
                webServer = (WebServer)instanceMethod.invoke(null, (Object[])null);
                webServer.init(RESTServlet.class.getName());
            } catch (Exception e) {
                throw new RuntimeException("Error initializing WebServer: " + getParamString("webserver_class"), e);
            }
        }
        return webServer;
    }
1183539
function () {

      // helper method to assert if a given url is local
      function isLocal(url) {
        var loc = document.location,
            reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host);
        return url.match(reg);
      }

      // gather all resources
      var scripts = document.getElementsByTagName("script"),
          links = document.getElementsByTagName("link"),
          uris = [];

      // track local js urls
      for (var i = 0; i < scripts.length; i++) {
        var script = scripts[i], src = script.getAttribute("src");
        if (src && isLocal(src))
          uris.push(src);
        if (src && src.match(/\blive.js#/)) {
          for (var type in active)
            active[type] = src.match("[#,|]" + type) != null
          if (src.match("notify")) 
            alert("Live.js is loaded.");
        }
      }
      if (!active.js) uris = [];
      if (active.html) uris.push(document.location.href);

      // track local css urls
      for (var i = 0; i < links.length && active.css; i++) {
        var link = links[i], rel = link.getAttribute("rel"), href = link.getAttribute("href", 2);
        if (href && rel && rel.match(new RegExp("stylesheet", "i")) && isLocal(href)) {
          uris.push(href);
          currentLinkElements[href] = link;
        }
      }

      // initialize the resources info
      for (var i = 0; i < uris.length; i++) {
        var url = uris[i];
        Live.getHead(url, function (url, info) {
          resources[url] = info;
        });
      }

      // add rule for morphing between old and new css files
      var head = document.getElementsByTagName("head")[0],
          style = document.createElement("style"),
          rule = "transition: all .3s ease-out;"
      css = [".livejs-loading * { ", rule, " -webkit-", rule, "-moz-", rule, "-o-", rule, "}"].join('');
      style.setAttribute("type", "text/css");
      head.appendChild(style);
      style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css));

      // yep
      loaded = true;
    }
36468
def api_call(method, path, params ={}, &proc)
      if cache = caching? && (@cache[cache_key(path, params)])
        return cache
      else
        if @logging
          Calculated::Logging.log_calculated_api(method, path, params) do
            api_call_without_logging(method, path, params, &proc)
          end
        else
          api_call_without_logging(method, path, params, &proc)
        end
      end
    end
1046748
def _call_geocoder(
            self,
            url,
            timeout=DEFAULT_SENTINEL,
            raw=False,
            requester=None,
            deserializer=json.loads,
            **kwargs
    ):
        

        if requester:
            req = url  # Don't construct an urllib's Request for a custom requester.

            # `requester` might be anything which can issue an HTTP request.
            # Assume that `requester` is a method of the `requests` library.
            # Requests, however, doesn't accept SSL context in its HTTP
            # request methods. A custom HTTP adapter has to be created for that.
            # So the current usage is not directly compatible with `requests`.
            requester = functools.partial(requester, context=self.ssl_context,
                                          proxies=self.proxies,
                                          headers=self.headers)
        else:
            if isinstance(url, Request):
                # copy Request
                headers = self.headers.copy()
                headers.update(url.header_items())
                req = Request(url=url.get_full_url(), headers=headers)
            else:
                req = Request(url=url, headers=self.headers)

        requester = requester or self.urlopen

        if timeout is None:
            warnings.warn(
                ('`timeout=None` has been passed to a geocoder call. Using '
                 'default geocoder timeout. In geopy 2.0 the '
                 'behavior will be different: None will mean "no timeout" '
                 'instead of "default geocoder timeout". Pass '
                 'geopy.geocoders.base.DEFAULT_SENTINEL instead of None '
                 'to get rid of this warning.'), DeprecationWarning, stacklevel=3)
            timeout = DEFAULT_SENTINEL

        timeout = (timeout if timeout is not DEFAULT_SENTINEL
                   else self.timeout)

        try:
            page = requester(req, timeout=timeout, **kwargs)
        except Exception as error:
            message = (
                str(error) if not py3k
                else (
                    str(error.args[0])
                    if len(error.args)
                    else str(error)
                )
            )
            self._geocoder_exception_handler(error, message)
            if isinstance(error, HTTPError):
                code = error.getcode()
                body = self._read_http_error_body(error)
                if body:
                    logger.info('Received an HTTP error (%s): %s', code, body,
                                exc_info=False)
                try:
                    raise ERROR_CODE_MAP[code](message)
                except KeyError:
                    raise GeocoderServiceError(message)
            elif isinstance(error, URLError):
                if "timed out" in message:
                    raise GeocoderTimedOut('Service timed out')
                elif "unreachable" in message:
                    raise GeocoderUnavailable('Service not available')
            elif isinstance(error, SocketTimeout):
                raise GeocoderTimedOut('Service timed out')
            elif isinstance(error, SSLError):
                if "timed out" in message:
                    raise GeocoderTimedOut('Service timed out')
            raise GeocoderServiceError(message)

        if hasattr(page, 'getcode'):
            status_code = page.getcode()
        elif hasattr(page, 'status_code'):
            status_code = page.status_code
        else:
            status_code = None
        if status_code in ERROR_CODE_MAP:
            raise ERROR_CODE_MAP[page.status_code]("\n%s" % decode_page(page))

        if raw:
            return page

        page = decode_page(page)

        if deserializer is not None:
            try:
                return deserializer(page)
            except ValueError:
                raise GeocoderParseError(
                    "Could not deserialize using deserializer:\n%s" % page
                )
        else:
            return page
1023678
def _mock_methodcall(self, methodname, localobject, Params=None, **params):
        # pylint: disable=invalid-name
        
        result = self._fake_invokemethod(methodname, localobject, Params,
                                         **params)

        # Sleep for defined number of seconds
        if self._response_delay:
            time.sleep(self._response_delay)

        return result
1174931
def call_webservice(method_name, arguments, schema_url, service_path)

      # Perform the call to the webservice and returns the result
      Operations::WebserviceCall.new(@rforce_binding, method_name, arguments, schema_url, service_path).run()

    end
1352054
function jsonpSuccess(requestSettings, callbackContext, mockHandler) {
		// If a local callback was specified, fire it and pass it the data
		if ( requestSettings.success ) {
			requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );
		}

		// Fire the global callback
		if ( requestSettings.global ) {
			(requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxSuccess", [{}, requestSettings]);
		}
	}
1157129
def run_locally(self):
        """"""
        self.thread = threading.Thread(target=self.execute_locally)
        self.thread.daemon = True # So that they die when we die
        self.thread.start()
383716
function runCall(name, call, input) {
    return web.post(connectorsUrl + '/' + name + '/' + call, input);
}
1244613
def call(self, my_args=None):
        
        LOGGER.debug("rest.Requester.call")
        if my_args is None:
            raise exceptions.ArianeConfError('requester call arguments')
        if 'http_operation' not in my_args or my_args['http_operation'] is None or not my_args['http_operation']:
            raise exceptions.ArianeConfError('requester call http_operation')
        if 'operation_path' not in my_args or my_args['operation_path'] is None:  # can be empty
            raise exceptions.ArianeConfError('requester call operation_path')
        if 'parameters' not in my_args:
            my_args['parameters'] = None

        if my_args['http_operation'] is "GET":
            if my_args['parameters'] is None:
                response = self.session.get(self.base_url + self.repository_path + my_args['operation_path'])
            else:
                response = self.session.get(self.base_url + self.repository_path + my_args['operation_path'],
                                            params=my_args['parameters'])
        elif my_args['http_operation'] is "POST":
            if my_args['parameters'] is not None:
                response = self.session.post(self.base_url + self.repository_path + my_args['operation_path'],
                                             params=my_args['parameters'])
            else:
                raise exceptions.ArianeConfError('parameters argument is mandatory for http POST request')
        else:
            raise exceptions.ArianeNotImplemented(my_args['http_operation'])

        if response.status_code is 200:
            try:
                return DriverResponse(
                    rc=0,
                    error_message=response.reason,
                    response_content=response.json()
                )
            except ValueError as e:
                return DriverResponse(
                    rc=0,
                    error_message=response.reason,
                    response_content=response.text
                )
        else:
            return DriverResponse(
                rc=response.status_code,
                error_message=response.reason,
                response_content=response.text
            )
1187313
def _call(self, mthd, uri, admin, data, headers, std_headers):
        
        if not uri.startswith("http"):
            uri = "/".join((self.auth_endpoint.rstrip("/"), uri))
        if admin:
            # Admin calls use a different port
            uri = re.sub(r":\d+/", ":35357/", uri)
        if std_headers:
            hdrs = self._standard_headers()
        else:
            hdrs = {}
        if headers:
            hdrs.update(headers)
        kwargs = {"headers": hdrs}
        if data:
            kwargs["body"] = data
        if "tokens" in uri:
            # We'll handle the exception here
            kwargs["raise_exception"] = False
        return pyrax.http.request(mthd, uri, verify=self.verify_ssl, **kwargs)
1151382
def call_remote(method, args)

      urn, soap_url = block_given? ? yield : ["urn:partner.soap.sforce.com", @url.path]

      # Create XML text from the arguments.
      expanded = ''
      @builder = Builder::XmlMarkup.new(:target => expanded)
      expand(@builder, {method => args}, urn)

      extra_headers = ""
      extra_headers << (AssignmentRuleHeaderUsingRuleId % assignment_rule_id) if assignment_rule_id
      extra_headers << AssignmentRuleHeaderUsingDefaultRule if use_default_rule
      extra_headers << MruHeader if update_mru
      extra_headers << (ClientIdHeader % client_id) if client_id

      if trigger_user_email or trigger_other_email or trigger_auto_response_email
        extra_headers << '<partner:EmailHeader soap:mustUnderstand="1">'

        extra_headers << '<partner:triggerUserEmail>true</partner:triggerUserEmail>' if trigger_user_email
        extra_headers << '<partner:triggerOtherEmail>true</partner:triggerOtherEmail>' if trigger_other_email
        extra_headers << '<partner:triggerAutoResponseEmail>true</partner:triggerAutoResponseEmail>' if trigger_auto_response_email

        extra_headers << '</partner:EmailHeader>'
      end

      # Fill in the blanks of the SOAP envelope with our
      # session ID and the expanded XML of our request.
      request = (Envelope % [@session_id, @batch_size, extra_headers, expanded])

      # reset the batch size for the next request
      @batch_size = DEFAULT_BATCH_SIZE

      # gzip request
      request = encode(request)

      headers = {
        'Connection' => 'Keep-Alive',
        'Content-Type' => 'text/xml',
        'SOAPAction' => '""',
        'User-Agent' => 'activesalesforce rforce/1.0'
      }

      unless show_debug
        headers['Accept-Encoding'] = 'gzip'
        headers['Content-Encoding'] = 'gzip'
      end

      # Send the request to the server and read the response.
      response = @server.post2(soap_url, request.lstrip, headers)

      # decode if we have encoding
      content = decode(response)

      # Check to see if INVALID_SESSION_ID was raised and try to relogin in
      if method != :login and @session_id and content =~ /sf:INVALID_SESSION_ID/
        login(@user, @password)

        # repackage and rencode request with the new session id
        request = (Envelope % [@session_id, @batch_size, extra_headers, expanded])
        request = encode(request)

        # Send the request to the server and read the response.
        response = @server.post2(soap_url, request.lstrip, headers)

        content = decode(response)
      end

      SoapResponse.new(content).parse
    end
562520
def execute_locally(self):
        """"""
        # Make script file #
        self.make_script()
        # Do it #
        with open(self.kwargs['out_file'], 'w') as handle:
            sh.python(self.script_path, _out=handle, _err=handle)
90363
public void call(final T request, final Functor<String, RemoteService.Response> process) {
        call(request, process, null);
    }
309594
def run_local(client):
  """"""
  webbrowser.open(client.get_auth_uri())
  code = wait_for_redirect()
  return client.get_token(code)