Example #1
0
 /**
  * @param RequestInterface $httpRequest
  * @return EchoResponse
  */
 private function sendAndProcessResponse(RequestInterface $httpRequest)
 {
     $httpResponse = $httpRequest->send();
     $data = $httpResponse->json();
     $response = new EchoResponse($this, $data);
     $response->setVerifier($this->getVerifier());
     return $response;
 }
Example #2
0
 private function sendRequest(RequestInterface $request)
 {
     try {
         return $request->send();
     } catch (\Exception $e) {
         throw new GithubException('Unexpected response.', 0, $e);
     }
 }
Example #3
0
 private function request(RequestInterface $request)
 {
     try {
         $response = $request->send();
     } catch (BadResponseException $e) {
         throw new Exception(sprintf('7digital API responded with an error %d.', $e->getResponse()->getStatusCode()), 0, $e);
     }
     return $this->getContent($response);
 }
Example #4
0
 /**
  * @param RequestInterface $request
  * @return array|mixed
  */
 public function sendOAuth(RequestInterface $request)
 {
     try {
         $response = $request->send();
     } catch (ClientErrorResponseException $e) {
         return ["Error" => "Error:" . $e->getMessage()];
     }
     $return = json_decode($response->getBody(), true);
     if (array_key_exists("expires_in", $return)) {
         $return["expires_at"] = (int) (date("U") + $return["expires_in"]);
     }
     return $return;
 }
 /**
  * Sends a request
  *
  * @param RequestInterface $request
  * @return Response
  * @throws ForbiddenException
  * @throws MetricaException
  */
 protected function sendRequest(RequestInterface $request)
 {
     try {
         $request->setHeader('User-Agent', $this->getUserAgent());
         $response = $request->send();
     } catch (ClientErrorResponseException $ex) {
         $result = $request->getResponse();
         $code = $result->getStatusCode();
         $message = $result->getReasonPhrase();
         if ($code === 403) {
             throw new ForbiddenException($message);
         }
         throw new MetricaException('Service responded with error code: "' . $code . '" and message: "' . $message . '"');
     }
     return $response;
 }
 /**
  * Get the issue count from the provided request.
  *
  *
  * @param array $request
  *   Guzzle request for the first page of results.
  * @return number
  *   The total number of issues for the search paramaters of the request.
  */
 public function getCount(\Guzzle\Http\Message\RequestInterface $request)
 {
     // Make sure page isn't set from a previous call on the same request object.
     $request->getQuery()->remove('page');
     $issueRowCount = 0;
     while (true) {
         $document = new DomCrawler\Crawler((string) $request->send()->getBody());
         $issueView = $document->filter('.view-project-issue-search-project-searchapi');
         $issueRowCount += $issueView->filter('table.views-table tbody tr')->reduce(function (DomCrawler\Crawler $element) {
             // Drupal.org is returning rows where all cells are empty,
             // which bumps up the count incorrectly.
             return $element->filter('td')->first()->filter('a')->count() > 0;
         })->count();
         $pagerNext = $issueView->filter('.pager-next a');
         if (!$pagerNext->count()) {
             break;
         }
         preg_match('/page=(\\d+)/', $pagerNext->attr('href'), $urlMatches);
         $request->getQuery()->set('page', (int) $urlMatches[1]);
     }
     return $issueRowCount;
 }
Example #7
0
File: Api.php Project: lsv/jwapi
 /**
  * Sets the response
  *
  * @param  RequestInterface $request
  * @return Response
  */
 protected function setResponse(RequestInterface $request)
 {
     try {
         $this->response = $request->send();
     } catch (ClientErrorResponseException $exception) {
         $this->response = $exception->getResponse();
         // @codeCoverageIgnoreStart
     } catch (ServerErrorResponseException $exception) {
         $this->response = $exception->getResponse();
     }
     // @codeCoverageIgnoreEnd
     return $this->response;
 }
