Ejemplo n.º 1
0
 public function validateCybertipSchema(EntityEnclosingRequest $req)
 {
     $xsd = $this->getConfig()->get('xsd');
     $error = null;
     $prev = libxml_use_internal_errors(true);
     try {
         $body = (string) $req->getBody();
         $dom = new \DOMDocument();
         $dom->loadXML($body);
         $ret = $dom->schemaValidateSource($xsd);
         if (!$ret) {
             $error = self::libxmlErrorExceptionFactory();
         }
     } catch (\Exception $e) {
         $error = $e;
     }
     libxml_use_internal_errors($prev);
     if ($error instanceof \Exception) {
         throw $error;
     } else {
         if ($error) {
             throw new XsdValidateException($error);
         }
     }
 }
 public function testSetsCurlHandleParameter()
 {
     $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
     $mediator = new RequestMediator($request);
     $handle = $this->getMockBuilder('Guzzle\\Http\\Curl\\CurlHandle')->disableOriginalConstructor()->getMock();
     $mediator->setCurlHandle($handle);
     $this->assertSame($handle, $request->getParams()->get('curl_handle'));
 }
Ejemplo n.º 3
0
 public function testAddsContentSha256WhenBodyIsPresent()
 {
     $request = new EntityEnclosingRequest('PUT', 'http://foo.com');
     $request->setBody('foo');
     $credentials = new Credentials('foo', 'bar');
     $signature = new S3SignatureV4('service', 'region');
     $signature->signRequest($request, $credentials);
     $this->assertEquals(hash('sha256', 'foo'), $request->getHeader('x-amz-content-sha256'));
 }
Ejemplo n.º 4
0
 public function testGetBody()
 {
     $request1 = $this->getRequest();
     $this->assertEquals('', $request1->getBody());
     $guzzleRequest = new EntityEnclosingRequest('GET', 'http://example.com');
     $guzzleRequest->setBody('test content');
     $request2 = new Guzzle3($guzzleRequest);
     $this->assertEquals('test content', $request2->getBody());
 }
Ejemplo n.º 5
0
 public function testAuthorizationHeader()
 {
     $plugin = $this->getPlugin();
     $uri = 'http://example.com/resource/1?key=value';
     $request = new EntityEnclosingRequest('GET', $uri, array('Content-Type' => 'text/plain', 'Date' => 'Fri, 19 Mar 1982 00:00:04 GMT', 'Custom1' => 'Value1'));
     $request->setBody('test content');
     $plugin->signRequest($request);
     $expected = 'Acquia 1:' . DigestVersion1Test::EXPECTED_HASH;
     $this->assertEquals($expected, (string) $request->getHeader('Authorization'));
 }
Ejemplo n.º 6
0
 public function testEmitsEvents()
 {
     $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
     $request->setBody('foo');
     $request->setResponse(new Response(200));
     // Ensure that IO events are emitted
     $request->getCurlOptions()->set('emit_io', true);
     // Attach listeners for each event type
     $request->getEventDispatcher()->addListener('curl.callback.progress', array($this, 'event'));
     $request->getEventDispatcher()->addListener('curl.callback.read', array($this, 'event'));
     $request->getEventDispatcher()->addListener('curl.callback.write', array($this, 'event'));
     $mediator = new RequestMediator($request, true);
     $mediator->progress('a', 'b', 'c', 'd');
     $this->assertEquals(1, count($this->events));
     $this->assertEquals('curl.callback.progress', $this->events[0]->getName());
     $this->assertEquals(3, $mediator->writeResponseBody('foo', 'bar'));
     $this->assertEquals(2, count($this->events));
     $this->assertEquals('curl.callback.write', $this->events[1]->getName());
     $this->assertEquals('bar', $this->events[1]['write']);
     $this->assertSame($request, $this->events[1]['request']);
     $this->assertEquals('foo', $mediator->readRequestBody('a', 'b', 3));
     $this->assertEquals(3, count($this->events));
     $this->assertEquals('curl.callback.read', $this->events[2]->getName());
     $this->assertEquals('foo', $this->events[2]['read']);
     $this->assertSame($request, $this->events[2]['request']);
 }
