Esempio n. 1
0
 /**
  * Makes api request
  *
  * @param   string     $qid     The id of the query.
  * @param   array      $options optional Query options for the request.
  * @param   string     $path    optional Uri path for the request (/user by default)
  * @param   string     $method  optional Http method (GET by default)
  * @return  object     Returns object that is an response data.
  * @throws  CloudynException
  */
 public function call($qid, array $options = array(), $path = '/user', $method = 'GET')
 {
     $options['qid'] = (string) $qid;
     $options['out'] = self::OUT_JSON;
     if (!isset($options['rqid'])) {
         $options['rqid'] = $this->getRequestId();
     }
     if (!isset($options['apiversion'])) {
         $options['apiversion'] = '0.4';
     }
     $this->request = $this->createNewRequest();
     $this->request->setUrl($this->getUrl() . $path);
     $this->request->setMethod(constant('HTTP_METH_' . strtoupper($method)));
     $this->request->setOptions(array('redirect' => 10, 'useragent' => 'Scalr Client (http://scalr.com)'));
     $this->request->addQueryData($options);
     //This line is very necessary or HttpResponce will add stored cookies
     $this->request->resetCookies();
     $this->message = $this->tryCall($this->request);
     $json = $this->message->getBody();
     $json = preg_replace('#^[^\\{\\[]+|[^\\}\\]]+$#', '', trim($json));
     $obj = json_decode($json);
     if (isset($obj->status) && $obj->status != 'ok' && isset($obj->message)) {
         throw new CloudynException('Cloudyn error. ' . $obj->message);
     }
     return $obj;
 }
Esempio n. 2
0
 /**
  * Perform the HTTP request.
  *
  * @param      \phpcouch\http\HttpRequest HTTP Request object
  *
  * @return     \phpcouch\http\HttpResponse  The response from the server
  *
  * @author     Simon Thulbourn <*****@*****.**>
  * @since      1.0.0
  */
 public function sendRequest(\phpcouch\http\HttpRequest $request)
 {
     $internalRequest = new \HttpRequest($request->getDestination(), self::$httpMethods[$request->getMethod()]);
     // additional headers
     foreach ($request->getHeaders() as $key => $values) {
         foreach ($values as $value) {
             $this->headers[$key] = $value;
         }
     }
     if (!isset($this->headers['Content-Type'])) {
         $this->headers['Content-Type'] = 'application/json';
     }
     if (null !== ($payload = $request->getContent())) {
         if (is_resource($payload)) {
             // This adapter has no real stream support as of now
             $payload = stream_get_contents($payload, -1, 0);
         }
         if ('PUT' == $request->getMethod()) {
             $internalRequest->setPutData($payload);
         } elseif ('POST' == $request->getMethod()) {
             $internalRequest->setBody($payload);
             $this->headers['Content-Length'] = strlen($payload);
         }
     }
     $internalRequest->addHeaders($this->headers);
     $message = new \HttpMessage($internalRequest->send());
     $response = new HttpResponse();
     $response->setStatusCode($message->getResponseCode());
     if (!isset($response)) {
         throw new TransportException('Could not read HTTP response status line');
     }
     foreach ($message->getHeaders() as $key => $value) {
         $response->setHeader($key, $value);
     }
     $response->setContent($message->getBody());
     if ($message->getResponseCode() >= 400) {
         if ($message->getResponseCode() % 500 < 100) {
             // a 5xx response
             throw new HttpServerErrorException($message->getResponseStatus(), $message->getResponseCode(), $response);
         } else {
             // a 4xx response
             throw new HttpClientErrorException($message->getResponseStatus(), $message->getResponseCode(), $response);
         }
     }
     return $response;
 }
Esempio n. 3
0
 /**
  * {@inheritdoc}
  * @see Scalr\Service\OpenStack\Client.ClientResponseInterface::hasError()
  */
 public function hasError()
 {
     if (!isset($this->errorData)) {
         $this->errorData = false;
         $code = $this->message->getResponseCode();
         if ($code < 200 || $code > 299) {
             $this->errorData = new ErrorData();
             if ($this->format == AppFormat::APP_JSON) {
                 $d = @json_decode($this->getContent());
                 if ($d === null) {
                     $this->errorData->code = $code;
                     $this->errorData->message = strip_tags($this->getContent());
                     $this->errorData->details = '';
                 } else {
                     list(, $v) = each($d);
                     if (is_object($v)) {
                         $this->errorData->code = $v->code;
                         $this->errorData->message = $v->message;
                         $this->errorData->details = isset($v->details) ? (string) $v->details : '';
                     } else {
                         //QuantumError
                         $this->errorData->code = $code;
                         $this->errorData->message = (string) $v;
                         $this->errorData->details = '';
                     }
                 }
             } else {
                 if ($this->format == AppFormat::APP_XML) {
                     $d = simplexml_load_string($this->getContent());
                     $this->errorData->code = $code;
                     $this->errorData->message = isset($d->message) ? (string) $d->message : '';
                     $this->errorData->details = isset($d->details) ? (string) $d->details : '';
                 } else {
                     throw new \InvalidArgumentException(sprintf('Unexpected application format "%s" in class %s', (string) $this->format, get_class($this)));
                 }
             }
             throw new RestClientException($this->errorData);
         }
     }
     return $this->errorData;
 }