Example #8
0
 /**
  * Perform a http request and return the response
  *
  * @param \Guzzle\Http\Message\RequestInterface $request the request to preform
  * @param bool $async whether or not to perform an async request
  *
  * @return \Guzzle\Http\Message\Response|mixed the response from elastic search
  * @throws \Exception
  */
 public function perform(\Guzzle\Http\Message\RequestInterface $request, $async = false)
 {
     try {
         $profileKey = null;
         if ($this->enableProfiling) {
             $profileKey = __METHOD__ . '(' . $request->getUrl() . ')';
             if ($request instanceof \Guzzle\Http\Message\EntityEnclosingRequest) {
                 $profileKey .= " " . $request->getBody();
             }
             Yii::beginProfile($profileKey);
         }
         $response = $async ? $request->send() : json_decode($request->send()->getBody(true), true);
         Yii::trace("Sent request to '{$request->getUrl()}'", 'application.elastic.connection');
         if ($this->enableProfiling) {
             Yii::endProfile($profileKey);
         }
         return $response;
     } catch (\Guzzle\Http\Exception\BadResponseException $e) {
         $body = $e->getResponse()->getBody(true);
         if (($msg = json_decode($body)) !== null && isset($msg->error)) {
             throw new \CException($msg->error);
         } else {
             throw new \CException($e);
         }
     } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
         throw new \CException($e->getResponse()->getBody(true));
     }
 }
Example #9
0
 /**
  * Process request into a response object
  *
  * @param RequestInterface $request
  * @return \Guzzle\Http\Message\Response
  * @throws \Dlin\Zendesk\Exception\ZendeskException
  */
 public function processRequest(RequestInterface $request)
 {
     $response = $request->send();
     $attempt = 0;
     while ($response->getStatusCode() == 429 && $attempt < 5) {
         $wait = $response->getHeader('Retry-After');
         if ($wait > 0) {
             sleep($wait);
         }
         $attempt++;
         $response = $request->send();
     }
     if ($response->getStatusCode() >= 500) {
         throw new ZendeskException('Zendesk Server Error Detected.');
     }
     if ($response->getStatusCode() >= 400) {
         if ($response->getContentType() == 'application/json') {
             $result = $response->json();
             $description = array_key_exists($result, 'description') ? $result['description'] : 'Invalid Request';
             $value = array_key_exists($result, 'value') ? $result['value'] : array();
             $exception = new ZendeskException($description);
             $exception->setError($value);
             throw $exception;
         } else {
             throw new ZendeskException('Invalid API Request');
         }
     }
     return $response;
 }