Ejemplo n.º 7
0
 /**
  * @return string
  */
 public function send($xml, Port $port, BindingOperation $bindingOperation)
 {
     $url = $port->getDomElement()->evaluate("string(soap:address/@location)", array("soap" => SoapClient::NS));
     $soapAction = $bindingOperation->getDomElement()->evaluate("string(soap:operation/@soapAction)", array("soap" => SoapClient::NS));
     $request = new EntityEnclosingRequest("POST", $url);
     $request->setBody($xml, "text/xml; charset=utf-8");
     $request->addHeader("SOAPAction", '"' . $soapAction . '"');
     if ($this->debugUri) {
         $request->setUrl($this->debugUri);
     }
     try {
         $response = $this->client->send($request);
     } catch (BadResponseException $e) {
         $response = $e->getResponse();
     }
     if (!$response->isSuccessful() && strpos($response->getContentType(), '/xml') === false) {
         throw new TransportException($response->getReasonPhrase(), $response->getStatusCode());
     }
     return $response->getBody(true);
 }
Ejemplo n.º 8
0
 /**
  * Test valid signature for entity-body style requests (POST, PUT, PATCH, DELETE).
  */
 public function testValidSignatureWithEntityBody()
 {
     $method = 'POST';
     $body = '{hello: "world!"}';
     $path = '/say/hello';
     $secret = '456';
     $queryParams = array('fiz' => 'buzz', 'foo' => 'bar');
     $request = new EntityEnclosingRequest($method, $path);
     $request->setBody($body);
     $signature = new Signature($secret, $request);
     $expected = $secret . $method . $path;
     ksort($queryParams);
     foreach ($queryParams as $key => $param) {
         $expected .= "{$key}={$param}";
         $request->getQuery()->set($key, $param);
     }
     $expected .= $body;
     $this->assertEquals($expected, $signature->getRawSignature(), 'Raw signature should include entity-body string.');
     $this->assertEquals(43, strlen($signature), 'Hash signature should be 43 characters in length.');
 }
