Run a Request

@param $str_method
@param ProtocolMessage $obj_request
@param ProtocolMessage $obj_response
@return ProtocolMessage|null|object
@throws ApplicationError
@throws \Exception
191216
private function execute($str_method, ProtocolMessage $obj_request, ProtocolMessage $obj_response)
    {
        try {
            $this->obj_last_request = $obj_request;
            $this->obj_last_response = null;
            ApiProxy::makeSyncCall('search', $str_method, $obj_request, $obj_response, 60);
            $this->obj_last_response = $obj_response;
        } catch (ApplicationError $obj_exception) {
            throw $obj_exception;
        }
    }
379276
def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw):
        
        if batch:
            urlsplitter = urlparse(API_ROOT).netloc
            ret = {"method": http_verb, "path": uri.split(urlsplitter, 1)[1]}
            if kw:
                ret["body"] = kw
            return ret

        if not ('app_id' in ACCESS_KEYS and 'rest_key' in ACCESS_KEYS):
            raise core.ParseError('Missing connection credentials')

        app_id = ACCESS_KEYS.get('app_id')
        rest_key = ACCESS_KEYS.get('rest_key')
        master_key = ACCESS_KEYS.get('master_key')

        url = uri if uri.startswith(API_ROOT) else cls.ENDPOINT_ROOT + uri
        if _body is None:
            data = kw and json.dumps(kw, default=date_handler) or "{}"
        else:
            data = _body
        if http_verb == 'GET' and data:
            url += '?%s' % urlencode(kw)
            data = None
        else:
            if cls.__name__ == 'File':
                data = data
            else:
                data = data.encode('utf-8')

        headers = {
            'Content-type': 'application/json',
            'X-Parse-Application-Id': app_id,
            'X-Parse-REST-API-Key': rest_key
        }
        headers.update(extra_headers or {})

        if cls.__name__ == 'File':
            request = Request(url.encode('utf-8'), data, headers)
        else:
            request = Request(url, data, headers)

        if ACCESS_KEYS.get('session_token'):
            request.add_header('X-Parse-Session-Token', ACCESS_KEYS.get('session_token'))
        elif master_key:
            request.add_header('X-Parse-Master-Key', master_key)

        request.get_method = lambda: http_verb

        try:
            response = urlopen(request, timeout=CONNECTION_TIMEOUT)
        except HTTPError as e:
            exc = {
                400: core.ResourceRequestBadRequest,
                401: core.ResourceRequestLoginRequired,
                403: core.ResourceRequestForbidden,
                404: core.ResourceRequestNotFound
                }.get(e.code, core.ParseError)
            raise exc(e.read())

        return json.loads(response.read().decode('utf-8'))
1305785
public static Object callMethod(Scriptable obj, String methodName,
                                    Object[] args)
    {
        return callMethod(null, obj, methodName, args);
    }