Example #10
0
 private function exec(\Guzzle\Http\Message\RequestInterface $request)
 {
     $start = microtime(true);
     $this->responseCode = 0;
     // Get snapshot of request headers.
     $request_headers = $request->getRawHeaders();
     // Mask authorization for logs.
     $request_headers = preg_replace('!\\nAuthorization: (Basic|Digest) [^\\r\\n]+\\r!i', "\nAuthorization: \$1 [**masked**]\r", $request_headers);
     try {
         $response = $request->send();
     } catch (\Guzzle\Http\Exception\BadResponseException $e) {
         $response = $e->getResponse();
     } catch (\Guzzle\Http\Exception\CurlException $e) {
         // Timeouts etc.
         DebugData::$raw = '';
         DebugData::$code = $e->getErrorNo();
         DebugData::$code_status = $e->getError();
         DebugData::$code_class = 0;
         DebugData::$exception = $e->getMessage();
         DebugData::$opts = array('request_headers' => $request_headers);
         DebugData::$data = null;
         $exception = new ResponseException($e->getError(), $e->getErrorNo(), $request->getUrl(), DebugData::$opts);
         $exception->requestObj = $request;
         // Log Exception
         $headers_array = $request->getHeaders();
         unset($headers_array['Authorization']);
         $headerString = '';
         foreach ($headers_array as $value) {
             $headerString .= $value->getName() . ': ' . $value . " ";
         }
         $log_message = '{code_status} ({code}) Request Details:[ {r_method} {r_resource} {r_scheme} {r_headers} ]';
         $httpScheme = strtoupper(str_replace('https', 'http', $request->getScheme())) . $request->getProtocolVersion();
         $log_params = array('code' => $e->getErrorNo(), 'code_status' => $e->getError(), 'r_method' => $request->getUrl(), 'r_resource' => $request->getRawHeaders(), 'r_scheme' => $httpScheme, 'r_headers' => $headerString);
         self::$logger->emergency($log_message, $log_params);
         throw $exception;
     }
     $this->responseCode = $response->getStatusCode();
     $this->responseText = trim($response->getBody(true));
     $this->responseLength = $response->getContentLength();
     $this->responseMimeType = $response->getContentType();
     $this->responseObj = array();
     $content_type = $response->getContentType();
     $firstChar = substr($this->responseText, 0, 1);
     if (strpos($content_type, '/json') !== false && ($firstChar == '{' || $firstChar == '[')) {
         $response_obj = @json_decode($this->responseText, true);
         if (is_array($response_obj)) {
             $this->responseObj = $response_obj;
         }
     }
     $status = self::getStatusMessage($this->responseCode);
     $code_class = floor($this->responseCode / 100);
     DebugData::$raw = $this->responseText;
     DebugData::$opts = array('request_headers' => $request_headers, 'response_headers' => $response->getRawHeaders());
     if ($request instanceof \Guzzle\Http\Message\EntityEnclosingRequestInterface) {
         DebugData::$opts['request_body'] = (string) $request->getBody();
     }
     DebugData::$opts['request_type'] = class_implements($request);
     DebugData::$data = $this->responseObj;
     DebugData::$code = $this->responseCode;
     DebugData::$code_status = $status;
     DebugData::$code_class = $code_class;
     DebugData::$exception = null;
     DebugData::$time_elapsed = microtime(true) - $start;
     if ($code_class != 2) {
         $uri = $request->getUrl();
         if (!empty($this->responseCode) && isset($this->responseObj['message'])) {
             $message = 'Code: ' . $this->responseCode . '; Message: ' . $this->responseObj['message'];
         } else {
             $message = 'API returned HTTP code of ' . $this->responseCode . ' when fetching from ' . $uri;
         }
         DebugData::$exception = $message;
         $this->debugCallback(DebugData::toArray());
         self::$logger->error($this->responseText);
         // Create better status to show up in logs
         $status .= ': ' . $request->getMethod() . ' ' . $uri;
         if ($request instanceof \Guzzle\Http\Message\EntityEnclosingRequestInterface) {
             $body = $request->getBody();
             if ($body instanceof \Guzzle\Http\EntityBodyInterface) {
                 $status .= ' with Content-Length of ' . $body->getContentLength() . ' and Content-Type of ' . $body->getContentType();
             }
         }
         $exception = new ResponseException($status, $this->responseCode, $uri, DebugData::$opts, $this->responseText);
         $exception->requestObj = $request;
         $exception->responseObj = $response;
         throw $exception;
     }
     $this->debugCallback(DebugData::toArray());
 }
Example #11
0
 /**
  * Function saying according to the status code if the injection was a success or not
  * @param RequestInterface $req
  * @param $url
  * @return array
  * @internal param SqlTarget $target
  */
 public function goslingResponse(RequestInterface $req, $url)
 {
     $success = false;
     $res = $req->send();
     $status_code = $res->getStatusCode();
     if ($status_code == 200) {
         // Create a request that has a query string and an X-Foo header
         $request = $this->_guzzle->get($url);
         // Send the request and get the response
         $response = $request->send();
         // Connection to DB
         $repo = $this->_em->getRepository('AppBundle:HtmlError');
         $html_errors = $repo->findAll();
         foreach ($html_errors as $html_error) {
             if (preg_match($html_error->getValue(), $response->getBody(true))) {
                 $success = true;
             }
         }
     }
     $result = array("Success" => $success, "Status_code" => $status_code);
     return $result;
 }