Ejemplo n.º 9
0
 /**
  * @return string
  */
 public function send($xml, Port $port, BindingOperation $bindingOperation)
 {
     $soapAction = $bindingOperation->getDomElement()->evaluate("string(soap:operation/@soapAction)", array("soap" => SoapClient::NS));
     if (!$soapAction) {
         $soapActionRequired = $bindingOperation->getDomElement()->evaluate("string(soap:operation/@soapActionRequired)", array("soap" => SoapClient::NS));
         if ($soapActionRequired == "true") {
             throw new TransportException("SoapAction required for operation '" . $bindingOperation->getName() . "'", 100);
         }
     }
     $url = $port->getDomElement()->evaluate("string(soap:address/@location)", array("soap" => SoapClient::NS));
     $request = new EntityEnclosingRequest("POST", $url);
     $request->setBody($xml, 'application/soap+xml; charset=utf-8;  action="' . $soapAction . '"');
     if ($this->debugUri) {
         $request->setUrl($this->debugUri);
     }
     $response = $this->client->send($request);
     if (!$response->isSuccessful()) {
         throw new TransportException($response->getReasonPhrase(), $response->getStatusCode());
     }
     return $response->getBody(true);
 }
 /**
  * @return EntityBody|\Guzzle\Http\EntityBodyInterface|null
  */
 public function getBody()
 {
     if (!$this->body) {
         $body = '';
         $contentType = $this->originalContentType ?: $this->getHeader('Content-Type');
         if ($this->relatedParts) {
             $parts = array_merge(array(new RelatedString($this->originalBody, $contentType)), $this->relatedParts);
             foreach (new MultipartRelatedIterator($parts, '--' . $this->boundary) as $part) {
                 $body .= $part;
             }
             $contentType = sprintf('%s;boundary=%s', self::MULTIPART_RELATED, $this->boundary);
         } else {
             $body = $this->originalBody;
         }
         parent::setBody($body, $contentType);
     }
     return parent::getBody();
 }
 /**
  * This function is used to send any kind of request to Nuxeo EM
  * @return NuxeoDocuments|string
  */
 public function sendRequest()
 {
     if (!$this->blobList) {
         $content = str_replace('\\/', '/', json_encode($this->finalRequest, JSON_FORCE_OBJECT));
         $this->request->setBody($content);
         $answer = '';
         try {
             $response = $this->request->send();
             $answer = $response->getBody(true);
         } catch (RequestException $ex) {
             throw new NuxeoClientException("error", NuxeoClientException::INTERNAL_ERROR_STATUS, $ex);
         }
         if (null == json_decode($answer, true)) {
             $documents = $answer;
             file_put_contents("tempstream", $answer);
         } else {
             $answer = json_decode($answer, true);
             $documents = new NuxeoDocuments($answer);
         }
         return $documents;
     } else {
         return $this->multiPart();
     }
 }
 /**
  * This function is used to send any kind of request to Nuxeo EM
  * @return NuxeoDocuments|string
  */
 public function sendRequest()
 {
     if (!$this->blobList) {
         $content = str_replace('\\/', '/', json_encode($this->finalRequest));
         $this->request->setBody($content);
         $answer = '';
         try {
             $response = $this->request->send();
             $answer = $response->getBody(true);
         } catch (RequestException $ex) {
             echo 'Error Server';
         }
         if (null == json_decode($answer, true)) {
             $documents = $answer;
             file_put_contents("tempstream", $answer);
         } else {
             $answer = json_decode($answer, true);
             $documents = new NuxeoDocuments($answer);
         }
         return $documents;
     } else {
         return $this->multiPart();
     }
 }
 public function testDoesNotCloneBody()
 {
     $request = new EntityEnclosingRequest('PUT', 'http://test.com/foo');
     $request->setBody('test');
     $newRequest = clone $request;
     $newRequest->setBody('foo');
     $this->assertInternalType('string', (string) $request->getBody());
 }
Ejemplo n.º 14
0
 /**
  * Constructor
  *
  * @param string $method
  * @param \Guzzle\Http\Url|string $url
  * @param array $headers
  */
 public function __construct($method, $url, $headers = array())
 {
     parent::__construct($method, $url, $headers);
     $this->xmlBody = array();
 }
Ejemplo n.º 15
0
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::addPostFields
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::getPostFiles
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::getPostFields
  */
 public function testHandlesEmptyStrings()
 {
     $request = new EntityEnclosingRequest('POST', 'http://test.com/');
     $request->addPostFields(array('a' => '', 'b' => null, 'c' => 'Foo', 'd' => '@' . __FILE__));
     $this->assertEquals(array('a' => '', 'b' => null, 'c' => 'Foo', 'd' => '@' . __FILE__), $request->getPostFields()->getAll());
     $this->assertEquals(array('d' => __FILE__), $request->getPostFiles());
 }
Ejemplo n.º 16
0
 public function testConvertsPostToGet()
 {
     $request = new EntityEnclosingRequest('POST', 'http://foo.com');
     $request->setPostField('foo', 'bar');
     $request->setPostField('baz', 'bam');
     $request = SignatureV4::convertPostToGet($request);
     $this->assertEquals('GET', $request->getMethod());
     $this->assertEquals('bar', $request->getQuery()->get('foo'));
     $this->assertEquals('bam', $request->getQuery()->get('baz'));
 }