268442
@Override
    public Object invoke(Object conn, Object requestData)
        throws AdapterException, ConnectionException
    {
        try {
            Object result;

            if (jmsSenderReceiver != null) {

                final String responseQueueName = this.getAttributeValueSmart(RESPONSE_QUEUE_NAME);
                final String requestDataForMessage = (String) requestData;
                final Queue replyQueue;
                final String correlationId = getCorrelationId();

                boolean replyIsTemporaryQueue = false;
                if (responseQueueName != null && responseQueueName.length() > 0) {
                    replyQueue = (Queue) ApplicationContext.getNamingProvider().lookup(null,
                            responseQueueName, Queue.class);
                    // msg.setJMSReplyTo(replyQueue);
                }
                else if (this.isSynchronous()) {
                    replyQueue = qSession.createTemporaryQueue();
                    // msg.setJMSReplyTo(replyQueue) ;
                    replyIsTemporaryQueue = true;
                }
                else
                    replyQueue = null;

                jmsSenderReceiver.send(getQueueName(), new MessageCreator() {

                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        Message message = session.createTextMessage(requestDataForMessage);
                        if (correlationId != null)
                            message.setJMSCorrelationID(correlationId);
                        if (replyQueue != null) {
                            message.setJMSReplyTo(replyQueue);
                        }
                        return message;
                    }

                });
                if (this.isSynchronous()) {
                    Message message = null;
                    jmsSenderReceiver.setReceiveTimeout(getTimeoutForResponse() * 1000);
                    if (replyIsTemporaryQueue) {
                        message = jmsSenderReceiver.receive(replyQueue);
                    }
                    else {
                        String messageSelector = "JMSCorrelationID = '" + correlationId + "'";
                        message = jmsSenderReceiver.receiveSelected(replyQueue, messageSelector);
                    }
                    if (message == null) {
                        throw new ActivityException(
                                "Synchronous JMS call times out while waiting for response");
                    }
                    else {
                        result = ((TextMessage)message).getText();
                    }
                }
                else
                    result = null;
            }
            else {
                QueueSession qSession = (QueueSession)conn;
                Queue replyQueue;
                boolean replyIsTemporaryQueue = false;
                QueueSender qSender = qSession.createSender(queue);
                TextMessage msg = qSession.createTextMessage((String)requestData);
                String responseQueueName = this.getAttributeValueSmart(RESPONSE_QUEUE_NAME);
                if (responseQueueName!=null && responseQueueName.length()>0) {
                    replyQueue = (Queue)ApplicationContext.getNamingProvider().lookup(null,responseQueueName,Queue.class);
                    msg.setJMSReplyTo(replyQueue);
                } else if (this.isSynchronous()) {
                    replyQueue = qSession.createTemporaryQueue();
                    msg.setJMSReplyTo(replyQueue);
                    replyIsTemporaryQueue = true;
                } else replyQueue = null;
                String correlationId = getCorrelationId();
                if (correlationId!=null) msg.setJMSCorrelationID(correlationId);
                qSender.send(msg);
                if (this.isSynchronous()) {
                    MessageConsumer consumer;
                    if (replyIsTemporaryQueue) {
                        consumer = qSession.createConsumer(replyQueue);
                    } else {
                        String messageSelector = "JMSCorrelationID = '" + correlationId + "'";
                        consumer = qSession.createConsumer(replyQueue, messageSelector);
                    }
                    msg = (TextMessage)consumer.receive(getTimeoutForResponse()*1000);
                    if (msg==null) {
                        throw new ActivityException("Synchronous JMS call times out while waiting for response");
                    } else {
                        result = msg.getText();
                    }
                } else result = null;
            }
            return result;
        } catch (Exception e) {
//            logger.severeException("Exception in JmsAdapter.invoke()" , e);
            throw new AdapterException(-1, "Exception in invoking JmsAdapter" , e);
        }
    }
669985
def execute(self, request, session=None, method='post'):
        '''
        
        '''
        params = {
            'app_key' : self.API_KEY,  
            'v'       : self.API_VERSION,
            'format'  : self.FORMAT,
            #'sign_method' : self.SIGN_METHOD,
            'partner_id'  : self.SDK_VERSON
        }
        api_params = request.get_api_params()
        params['timestamp'] = self._get_timestamp()
        params['method'] = request.get_method_name()
        if session is not None :
            params['session'] = session
        params.update(api_params)
        params['sign'] = self._sign(params)
        #print params
        method = method.lower()
        if method == 'get':
            form_data = urllib.urlencode(params)
            rsp = requests.get('%s?%s'%(self.GATEWAY, form_data))
        elif method == 'post':
            rsp = requests.post(self.GATEWAY, data=params)
        rsp = json.loads(rsp.content)
        if rsp.has_key('error_response'):
            error_code = rsp['error_response']['code']
            if 'sub_msg' in rsp['error_response']:
                msg = '%s [%s]'%(rsp['error_response']['sub_msg'], rsp['error_response']['msg'])
            else:
                msg = rsp['error_response']['msg']
            raise TOPException(error_code, msg)
        else:
            #pprint(rsp)
            rsp = rsp[request.get_method_name().replace('.','_')[7:] + '_response']
            if not rsp: return None
            return rsp
469100
private function runSingleRequest($request_method, $parameters) {

        try {

            $registered_method = $this->checkRequestSustainability($request_method);

            $selected_signature = $this->checkRequestConsistence($registered_method, $parameters);

            if ( is_array($parameters) ) $parameters = self::matchParameters($parameters, $registered_method, $selected_signature);

            $this->parameters->setParameters($parameters);

            $callback = $registered_method->getCallback();

            $attributes = $registered_method->getArguments();

            array_unshift($attributes, $this->parameters);

        } catch (RpcException $re) {

            throw $re;

        }

        set_error_handler(

            function($severity, $message, $file, $line) {

                $this->logger->error($message, array(
                    "FILE" => $file,
                    "LINE" => $line
                ));

                throw new RpcException('Internal error', -32603);

            }

        );

        try {

            // $return = call_user_func($callback, $this->parameters);
            $return = call_user_func_array($callback, $attributes);

        } catch (RpcException $re) {

            restore_error_handler();

            throw $re;

        } catch (Exception $e) {

            restore_error_handler();

            $this->logger->error($e->getMessage(), array(
                "FILE" => $e->getFile(),
                "LINE" => $e->getLine()
            ));

            throw new RpcException('Internal error', -32603);

        }

        restore_error_handler();

        return $return;

    }