Example #12
0
 /**
  * Send datas trough HTTP client
  *
  * @param HttpRequestInterface $request
  *
  * @param bool                 $stopOnException
  *
  * @return HttpResponse
  * @throws \Exception
  */
 protected function send(HttpRequestInterface $request, $stopOnException = false)
 {
     $request->setHeader('Content-Type', 'application/json')->setHeader('X-Auth-Token', array($this->token))->setHeader('X-Auth-UserId', array($this->userId));
     try {
         $response = $request->send();
     } catch (ClientErrorResponseException $e) {
         if (!$stopOnException && 401 == $e->getResponse()->getStatusCode() && null != $this->username) {
             // If the HTTP error is 401 Unauthorized, the session is cleared
             $username = $this->username;
             $password = $this->password;
             $this->clearSession();
             // Then we try a new authentication
             $this->getUserToken($username, $password);
             // Then we resend the request once
             $response = $this->send($request, true);
         } else {
             throw $e;
         }
     }
     if (!$response) {
         throw new \Exception(__NAMESPACE__ . '\\' . __CLASS__ . ' : Bad response while sending the request');
     }
     return $response;
 }
Example #13
0
 private function send(RequestInterface $request)
 {
     try {
         $this->logger and $this->logger->debug(sprintf('%s "%s"', $request->getMethod(), $request->getUrl()));
         $this->logger and $this->logger->debug(sprintf("Request:\n%s", (string) $request));
         $response = $request->send();
         $this->logger and $this->logger->debug(sprintf("Response:\n%s", (string) $response));
         return $response;
     } catch (ClientErrorResponseException $e) {
         $this->logException($e);
         $this->processClientError($e);
     } catch (BadResponseException $e) {
         $this->logException($e);
         throw new ApiServerException('Something went wrong with upstream', 0, $e);
     }
 }
Example #14
0
 /**
  * Sends a request.
  *
  * @param \Guzzle\Http\Message\RequestInterface $request The request.
  *
  * @throws \Widop\HttpAdapter\HttpAdapterException If an error occured.
  *
  * @return \Widop\HttpAdapter\HttpResponse The response.
  */
 private function sendRequest(RequestInterface $request)
 {
     $request->getParams()->set('redirect.max', $this->getMaxRedirects());
     try {
         $response = $request->send();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($request->getUrl(), $this->getName(), $e->getMessage());
     }
     return $this->createResponse($response->getStatusCode(), $request->getUrl(), $response->getHeaders()->toArray(), $response->getBody(true), $response->getEffectiveUrl());
 }
Example #15
0
 /**
  * @{inheritDoc}
  */
 public function request(RequestInterface $request)
 {
     $response = null;
     try {
         $response = $request->send();
     } catch (ClientErrorResponseException $e) {
         $error = $e->getResponse()->json();
         throw new TmdbApiException($error['status_message'], $error['status_code']);
     }
     $this->lastRequest = $request;
     $this->lastResponse = $response;
     return $response;
 }
Example #16
0
 /**
  * fetch file from remote destination
  *
  * @param RequestInterface $request request
  *
  * @return string
  */
 private function fetchFile($request)
 {
     try {
         $response = $request->send();
     } catch (\Guzzle\Http\Exception\CurlException $e) {
         throw new HttpException(Response::HTTP_BAD_GATEWAY, $e->getError(), $e, $e->getRequest()->getHeaders()->toArray(), $e->getCode());
     }
     $content = $response->getBody(true);
     if (isset($this->cache)) {
         $this->cache->save($this->options['storeKey'], $content, $this->cacheLifetime);
     }
     return $content;
 }
 /**
  * @param RequestInterface $request
  * @return array
  * @throws CommunicationError
  * @throws ExpiredAuthRequestError
  * @throws InvalidCredentialsError
  * @throws InvalidRequestError
  * @throws InvalidResponseError
  * @throws LaunchKeyEngineError
  * @throws NoPairedDevicesError
  * @throws NoSuchUserError
  * @throws RateLimitExceededError
  */
 private function sendRequest(RequestInterface $request)
 {
     try {
         $response = $request->send();
         $this->debugLog("Response received", array("response" => $response->getMessage()));
     } catch (ClientErrorResponseException $e) {
         $message = $e->getMessage();
         $code = $e->getCode();
         try {
             $data = $this->jsonDecodeData($request->getResponse()->getBody());
             $this->throwExceptionForErrorResponse($data, $e);
         } catch (InvalidResponseError $de) {
             throw new InvalidRequestError($message, $code, $e);
         }
     } catch (ServerErrorResponseException $e) {
         throw new CommunicationError("Error performing request", $e->getCode(), $e);
     }
     $data = $this->jsonDecodeData($response->getBody(true));
     // If debug response with data in the "response" attribute return that
     return isset($data["response"]) ? $data["response"] : $data;
 }