Ejemplo n.º 17
0
 /**
  * @param string $repo
  * @param string $branch
  * @return Response
  */
 protected function getQueueLocation($repo, $branch)
 {
     $header = $this->getCrumbHeader();
     $post = new EntityEnclosingRequest('POST', $this->buildUrl, [$header]);
     $post->setAuth($this->username, $this->passkey)->setPath('/job/' . $repo . '/buildWithParameters/api/xml')->setPostField('BUILD_TYPE', $branch);
     try {
         return $this->httpClient->send($post);
     } catch (ClientErrorResponseException $e) {
         $response = $e->getResponse();
         switch ($response->getStatusCode()) {
             case 404:
                 throw new \InvalidArgumentException("Repository '{$repo}' not found");
             default:
                 throw new $e();
         }
     }
 }
Ejemplo n.º 18
0
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::configureRedirects
  */
 public function testCanDisableRedirects()
 {
     $request = new EntityEnclosingRequest('PUT', 'http://test.com/');
     $request->configureRedirects(false, false);
     $this->assertTrue($request->getParams()->get(RedirectPlugin::DISABLE));
 }
Ejemplo n.º 19
0
 public function testDoesNotSeekOnRequestsWithNoBodyWhenRetrying()
 {
     // Create a request with a body
     $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
     $request->getParams()->set(BackoffPlugin::DELAY_PARAM, 2);
     $plugin = new BackoffPlugin(new ConstantBackoffStrategy(0));
     $plugin->onRequestPoll($this->getMockEvent($request));
 }