458688
public function request($method = null)
	{
		# Verifying if was set method.
		if (!is_null($method)) $this->setMethod($method);
		
		# Verifying if URI is setted.
		if (is_null($this->uri)) {
			throw new RuntimeException('URI must be set before calling request method.');
		}
		
		# Setting default CURL options
		$this->setCurlOpts($this->defaultCurlOpts);
		
		# Verifying and preparing request for specified method.
		switch ($this->method) {
			case 'GET' : 
				// Specific routines for GET request.
				break;
			case 'POST' :
				$this->setCurlOpts(CURLOPT_POST, true); 
				
				if ($this->useRawData) {
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $this->dataRaw);
				} else {
					// Verifying if has files to send
					if (count($this->files) > 0) {
						foreach ($this->files as $k => $v) {
							// Verifying if PHP version is over 5.4
							if (PHP_VERSION_ID < 50500) {
								$this->setParameterPost($k, "@$v");
							} else {
								$cFile = new CURLFile($v,mime_content_type($v),$k);
								$this->setParameterPost($k, $cFile);
							}
						} 
					}
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $this->paramsPost);
				}
				break;
			case 'PUT' : 
				$this->setCurlOpts(CURLOPT_CUSTOMREQUEST, "PUT");
				if ($this->useRawData) {
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $this->dataRaw);
				} else {
					$data = http_build_query($this->paramsPost);
					$this->setCurlOpts(CURLOPT_POSTFIELDS, $data);
				}
				break;
			case 'DELETE' : 
				$this->setCurlOpts(CURLOPT_CUSTOMREQUEST, "DELETE");
				break;
		}
		
		# Rendering GET parameters into a query string.
		$queryString = (count($this->paramsGet) > 0) ? '?' . http_build_query($this->paramsGet) : '';
		
		# Preparing and setting URI in CURL options
		$uri = $this->uri . $queryString;
		$this->setCurlOpts(CURLOPT_URL, $uri);
		
		# Parsing headers
		$headers = array();
		foreach ($this->headers as $key => $value) {
			$headers[] = $key . ': ' . $value;
		}
		$this->setCurlOpts(CURLOPT_HTTPHEADER, $headers);
		
		# Setting remaining options in CURL
		$this->setCurlOpts(array(
			CURLOPT_HTTP_VERSION=>$this->httpVersion,
		));
		
		# Initializing Request
		$ch = curl_init();
		curl_setopt_array($ch, $this->curlOpts);
		
		# Performing Request
		$response = curl_exec($ch);
		
		# Verifying if request was successfully executed.
		if (!$response) {
			throw new RuntimeException('cURL Request Error: ' . curl_errno($ch));
		}
		
		# Closing handle
		curl_close($ch);
		
		# Verifying if a custom response handler was set
		if (!is_null($this->responseHandler)) {
			$this->response = $this->responseHandler->fromString($response);
		} else {
			$this->response = Response::fromString($response);
		}
		
		# Saving last instance in Client
		$this->lastRequest = clone $this;
		
		# Verifying noReset control var
		if (!$this->noReset) {
			$this->reset();
		}
		
		return $this->response;
	}
1079044
def _RunMethod(self, method_config, request, global_params=None,
                   upload=None, upload_config=None, download=None):
        """"""
        if upload is not None and download is not None:
            # TODO(craigcitro): This just involves refactoring the logic
            # below into callbacks that we can pass around; in particular,
            # the order should be that the upload gets the initial request,
            # and then passes its reply to a download if one exists, and
            # then that goes to ProcessResponse and is returned.
            raise exceptions.NotYetImplementedError(
                'Cannot yet use both upload and download at once')

        http_request = self.PrepareHttpRequest(
            method_config, request, global_params, upload, upload_config,
            download)

        # TODO(craigcitro): Make num_retries customizable on Transfer
        # objects, and pass in self.__client.num_retries when initializing
        # an upload or download.
        if download is not None:
            download.InitializeDownload(http_request, client=self.client)
            return

        http_response = None
        if upload is not None:
            http_response = upload.InitializeUpload(
                http_request, client=self.client)
        if http_response is None:
            http = self.__client.http
            if upload and upload.bytes_http:
                http = upload.bytes_http
            opts = {
                'retries': self.__client.num_retries,
                'max_retry_wait': self.__client.max_retry_wait,
            }
            if self.__client.check_response_func:
                opts['check_response_func'] = self.__client.check_response_func
            if self.__client.retry_func:
                opts['retry_func'] = self.__client.retry_func
            http_response = http_wrapper.MakeRequest(
                http, http_request, **opts)

        return self.ProcessHttpResponse(method_config, http_response, request)