Example #18
0
 /**
  * @param \Guzzle\Http\Message\RequestInterface $request
  */
 public function __construct(RequestInterface $request)
 {
     $this->response = $request->send();
     parent::__construct($this->response->json());
 }
Example #19
0
 /**
  * @param RequestInterface $request
  *
  * @return array|\Guzzle\Http\Message\Response
  */
 protected function sendRequest(RequestInterface $request)
 {
     try {
         $response = $request->send();
         $this->lastRequest = $request;
     } catch (BadResponseException $e) {
         $response = $e->getResponse();
     }
     $this->lastResponse = $response;
     try {
         return $response->json();
     } catch (Exception $e) {
         return $response->getBody(true);
     }
 }
Example #20
0
 /**
  * Sends a single request to a WebDAV server
  *
  * @param HttpRequest $request
  *            The request
  *            
  * @throws Exception\NoSuchResourceException
  * @throws Exception\HttpException
  * @return HttpResponse Returns the server response
  */
 protected function doRequest(HttpRequest $request)
 {
     $error = null;
     $response = null;
     $this->lastRequest = $request;
     $this->lastResponse = null;
     try {
         $response = $request->send();
     } catch (BadResponseException $error) {
         $response = $error->getResponse();
     }
     // Creates History
     $this->lastResponse = $response;
     if ($error && $this->throwExceptions) {
         switch ($response->getStatusCode()) {
             case 404:
                 throw new NoSuchResourceException('No such file or directory');
             default:
                 throw HttpException::factory($error);
         }
     }
     return $response;
 }
Example #21
0
 /**
  * @param $request RequestInterface
  * @return mixed
  * @throws Exception
  */
 private function sendRequest(RequestInterface $request)
 {
     try {
         $request->send();
     } catch (ClientErrorResponseException $e) {
         $data = json_decode($request->getResponse()->getBody(true), true);
         if ($e->getResponse()->getStatusCode() == 404) {
             throw new CredentialsNotFoundException($data["message"], null, $e);
         } else {
             throw new Exception('Error from Provisioning API: ' . $data["message"], null, $e);
         }
     } catch (BadResponseException $e) {
         throw new Exception('Error receiving response from Provisioning API', null, $e);
     }
     $result = $this->parseResponse($request->getResponse()->getBody(true));
     return $result;
 }
Example #22
0
 public function send()
 {
     $response = $this->responses['video'];
     $response->setGuzzleResponse($this->guzzleRequest->send());
     return $response;
 }
 /**
  * Run guzzle request
  *
  * @param RequestInterface $request
  *
  * @return array
  */
 private function runRequest(RequestInterface $request)
 {
     try {
         $request->send();
         //send the req and return the json
         return $request->getResponse()->json();
     } catch (Exception $e) {
         return array('error' => $request->getResponse()->json());
     }
 }
 /**
  * @param RequestInterface $request
  *
  * @return string|bool
  */
 protected function readXmlData(RequestInterface $request)
 {
     try {
         $response = $request->send();
     } catch (RequestException $exc) {
         $mess = 'Could NOT get XML data';
         $this->getLogger()->debug($mess, ['exception' => $exc]);
         return false;
     }
     return $response->getBody(true);
 }
Example #25
0
 /**
  * {@inheritDoc}
  */
 public function executeRequest(RequestInterface $request, array $validStatusCodes)
 {
     try {
         $response = $request->send();
     } catch (ClientErrorResponseException $e) {
         $response = $e->getResponse();
     }
     // catch some common errors
     if (in_array($response->getStatusCode(), array(401, 403))) {
         throw new AccessDeniedException($response->getBody(true), $response->getStatusCode());
     } elseif (404 === $response->getStatusCode()) {
         throw new NotFoundException($response->getBody(true));
     } elseif (409 === $response->getStatusCode()) {
         throw new ConflictException($response->getBody(true));
     }
     if (!in_array($response->getStatusCode(), $validStatusCodes)) {
         throw new XApiException($response->getBody(true), $response->getStatusCode());
     }
     return $response;
 }