Ejemplo n.º 20
0
 /**
  * Returns a list of headers as key/value pairs.
  *
  * @param  boolean $asObjects (Optional) returns the headers as object.
  * @return array List of headers as key/value pairs.
  */
 public function getHeaders($asObjects = false)
 {
     if ($asObjects === true) {
         return parent::getHeaders();
     }
     $headers = array();
     /* @var \Guzzle\Http\Message\Header $header */
     foreach (parent::getHeaders()->getAll() as $header) {
         $headers[$header->getName()] = (string) $header;
     }
     return $headers;
 }
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::setBody
  */
 public function testSetsContentTypeWhenSettingBodyByGuessingFromEntityBody()
 {
     $request = new EntityEnclosingRequest('PUT', 'http://test.com/foo');
     $request->setBody(EntityBody::factory(fopen(__FILE__, 'r')));
     $this->assertEquals('text/x-php', (string) $request->getHeader('Content-Type'));
 }
    /**
     * Overrides default Guzzle usage of curl_multi_exec by a simple curl call
     * and adds some metrics in Newrelic
     *
     * @param EntityEnclosingRequest $request
     * @return Response
     */
    public static function sendRequest( EntityEnclosingRequest $request )
    {
        $ch = curl_init($request->getUrl());
        $curlOptions = array(
            CURLOPT_URL            => $request->getUrl(),
            CURLOPT_TIMEOUT        => \eZINI::instance('merck.ini')->variable('WebService', 'ESBTimeout'),
            CURLOPT_CONNECTTIMEOUT => \eZINI::instance('merck.ini')->variable('WebService', 'ESBConnectTimeout'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => true,
            CURLOPT_USERAGENT      => (string) $request->getHeader('User-Agent'),
            CURLOPT_PORT           => $request->getPort(),
            CURLOPT_HTTPHEADER     => $request->getHeaderLines(),
            CURLOPT_HTTP_VERSION   => $request->getProtocolVersion() === '1.0'
                    ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1,
            // Verifies the authenticity of the peer's certificate
            CURLOPT_SSL_VERIFYPEER => 1,
            // Certificate must indicate that the server is the server to which you meant to connect
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => (string) $request->getBody(),
            CURLOPT_VERBOSE        => false,
        );
        curl_setopt_array($ch, $curlOptions);

        $start = microtime(true);
        $curlResult = curl_exec( $ch );
        $curlCallTime = ( microtime(true) - $start ) * 1000;

        $newRelicApi = new \klpNrApi();
        $methodLabel =   preg_match('#/(?P<method>[^/?]+)(?:\?.*)?$#', $request->getUrl(), $m)
            ? ucfirst( $m['method'] )
            : 'Unknown';
        $newRelicApi->addParameter( 'ESB/'.$methodLabel.':'.$request->getPort(), $curlCallTime );
        $newRelicApi->setCustomMetric( 'Custom/ESB/'.$methodLabel, $curlCallTime );

        $body               = $curlResult;
        $maxHeaderBlocks    = 5;
        $index              = 0;

        // We have to deal with HTTP/1.1 100 continue headers
        do
        {
            list( $header, $body ) = explode("\r\n\r\n", $body, 2);
            $index++;
        }
        while( $index < $maxHeaderBlocks && strpos($body, 'HTTP/1') === 0 );

        $parsedHeaders = array();
        foreach( explode("\n", $header) as $h )
        {
            list( $key, $val ) = explode(':', $h);
            $parsedHeaders[trim($key)] = trim($val);
        }
        $http_status = curl_getinfo( $ch, CURLINFO_HTTP_CODE );

        if ( \eZINI::instance('merck.ini')->variable( 'WebService', 'CurlGetInfo' ) == 'enabled' )
        {
            $curlInfo = curl_getinfo($ch);
            $logMessage  = \ClusterTool::clusterIdentifier().'::'.$methodLabel."\n";
            $logMessage .= var_export( $curlInfo, true );

            \eZLog::write($logMessage, 'esbcurldetails.log');
        }

        curl_close($ch);

        $response = new Response( $http_status, $parsedHeaders, $body );
        $response->setRequest($request);
        $request->setResponse($response);

        return $response;
    }
Ejemplo n.º 23
0
 /**
  * @covers Guzzle\Http\Plugin\ExponentialBackoffPlugin::onRequestPoll
  */
 public function testDoesNotSeekOnRequestsWithNoBodyWhenRetrying()
 {
     // Create a request with a body
     $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
     $request->getParams()->set('plugins.exponential_backoff.retry_time', 2);
     $plugin = new ExponentialBackoffPlugin(2, null, array($this, 'delayClosure'));
     $plugin->onRequestPoll($this->getMockEvent($request));
 }
 /**
  * @covers Guzzle\Http\Plugin\ExponentialBackoffPlugin::onRequestPoll
  */
 public function testSeeksToBeginningOfRequestBodyWhenRetrying()
 {
     // Create a mock curl multi object
     $multi = $this->getMockBuilder('Guzzle\\Http\\Curl\\CurlMulti')->setMethods(array('remove', 'add'))->getMock();
     // Create a request with a body
     $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
     $request->setBody('abc');
     // Set the retry time to be something that will be retried always
     $request->getParams()->set('plugins.exponential_backoff.retry_time', 2);
     // Seek to the end of the stream
     $request->getBody()->seek(3);
     $this->assertEquals('', $request->getBody()->read(1));
     // Create a plugin that does not delay when retrying
     $plugin = new ExponentialBackoffPlugin(2, null, array($this, 'delayClosure'));
     // Create an event that is expected for the Poll event
     $event = new Event(array('request' => $request, 'curl_multi' => $multi));
     $event->setName(CurlMultiInterface::POLLING_REQUEST);
     $plugin->onRequestPoll($event);
     // Ensure that the stream was seeked to 0
     $this->assertEquals('a', $request->getBody()->read(1));
 }
Ejemplo n.º 25
0
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::setState
  */
 public function testSetStateToTransferWithEmptyBodySetsContentLengthToZero()
 {
     $request = new EntityEnclosingRequest('POST', 'http://test.com/');
     $request->setState($request::STATE_TRANSFER);
     $this->assertEquals('0', (string) $request->getHeader('Content-Length'));
 }
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::getPostFiles
  */
 public function testAllowsNestedPostData()
 {
     $request = new EntityEnclosingRequest('POST', 'http://test.com/');
     $request->addPostFields(array('a' => array('b', 'c')));
     $this->assertEquals(array('a' => array('b', 'c')), $request->getPostFields());
 }