1362679
private function executeGqlAsBasicQuery(ProtocolMessage $obj_gql_request)
    {
        // Set up the new request
        $obj_query_request = $this->setupRunQuery();
        $obj_query = $obj_query_request->mutableQuery();

        // Transfer any transaction data to the new request
        /** @var RunQueryRequest $obj_gql_request */
        if($obj_gql_request->mutableReadOptions()->hasTransaction()) {
            $obj_query_request->mutableReadOptions()->setTransaction($obj_gql_request->mutableReadOptions()->getTransaction());
        }

        // Parse the GQL string
        $obj_gql_query = $obj_gql_request->getGqlQuery();
        $obj_parser = new ProtoBufGQLParser($this->obj_schema);
        $obj_parser->parse($obj_gql_query->getQueryString(), $obj_gql_query->getNameArgList());

        // Start applying to the new RunQuery request
        $obj_query->addKind()->setName($obj_parser->getKind());
        foreach($obj_parser->getOrderBy() as $arr_order_by) {
            $obj_query->addOrder()->setDirection($arr_order_by['direction'])->mutableProperty()->setName($arr_order_by['property']);
        }

        // Limits, Offsets, Cursors
        $obj_parser->getLimit() && $obj_query->setLimit($obj_parser->getLimit());
        $obj_parser->getOffset() && $obj_query->setOffset($obj_parser->getOffset());
        $obj_parser->getStartCursor() && $obj_query->setStartCursor($obj_parser->getStartCursor());
        // @todo @ $obj_query->setEndCursor();

        // Filters
        $int_filters = count($obj_parser->getFilters());
        if(1 === $int_filters) {
            $this->configureFilterFromGql($obj_query->mutableFilter()->mutablePropertyFilter(), $obj_parser->getFilters()[0]);
        } else if (1 < $int_filters) {
            $obj_composite_filter = $obj_query->mutableFilter()->mutableCompositeFilter()->setOperator(\google\appengine\datastore\v4\CompositeFilter\Operator::AND_);
            foreach ($obj_parser->getFilters() as $arr_filter) {
                $this->configureFilterFromGql($obj_composite_filter->addFilter()->mutablePropertyFilter(), $arr_filter);
            }
        }
        return $this->execute('RunQuery', $obj_query_request, new RunQueryResponse());
    }
1337495
public static void callMethod(final Object obj, final String methodName, final boolean includePrivateMehtods, final Object... args)
			throws InvocationTargetException {
		final Class[] intArgsClass = initParamsClasses(args);
		try {
			Class<?> current = obj.getClass();
			Method method = null;
			while (current != Object.class) {
				try {
					method = current.getDeclaredMethod(methodName, intArgsClass);
					break;
				} catch (final NoSuchMethodException ex) {
					current = current.getSuperclass();
				}
			}
			if (method == null) {
				throw new NoSuchMethodException("Mehtod is not found in " + current);
			}
			method.setAccessible(true);
			method.invoke(obj, args);
		} catch (final InvocationTargetException e) {
			throw new InvocationTargetException(e.getCause());
		} catch (final Exception e) {
			throw new InvocationTargetException(e);
		}
	}
1198785
public function run($method = null, $url = null)
    {
        // Initiate the apps.
        try {
            AppManager::getInstance()->initApps();
        } catch (AlreadyInitiatedException $exception) {
            // Ignore, this can happen when in tests for example.
        }

        // Prepare the session loading.
        if (! headers_sent()) { // @codeCoverageIgnore
            if (Http::getInstance()->getSession() !== null && ! Http::getInstance()->getSession()->isStarted()) { // @codeCoverageIgnore
                Http::getInstance()->getSession()->start(); // @codeCoverageIgnore
            }
        }

        // Begin parsing request.
        if ($method === null) $method = Http::getInstance()->getRequest()->getMethod();
        if ($url === null) {
            $url = $_SERVER['REQUEST_URI'];
            // Strip query from url
            if (strstr($url, '?')) {
                $parts = explode('?', $url, 2);
                $url = $parts[0];
            }
        }

        // Compile
        $this->compiled = strtoupper($method) . '~' . $url;

        // Try to match
        foreach($this->routes as $route) {
            if ($route->match($this->compiled)) {
                Http::getInstance()->setRoute($route);
                $this->executeRoute($route, $method);
                return;
            }
        }

        // Try to match debug routes.
        if (Configuration::get('app.env') === 'development' && Configuration::get('app.profiler', false)) {
            if (strpos(Http::getInstance()->getRequest()->getPathInfo(), '/__debug__') === 0) { // @codeCoverageIgnore
                $response = DebugBarHelper::getInstance()->processDebugRequest(Http::getInstance()->getRequest()); // @codeCoverageIgnore
                if ($response instanceof Response) { // @codeCoverageIgnore
                    $response->prepare(Http::getInstance()->getRequest()); // @codeCoverageIgnore
                    $response->send(); // @codeCoverageIgnore
                    return; // @codeCoverageIgnore
                }
            }
        }

        // 404
        if ($this->notFoundRoute === null) {
            throw new NotFoundException('Route not found!');
        }
        Http::getInstance()->setRoute($this->notFoundRoute);
        $this->executeRoute($this->notFoundRoute, $method);
    }