Esempio n. 4
0
 public function __construct(HttpMessage $response = null)
 {
     if ($response && $response->getType() != HTTP_MSG_RESPONSE) {
         throw new Kwf_Exception("invalid response type");
     }
     if ($response && ($response->getResponseCode() == 301 || $response->getResponseCode() == 302)) {
         //workaround for strange pecl_http bug that breaks requests that redirect to the same url again
         //and for some reason then there is only response message containing in the body the second response message (including http headers)
         if (preg_match('#^HTTP/1\\.. [0-9]{3} #', $response->getBody())) {
             $r = HttpMessage::factory($response->getBody());
             if ($r->getType() == HTTP_MSG_RESPONSE) {
                 $response = $r;
             }
         }
     }
     $this->_response = $response;
 }
Esempio n. 5
0
 /**
  * Deep clone of this instance
  *
  * @return void
  */
 public function __clone()
 {
     parent::__clone();
     if ($this->_url instanceof HttpUrl) {
         $this->_url = clone $this->_url;
     }
 }
Esempio n. 6
0
 /**
  * Send a HTTP response.
  *
  * @param int $code
  * @param string $mimetype
  * @param string $body
  * @param array $headers
  * @return void
  */
 private function returnResponse($code, $body = '', $mimetype = 'text/plain', array $headers = array())
 {
     $msg = new HttpMessage();
     $msg->setType(HttpMessage::TYPE_RESPONSE);
     $msg->setResponseCode($code);
     $msg->setResponseStatus(self::$statuses[$code]);
     $headers['Content-Type'] = (string) $mimetype;
     $headers['Content-Length'] = (string) strlen($body);
     $msg->setHeaders($headers);
     $msg->setBody($body);
     fwrite($this->conn, $msg->toString());
 }
Esempio n. 7
0
 public function getBody()
 {
     return $this->_message->getBody();
 }
 public function getBody()
 {
     $content = array('body' => parent::getBody(), 'content-type' => $this->getHeader('content-type'));
     $document = array('url' => $this->getUrl(), 'content' => $content);
     return $this->getCharsetFront()->convert($document);
 }
Esempio n. 9
0
 /**
  * Initializes the default configuration for the object
  *
  * Called from {@link __construct()} as a first step of object instantiation.
  *
  * @param  ObjectConfig $config  An optional ObjectConfig object with configuration options.
  * @return void
  */
 protected function _initialize(ObjectConfig $config)
 {
     $config->append(array('content' => '', 'content_type' => 'text/html', 'status_code' => '200', 'status_message' => null, 'headers' => array()));
     parent::_initialize($config);
 }
Esempio n. 10
0
 public function __construct(int $status = Http::OK, array $headers = [], string $protocolVersion = '1.1')
 {
     parent::__construct($headers, $protocolVersion);
     $this->status = $this->filterStatus($status);
     $this->reason = '';
 }
Esempio n. 11
0
 public function getHeaders() : array
 {
     $headers = parent::getHeaders();
     if (empty($this->headers['host']) && $this->uri !== NULL && !empty($this->uri->getHost())) {
         $headers['Host'] = $this->getHeader('Host');
     }
     return $headers;
 }
Esempio n. 12
0
function response_dump(HttpMessage $res)
{
    printf("Code: %d\n", $res->getResponseCode());
    printf("Body: %s\n", $res->getBody());
}
Esempio n. 13
0
/**
 * Test HttpMessage.
 */
function test_HttpMessage()
{
    $message = new HttpMessage();
    echo $message->setResponseCode(200);
}
Esempio n. 14
0
 /**
  * {@inheritdoc}
  * @see Scalr\Service\Aws\Client.ClientResponseInterface::getResponseStatus()
  */
 public function getResponseStatus()
 {
     return $this->message->getResponseStatus();
 }