310889
public function call($obj, string $func, int $expire = null, ...$params) {
		$key = $this->generateKey($obj, $func, $params);
		return $this->rememberEverythingWithKey($key, function() use ($obj, $func, $params) {
			return $this->runFunc($obj, $func, $params);
		}, $expire);
	}
918130
def rpc(rpc_method, attrs={}, req_opts=nil)
      body = Encoding.encode_json(attrs)

      resp = self.class.make_http_request(@conn, @service_full_name, rpc_method, Encoding::JSON, req_opts, body)
      if resp.status != 200
        return ClientResp.new(nil, self.class.error_from_response(resp))
      end

      data = Encoding.decode_json(resp.body)
      return ClientResp.new(data, nil)
    end
592627
protected function request($method, $uri, $headers, $payload = null, $responseHeader = false)
    {
        $ch = curl_init($uri);

        $options = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HEADER => $responseHeader,
            CURLOPT_HTTPHEADER => $headers,
        ];

        $options[CURLOPT_CUSTOMREQUEST] = $method;

        if (!is_null($payload)) {
            $options[CURLOPT_POSTFIELDS] = $payload;
        }

        curl_setopt_array($ch, $options);

        $response = curl_exec($ch);

        if (false === $response) {
            throw new \RuntimeException(curl_error($ch));
        }

        $info = curl_getinfo($ch);
        if (200 != $info['http_code'] && 201 != $info['http_code']) {
            throw new \RuntimeException('Error sending request: '.$info['http_code'].' msg: '.$response);
        }

        return $response;
    }
1120127
def _run_search_request(
            self, protocol_request, object_name, protocol_response_class):
        
        not_done = True
        while not_done:
            response_object = self._run_search_page_request(
                protocol_request, object_name, protocol_response_class)
            value_list = getattr(
                response_object,
                protocol.getValueListName(protocol_response_class))
            for extract in value_list:
                yield extract
            not_done = bool(response_object.next_page_token)
            protocol_request.page_token = response_object.next_page_token
535075
private function runCallbacks(&$obj, callable $customCallback = null)
    {
        $factoryCallback = $this->callback();
        if (isset($factoryCallback)) {
            $factoryCallback($obj);
        }
        if (isset($customCallback)) {
            $customCallback($obj);
        }
    }
426507
public function run(RequestInterface $request = null, ResponseInterface $response = null)
    {

        if (is_null($request)) {
            if (!$this->getContainer()->has('request')) {
                if ($this->getContainer()->has('Psr\Http\Message\ServerRequestInterface')) {
                    $this->getContainer()->add('request', 'Psr\Http\Message\ServerRequestInterface');
                } else if ($this->getContainer()->has('Psr\Http\Message\RequestInterface')) {
                    $this->getContainer()->add('request', 'Psr\Http\Message\RequestInterface');
                }
            }
            $request = $this->getContainer()->get('request');
        }
        if (is_null($response)) {
            if (!$this->getContainer()->has('response') && $this->getContainer()->has('Psr\Http\Message\ResponseInterface')) {
                $this->getContainer()->add('response', 'Psr\Http\Message\ResponseInterface');
            }
            $response = $this->getContainer()->get('response');
        }

        $this->getContainer()->add('request', $request);
        $this->getContainer()->add('response', $response);

        $this->setErrorHandler();
        $this->getKernel()->run($request, $response);

        if ($this->getLogger()) {
            if ($request instanceof ServerRequestInterface) {
                $this->getLogger()->debug('Script execution time: '.number_format(microtime(true) - $request->getServerParams()['REQUEST_TIME_FLOAT'], 3).' s');
            }
            $this->getLogger()->debug('Memory usage: '.number_format(memory_get_usage()/1024/1024, 3).' MB.');
        }
    }