Esempio n. 15
0
 /**
  * Set all of the headers. This will overwrite any existing headers.
  *
  * @param array|string $headers An array or string of headers to set.
  *
  * The array of headers can be in the following form:
  *
  * - ["Header-Name" => "value", ...]
  * - ["Header-Name" => ["lines, ...], ...]
  * - ["Header-Name: value", ...]
  * - Any combination of the above formats.
  *
  * A header string is the the form of the HTTP standard where each Key: Value pair is separated by `\r\n`.
  *
  * @return HttpResponse Returns `$this` for fluent calls.
  */
 public function setHeaders($headers)
 {
     parent::setHeaders($headers);
     if ($statusLine = $this->parseStatusLine($headers)) {
         $this->setStatus($statusLine);
     }
     return $this;
 }
Esempio n. 16
0
 /**
  * Pecl HTTP request headers
  *
  * If the pecl_http extension is loaded use it to get the incoming
  * request headers, otherwise return null. Abstracted for testing
  * purposes.
  *
  * @return array|null Headers or null if no extension
  */
 protected function peclHttpHeaders()
 {
     if (extension_loaded('http') && class_exists('HttpMessage')) {
         $message = HttpMessage::fromEnv(HttpMessage::TYPE_REQUEST);
         return $message->getHeaders();
     }
     return null;
 }
Esempio n. 17
0
 /**
  * Fetches properties from the response.
  *
  * @param \HttpMessage $response Response
  * @return array
  */
 private function getProperties(\HttpMessage $response)
 {
     // Process the XML with properties
     $properties = array();
     $reader = new \Jyxo\XmlReader();
     $reader->XML($response->getBody());
     // Ignore warnings
     while (@$reader->read()) {
         if (\XMLReader::ELEMENT === $reader->nodeType && 'D:prop' === $reader->name) {
             while (@$reader->read()) {
                 // Element must not be empty and has to look something like <lp1:getcontentlength>13744</lp1:getcontentlength>
                 if (\XMLReader::ELEMENT === $reader->nodeType && !$reader->isEmptyElement) {
                     if (preg_match('~^lp\\d+:(.+)$~', $reader->name, $matches)) {
                         // Apache
                         $properties[$matches[1]] = $reader->getTextValue();
                     } elseif (preg_match('~^D:(.+)$~', $reader->name, $matches)) {
                         // Lighttpd
                         $properties[$matches[1]] = $reader->getTextValue();
                     }
                 } elseif (\XMLReader::END_ELEMENT === $reader->nodeType && 'D:prop' === $reader->name) {
                     break;
                 }
             }
         }
     }
     return $properties;
 }
Esempio n. 18
0
    public function testExecute()
    {
        $statusCode = 200;
        $statusMessage = 'OK';
        $body = 'data';
        $data = <<<EOF
HTTP/1.1 {$statusCode} {$statusMessage}
X-Foo: test

{$body}
EOF;
        $request = new Request();
        $endpoint = new Endpoint();
        $mockHttpRequest = $this->getMock('HttpRequest');
        $mockHttpRequest->expects($this->once())->method('send')->will($this->returnValue(\HttpMessage::factory($data)));
        $mock = $this->getMock('Solarium\\Core\\Client\\Adapter\\PeclHttp', array('toHttpRequest'));
        $mock->expects($this->once())->method('toHttpRequest')->with($request, $endpoint)->will($this->returnValue($mockHttpRequest));
        $response = $mock->execute($request, $endpoint);
        $this->assertEquals($body, $response->getBody());
        $this->assertEquals($statusCode, $response->getStatusCode());
        $this->assertEquals($statusMessage, $response->getStatusMessage());
    }
Esempio n. 19
0
 /**
  * Set the content for this message.
  *
  * @param      mixed The content to be sent in this message.
  */
 public function setContent($content)
 {
     if (is_array($content)) {
         // Create a multipart/related request
         // (use a temp stream as the data might be huge and concatting it would double the memory usage)
         $fp = fopen('php://temp', 'w+');
         $boundary = md5(uniqid(mt_rand(), true));
         foreach ($content as $i => $part) {
             fwrite($fp, '--');
             fwrite($fp, $boundary);
             fwrite($fp, "\r\n");
             if ($i == 0 && ($contentType = $this->getContentType())) {
                 // Use content type for first part only (the document)
                 fwrite($fp, 'Content-Type: ');
                 fwrite($fp, $contentType);
                 fwrite($fp, "\r\n");
             }
             fwrite($fp, "\r\n");
             if (is_resource($part)) {
                 stream_copy_to_stream($part, $fp, -1, 0);
             } else {
                 fwrite($fp, $part);
             }
             fwrite($fp, "\r\n");
         }
         fwrite($fp, '--');
         fwrite($fp, $boundary);
         fwrite($fp, '--');
         fwrite($fp, "\r\n");
         $content = $fp;
         $this->setContentType('multipart/related;boundary="' . $boundary . '"');
     }
     parent::setContent($content);
 }