public function indexAction()
 {
     $this->_helper->viewRenderer->setNoRender(false);
     $this->_helper->layout()->enableLayout();
     if ($this->getRequest()->isPost()) {
         if ($this->_getParam('num_cnpj') == '') {
             Zend_Layout::getMvcInstance()->assign('msg_error', 'Campo CNPJ é obrigatório !');
         } else {
             if (strlen($this->_getParam('num_cnpj')) < 18) {
                 Zend_Layout::getMvcInstance()->assign('msg_error', 'CNPJ está incorreto !');
             } else {
                 $num_cnpj = $this->_getParam('num_cnpj', '');
                 $this->view->assign('num_cnpj', $num_cnpj);
                 // Incluir arquivo de cliente web service
                 require_once 'Zend/Rest/Client.php';
                 // Criar classe da conexão com o web-service
                 $clientRest = new Zend_Rest_Client('http://' . $_SERVER['HTTP_HOST'] . '/Consulta/sintegra');
                 // Fazer requisição do registro
                 $result = $clientRest->ConsultarRegistro($num_cnpj, $this->generateAuthKey())->get();
                 $result = json_decode($result);
                 if (count($result) <= 0) {
                     Zend_Layout::getMvcInstance()->assign('msg_error', 'Não foi encontrado nenhum registro para o CNPJ ' . $num_cnpj);
                 } else {
                     $result = get_object_vars($result[0]);
                     Zend_Layout::getMvcInstance()->assign('msg_success', 'Exibindo dados do CNPJ ' . $num_cnpj);
                     $this->view->assign('result', $result);
                 }
             }
         }
     }
 }
Example #2
0
 public function execute()
 {
     $action = SJB_Request::getVar('action');
     $sessionUpdateData = SJB_Session::getValue(self::SESSION_UPDATE_TAG);
     if ($action == 'mark_as_closed') {
         if (is_array($sessionUpdateData)) {
             $sessionUpdateData['closed_by_user'] = true;
             SJB_Session::setValue(self::SESSION_UPDATE_TAG, $sessionUpdateData);
         }
         exit;
     }
     // check updates
     $serverUrl = SJB_System::getSystemSettings('SJB_UPDATE_SERVER_URL');
     $version = SJB_System::getSystemSettings('version');
     // CHECK FOR UPDATES
     $updateInfo = SJB_Session::getValue(self::SESSION_UPDATE_TAG);
     if (empty($updateInfo)) {
         // check URL for accessibility
         $ch = curl_init($serverUrl);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_exec($ch);
         $urlInfo = curl_getinfo($ch);
         $availableVersion = array();
         $updateStatus = '';
         if ($urlInfo['http_code'] > 0) {
             // OK. Url is accessible - lets get update info
             try {
                 $client = new Zend_Rest_Client($serverUrl);
                 $result = $client->isUpdateAvailable($version['major'], $version['minor'], $version['build'], SJB_System::getSystemSettings('USER_SITE_URL'))->get();
                 if ($result->isSuccess()) {
                     $updateStatus = (string) $result->updateStatus;
                     switch ($updateStatus) {
                         case 'available':
                             $availableVersion = array('major' => (string) $result->version->major, 'minor' => (string) $result->version->minor, 'build' => (string) $result->version->build);
                             break;
                     }
                 }
             } catch (Exception $e) {
                 SJB_Error::writeToLog('Update Check: ' . $e->getMessage());
             }
         }
         $updateInfo = array('availableVersion' => $availableVersion, 'updateStatus' => $updateStatus);
         SJB_Session::setValue(self::SESSION_UPDATE_TAG, $updateInfo);
     } else {
         if (isset($updateInfo['availableVersion']) && !empty($updateInfo['availableVersion'])) {
             if ($updateInfo['availableVersion']['build'] <= $version['build']) {
                 $updateInfo = array('availableVersion' => $updateInfo['availableVersion'], 'updateStatus' => 'none');
             }
         }
     }
     echo json_encode($updateInfo);
     exit;
 }
Example #3
0
 /**
  * @return void
  */
 public function setUp()
 {
     $httpClient = new Zend_Http_Client();
     $httpClient->setConfig(array('useragent' => 'Zend_Service_Delicious - Unit tests/0.1', 'keepalive' => true));
     Zend_Rest_Client::setHttpClient($httpClient);
     $this->_delicious = new Zend_Service_Delicious();
 }
 public function setUp()
 {
     $this->adapter = new Zend_Http_Client_Adapter_Test();
     $client = new Zend_Http_Client(null, array('adapter' => $this->adapter));
     Zend_Rest_Client::setHttpClient($client);
     $this->shipapi = new ShipApi('user', 'pass', 'http://www.test.com');
 }
Example #5
0
 /**
  * Look up item(s) by ASIN
  *
  * @param  string $asin    Amazon ASIN ID
  * @param  array  $options Query Options
  * @see http://www.amazon.com/gp/aws/sdk/main.html/102-9041115-9057709?s=AWSEcommerceService&v=2005-10-05&p=ApiReference/ItemLookupOperation
  * @throws Zend_Service_Exception
  * @return Zend_Service_Amazon_Item|Zend_Service_Amazon_ResultSet
  */
 public function itemLookup($asin, array $options = array())
 {
     $defaultOptions = array('IdType' => 'ASIN', 'ResponseGroup' => 'Small');
     $options['ItemId'] = (string) $asin;
     $options = $this->_prepareOptions('ItemLookup', $options, $defaultOptions);
     $this->_rest->getHttpClient()->resetParameters();
     $response = $this->_rest->restGet('/onca/xml', $options);
     if ($response->isError()) {
         /**
          * @see Zend_Service_Exception
          */
         require_once 'Zend/Service/Exception.php';
         throw new Zend_Service_Exception('An error occurred sending request. Status code: ' . $response->getStatus());
     }
     $dom = new DOMDocument();
     $dom->loadXML($response->getBody());
     self::_checkErrors($dom);
     $xpath = new DOMXPath($dom);
     $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
     $items = $xpath->query('//az:Items/az:Item');
     if ($items->length == 1) {
         /**
          * @see Zend_Service_Amazon_Item
          */
         require_once 'Zend/Service/Amazon/Item.php';
         return new Zend_Service_Amazon_Item($items->item(0));
     }
     /**
      * @see Zend_Service_Amazon_ResultSet
      */
     require_once 'Zend/Service/Amazon/ResultSet.php';
     return new Zend_Service_Amazon_ResultSet($dom);
 }
Example #6
0
    /**
     * Perform a web content search on search.yahoo.com.  A basic query
     * consists simply of a text query.  Additional options that can be
     * specified consist of:
     * 'results'    => int  How many results to return, max is 50
     * 'start'      => int  The start offset for search results
     * 'language'   => lang  The target document language to match
     * 'type'       => (all|any|phrase)  How the query should be parsed
     * 'site'       => string  A site to which your search should be restricted
     * 'format'     => (any|html|msword|pdf|ppt|rss|txt|xls)
     * 'adult_ok'   => bool  permit 'adult' content in the search results
     * 'similar_ok' => bool  permit similar results in the result set
     * 'country'    => string  The country code for the content searched
     * 'license'    => (any|cc_any|cc_commercial|cc_modifiable)  The license of content being searched
     * 'region'     => The regional search engine on which the service performs the search. default us.
     *
     * @param  string $query    the query being run
     * @param  array  $options  any optional parameters
     * @return Zend_Service_Yahoo_WebResultSet  The return set
     * @throws Zend\Service\Exception
     */
    public function webSearch($query, array $options = array())
    {
        static $defaultOptions = array('type'     => 'all',
                                       'start'    => 1,
                                       'results'  => 10,
                                       'format'   => 'any');

        $options = $this->_prepareOptions($query, $options, $defaultOptions);
        $this->_validateWebSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/WebSearchService/V1/webSearch', $options);

        if ($response->isError()) {
            throw new Zend\Service\Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        return new Zend_Service_Yahoo_WebResultSet($dom);
    }
Example #7
0
 /**
  * Get recommendations from recommender API
  * @param string $type
  * @param array  $parameters
  * @return array
  */
 public function getRecommendations($type, $parameters)
 {
     try {
         $response = $this->_client->restGet(sprintf('/recommend/%s', $type), $parameters);
         $this->_recommendLogger->logApiCall($this->_client, $response);
         if ($response->getStatus() !== 200) {
             throw new \Zend_Http_Client_Exception('Recommender failed to respond');
         }
         $recommendations = json_decode($response->getRawBody(), true);
         if (is_array($recommendations)) {
             return $recommendations;
         }
     } catch (\Zend_Http_Client_Exception $e) {
         $this->_recommendLogger->logApiCallException($this->_client, $e);
     }
     return [];
 }
 /**
  * Set special headers for request
  *
  * @param  string  $apiToken
  * @param  string  $apiVersion
  * @param  string  $requestSignature
  * @return void
  */
 protected function _setHeaders($apiToken, $apiVersion, $requestSignature = null)
 {
     $headers = array('User-Agent' => 'TicketEvolution_Webservice', 'X-Token' => (string) $apiToken, 'Accept' => (string) 'application/json');
     if (!empty($requestSignature)) {
         $headers['X-Signature'] = (string) $requestSignature;
     }
     $this->_rest->getHttpClient()->setHeaders($headers);
 }
Example #9
0
 /**
  * Connects to the AUTH API in Teleserv to authenticate an agent against his HOME credentials.
  *
  * @return Zend_Auth_Result
  * @author Bryan Zarzuela
  * @throws Zend_Auth_Adapter_Exception
  */
 public function authenticate()
 {
     // This is not a real salt. I have to fix this one of these days.
     // Encrypt the password before sending over the wire.
     $password = sha1($this->_password . 'andpepper');
     $client = new Zend_Rest_Client($this->_url);
     $response = $client->authenticate($this->_username, $password)->post();
     if (!$response->isSuccess()) {
         throw new Zend_Auth_Adapter_Exception("Cannot authenticate");
     }
     if (!$response->success()) {
         return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null);
     }
     $data = unserialize($response->data());
     // var_dump($data);
     $identity = new Teleserv_Auth_Identity($data);
     return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
 }
 public function __construct($uri, $email, $password, $consumer_key, $consumer_secret, $oauth_realm, $cookieJarFile = './OX3_Api_CookieJar.txt', $sso = array(), $proxy = array())
 {
     parent::__construct($uri);
     $aUrl = parse_url($uri);
     if (empty($sso)) {
         $sso = array('siteUrl' => 'https://sso.openx.com/api/index/initiate', 'requestTokenUrl' => 'https://sso.openx.com/api/index/initiate', 'accessTokenUrl' => 'https://sso.openx.com/api/index/token', 'authorizeUrl' => 'https://sso.openx.com/login/login', 'loginUrl' => 'https://sso.openx.com/login/process');
     }
     // Set the proxy['adapter'] if $proxy config was passed in
     if (!empty($proxy)) {
         $proxy['adapter'] = 'Zend_Http_Client_Adapter_Proxy';
     }
     // Initilize the cookie jar, from the $cookieJarFile if present
     $client = self::getHttpClient();
     $cookieJar = false;
     if (is_readable($cookieJarFile)) {
         $cookieJar = @unserialize(file_get_contents($cookieJarFile));
     }
     if (!$cookieJar instanceof Zend_Http_CookieJar) {
         $cookieJar = new Zend_Http_CookieJar();
     }
     $client->setCookieJar($cookieJar);
     $client->setConfig($proxy);
     $result = $this->put('/a/session/validate');
     // See if the openx3_access_token is still valid...
     if ($result->isError()) {
         // Get Request Token
         $config = array('siteUrl' => $sso['siteUrl'], 'requestTokenUrl' => $sso['requestTokenUrl'], 'accessTokenUrl' => $sso['accessTokenUrl'], 'authorizeUrl' => $sso['authorizeUrl'], 'consumerKey' => $consumer_key, 'consumerSecret' => $consumer_secret, 'realm' => $oauth_realm);
         $oAuth = new OX3_Oauth_Consumer($config);
         $requestToken = $oAuth->getRequestToken();
         // Authenticate to SSO
         $loginClient = new Zend_Http_Client($sso['loginUrl']);
         $loginClient->setCookieJar();
         $loginClient->setConfig($proxy);
         $loginClient->setParameterPost(array('email' => $email, 'password' => $password, 'oauth_token' => $requestToken->getToken()));
         $loginClient->request(Zend_Http_Client::POST);
         $loginBody = $loginClient->getLastResponse()->getBody();
         // Parse response, sucessful headless logins will return oob?oauth_token=<token>&oauth_verifier=<verifier> as the body
         if (substr($loginBody, 0, 4) == 'oob?') {
             $vars = array();
             @parse_str(substr($loginBody, 4), $vars);
             if (empty($vars['oauth_token'])) {
                 throw new Exception('Error parsing SSO login response');
             }
             // Swap the (authorized) request token for an access token:
             $accessToken = $oAuth->getAccessToken($vars, $requestToken)->getToken();
             $client->setCookie(new Zend_Http_Cookie('openx3_access_token', $accessToken, $aUrl['host']));
             $result = $this->put('/a/session/validate');
             if ($result->isSuccessful()) {
                 file_put_contents($cookieJarFile, serialize($client->getCookieJar()), LOCK_EX);
                 chmod($cookieJarFile, 0666);
             }
         } else {
             throw new Exception('SSO Authentication error');
         }
     }
 }
Example #11
0
 /**
  *
  * @return void
  */
 public function setUp()
 {
     if (!constant('TESTS_ZEND_SERVICE_DELICIOUS_ENABLED')) {
         $this->markTestSkipped('Zend_Service_Delicious online tests are not enabled');
     }
     $httpClient = new Zend_Http_Client();
     $httpClient->setConfig(array('useragent' => 'Zend_Service_Delicious - Unit tests/0.1', 'keepalive' => true));
     Zend_Rest_Client::setDefaultHTTPClient($httpClient);
     $this->_delicious = new Zend_Service_Delicious(self::TEST_UNAME, self::TEST_PASS);
 }
Example #12
0
 public function __construct($serviceUrl = null)
 {
     if (is_null($serviceUrl)) {
         $serviceUrl = Zend_Registry::get('config')->service->users->url;
         if (!$serviceUrl) {
             throw new Kwf_Exception("'service.users.url' not defined in config (usually defined in KWF config)");
         }
     }
     parent::__construct($serviceUrl);
 }
Example #13
0
    public function call($type, $url, $json)
    {
        $version = Shopware()->BackendSession()->storeApiConfigVersion;
        $language = Shopware()->BackendSession()->storeApiConfigLanguage;
        $json['config'] = array(
            'version' => $version,
            'language' => $language
        );

        $json = Zend_Json::encode($json);
        $response = $this->client->call($type, $url, $json)->post();

        if($response->status == self::RESPONSE_FAILED) {
            preg_match('#(.*):(\d*)#', $response->response->message, $error_match);
            return new Shopware_StoreApi_Exception_Response($error_match[1], $error_match[2]);
        } else {
            $preparedResponse = new Shopware_StoreApi_Core_Response_Response($response->response);
            return current($preparedResponse->getCollection());
        }
    }
Example #14
0
 /**
  * Call corresponding web service method and return the results.
  *
  * @deprecated Zend_Rest_Client does not format URI accordingly
  * @param array $params
  * @return array The parsed packstation data
  * @throws Dhl_Account_Exception
  */
 public function findPackstations(array $params)
 {
     /* @var $helper Dhl_Account_Helper_Data */
     $helper = Mage::helper('dhlaccount/data');
     $params = $this->getDefaultParams() + $params;
     try {
         $result = $this->getClient()->postfinder($params)->get();
     } catch (Zend_Rest_Client_Result_Exception $e) {
         $response = $this->client->getHttpClient()->getLastResponse();
         $helper->log($this->client->getHttpClient()->getLastRequest());
         $helper->log(sprintf("%s\nHTTP/%s %s %s", $e->getMessage(), $response->getVersion(), $response->getStatus(), $response->getMessage()));
         throw new Dhl_Account_Exception($helper->__('An error occured while retrieving the packstation data.'));
     }
     // TODO(nr): transform web service response to usable output.
     return $result;
 }
Example #15
0
 public function __construct($type)
 {
     $this->_type = $type;
     $app = $GLOBALS['application']->getOption('app');
     $message_config = $app['messages'][$type];
     $server = $message_config['server'];
     $context = $message_config['context'];
     unset($message_config['server']);
     unset($message_config['context']);
     $this->_messages = new StdClass();
     foreach ($message_config as $key => $method) {
         $key = str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
         $this->_messages->{$key} = $context . $method;
     }
     Zend_Rest_Client::__construct($server);
     $this->getHttpClient()->setHeaders('Accept-Encoding', 'plain');
 }
Example #16
0
 /**
  * Utility function to find Flickr photo details by ID.
  * @param string $id the NSID
  * @return Zend_Service_Flickr_Image the details for the specified image
  */
 public function getImageDetails($id)
 {
     static $method = 'flickr.photos.getSizes';
     $options = array('api_key' => $this->apiKey, 'method' => $method, 'photo_id' => $id);
     if (!empty($id)) {
         $response = $this->_rest->restGet('/services/rest/', $options);
         $dom = new DOMDocument();
         $dom->loadXML($response->getBody());
         $xpath = new DOMXPath($dom);
         self::_checkErrors($dom);
         $return = array();
         foreach ($xpath->query('//size') as $size) {
             $label = (string) $size->getAttribute('label');
             $retval[$label] = new Zend_Service_Flickr_Image($size);
         }
     } else {
         throw new Zend_Service_Exception('You must supply a photo ID');
     }
     return $retval;
 }
Example #17
0
 /**
  * Perform a web content search on search.yahoo.com.  A basic query
  * consists simply of a text query.  Additional options that can be
  * specified consist of:
  * 'results'    => int  How many results to return, max is 50
  * 'start'      => int  The start offset for search results
  * 'language'   => lang  The target document language to match
  * 'type'       => (all|any|phrase)  How the query should be parsed
  * 'site'       => string  A site to which your search should be restricted
  * 'format'     => (any|html|msword|pdf|ppt|rss|txt|xls)
  * 'adult_ok'   => bool  permit 'adult' content in the search results
  * 'similar_ok' => bool  permit similar results in the result set
  * 'country'    => string  The country code for the content searched
  * 'license'    => (any|cc_any|cc_commercial|cc_modifiable)  The license of content being searched
  * 'region'     => The regional search engine on which the service performs the search. default us.
  *
  * @param  string $query    the query being run
  * @param  array  $options  any optional parameters
  * @return Zend_Service_Yahoo_WebResultSet  The return set
  * @throws Zend_Service_Exception
  */
 public function webSearch($query, array $options = array())
 {
     static $defaultOptions = array('type' => 'all', 'start' => 1, 'results' => 10, 'format' => 'any');
     $options = $this->_prepareOptions($query, $options, $defaultOptions);
     $this->_validateWebSearch($options);
     $this->_rest->getHttpClient()->resetParameters();
     $this->_rest->setUri('http://search.yahooapis.com');
     $response = $this->_rest->restGet('/WebSearchService/V1/webSearch', $options);
     if ($response->isError()) {
         /**
          * @see Zend_Service_Exception
          */
         require_once LIB_DIR . '/Zend/Service/Exception.php';
         throw new Zend_Service_Exception('An error occurred sending request. Status code: ' . $response->getStatus());
     }
     $dom = new DOMDocument();
     $dom = Zend_Xml_Security::scan($response->getBody(), $dom);
     self::_checkErrors($dom);
     /**
      * @see Zend_Service_Yahoo_WebResultSet
      */
     require_once LIB_DIR . '/Zend/Service/Yahoo/WebResultSet.php';
     return new Zend_Service_Yahoo_WebResultSet($dom);
 }
function search()
{
    // load Zend classes
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Rest_Client');
    // define category prefix
    $prefix = 'hollywood';
    // initialize REST client
    $wikipedia = new Zend_Rest_Client('http://en.wikipedia.org/w/api.php');
    // set query parameters
    $wikipedia->action('query');
    $wikipedia->list('allcategories');
    //All list queries return a limited number of results.
    $wikipedia->acprefix($prefix);
    $wikipedia->format('xml');
    // perform request and iterate over XML result set
    $result = $wikipedia->get();
    //echo "<ol>";
    foreach ($result->query->allcategories->c as $c) {
        //<a href="http://www.wikipedia.org/wiki/Category:
        echo $c . "<br>";
    }
}
Example #19
0
      - http://framework.zend.com/manual/en/zend.rest.client.html
      - http://www.pixelated-dreams.com/archives/243-Next-Generation-REST-Web-Services-Client.html
**/
require 'Zend/Rest/Client.php';
$taskr_site_url = "http://localhost:7007";
/**
  If your Taskr server is configured to require authentication, uncomment the next block
  and change the username and password to whatever you have in your server's config.yml.
 **/
//$username = '******';
//$password = '******';
//Zend_Rest_Client::getHttpClient()->setAuth($username, $password);
/**
  Initialize the REST client.
 **/
$rest = new Zend_Rest_Client($taskr_site_url);
/**
  Retreiving the list of all scheduled Tasks
 **/
$tasks = $rest->get("/tasks.xml");
// $tasks is a SimpleXml object, so calling print_r($result) will let
// you see all of its data.
//
// Here's an example of how to print out all of the tasks as an HTML list:
if ($tasks->task) {
    echo "<ul>\n";
    foreach ($tasks->task as $task) {
        echo "\t<li>" . $task->name . "</li>\n";
        echo "\t<ul>\n";
        echo "\t\t<li>execute " . $task->{'schedule-method'} . " " . $task->{'schedule-when'} . "</li>\n";
        echo "\t\t<li>created by " . $task->{'created-by'} . " on " . $task->{'created-on'} . "</li>\n";
Example #20
0
 /**
  * @param string $ps_url The url to connect to
  * @param array $ps_options An array of options:
  *		timeout = the number of seconds to wait for a response before throwing an exception. Default is 30 seconds.
  */
 public function __construct($ps_uri = null, $pa_options = null)
 {
     self::getHttpClient()->setCookieJar(true);
     self::getHttpClient()->setConfig(array("timeout" => isset($pa_options['timeout']) && (int) $pa_options['timeout'] > 0 ? (int) $pa_options['timeout'] : 30));
     parent::__construct($ps_uri);
 }
Example #21
0
<?php

/**
 * @file
 * @ingroup DAPCPTest
 * 
 * @author Dian
 */
require_once 'Zend/Rest/Client.php';
$client = new Zend_Rest_Client('http://localhost/mw/api.php?action=wspcp&format=xml');
#$client->readPage("WikiSysop", NULL, NULL, NULL, NULL, "Main Page")->get();
$client->method("readPage");
$client->title("Main Page");
$result = $client->get();
var_dump($result->wspcp()->text);
//echo $client->createPage("WikiSysop", NULL, NULL, NULL, NULL, "REST Test", "Adding some content")->get()->getIterator()->asXML();
//$__obj = $client->readPage("WikiSysop", NULL, NULL, NULL, NULL, "Main Page")->get();
//$__res = $__obj->__toString();
//var_dump($client->readPage("WikiSysop", NULL, NULL, NULL, NULL, "Main Page")->get());
//echo $client->login("WikiSysop", "!>ontoprise?")->get();
//var_dump($client->sayHello("Tester", "now")->get());
Example #22
0
    public function testRestPut()
    {
        $expXml   = file_get_contents($this->path . 'returnString.xml');
        $response = "HTTP/1.0 200 OK\r\n"
                  . "X-powered-by: PHP/5.2.0\r\n"
                  . "Content-type: text/xml\r\n"
                  . "Content-length: " . strlen($expXml) . "\r\n"
                  . "Server: Apache/1.3.34 (Unix) PHP/5.2.0)\r\n"
                  . "Date: Tue, 06 Feb 2007 15:01:47 GMT\r\n"
                  . "Connection: close\r\n"
                  . "\r\n"
                  . $expXml;
        $this->adapter->setResponse($response);

        $reqXml   = file_get_contents($this->path . 'returnInt.xml');
        $response = $this->rest->restPut('/rest/', $reqXml);
        $this->assertTrue($response instanceof Zend_Http_Response);
        $body = $response->getBody();
        $this->assertContains($expXml, $response->getBody());

        $request = Zend_Rest_Client::getHttpClient()->getLastRequest();
        $this->assertContains($reqXml, $request, $request);
    }
Example #23
0
 /**
  * Look up for a Single Item
  *
  * @param string $asin Amazon ASIN ID
  * @param array $options Query Options
  * @see http://www.amazon.com/gp/aws/sdk/main.html/102-9041115-9057709?s=AWSEcommerceService&v=2005-10-05&p=ApiReference/ItemLookupOperation
  * @throws Zend_Service_Exception
  * @return Zend_Service_Amazon_Item|Zend_Service_Amazon_ResultSet|null
  */
 public function itemLookup($asin, $options = null)
 {
     if (!$options) {
         $options = array();
     }
     $defaultOptions = array('IdType' => 'ASIN', 'ResponseGroup' => 'Small');
     $options['ItemId'] = $asin;
     $options = $this->_prepareOptions('ItemLookup', $options, $defaultOptions);
     $this->_validateItemLookup($options);
     $response = $this->_rest->restGet('/onca/xml', $options);
     if ($response->isError()) {
         throw new Zend_Service_Exception('An error occurred sending request. Status code: ' . $response->getStatus());
     }
     $dom = new DOMDocument();
     $dom->loadXML($response->getBody());
     self::_checkErrors($dom);
     $xpath = new DOMXPath($dom);
     $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
     $items = $xpath->query('//az:Items/az:Item');
     if ($items->length == 1) {
         return new Zend_Service_Amazon_Item($items->item(0));
     } elseif ($items->length > 1) {
         return new Zend_Service_Amazon_ResultSet($items);
     }
     return null;
 }
Example #24
0
    /**
     * Perform a rest post throwing an exception if result failed
     *
     * @param string $method
     * @param array  $options
     * @param array  $defaultOptions
     * @return Zend_Rest_Client_Result
     */
    protected function _restFileUpload($method, $file, $param, array $options, array $defaultOptions = array())
    {
        $options  = $this->_prepareOptions($method, $options, $defaultOptions);

        $client = Zend_Rest_Client::getHttpClient();
        $client->setUri($this->getScribdClient()->getRestClient()->getUri());

        $client->setParameterGet($options);
        $client->setFileUpload($file, $param);
        $response = $client->request('POST');

        if ($response->isError()) {
            $code = $response->extractCode($response->asString());

            /**
             * @see Zym_Service_Scribd_Exception
             */
            require_once 'Zym/Service/Scribd/Exception.php';
            throw new Zym_Service_Scribd_Exception($response->getMessage(), $code);
        }

        return $this->_handleResponse($response);
    }
Example #25
0
	protected function _performPost($method, $data = null)
	{
		if (is_string($data)) {
			self::getHttpClient()->setHeaders('Content-Type', 'application/json');
		}
		return parent::_performPost($method, $data);
    }
 /**
  * @group EricssonListPagingInt
  */
 public function testFindAllByMasterFilterAlias()
 {
     Zend_Rest_Client::getHttpClient()->setConfig(array('timeout' => 60));
     $rawFilters = array('alias' => 'alias');
     $filterList = SimService::getInstance()->buildFilterList($rawFilters);
     $filters = array('organizationId' => Application\Model\Organization\OrgMasterModel::ORG_TYPE . '-' . 'master11111111111111111111111111', 'filterList' => $filterList);
     $sims = $this->simMapper->findAll($filters, array('count' => 100));
     $this->assertNotNull($sims);
     $this->assertGreaterThanOrEqual('1', $sims->getCount());
 }
 public function tearDown()
 {
     Zend_Rest_Client::setHttpClient($this->_httpClientOriginal);
 }
 /**
  *  rest-client.docx
  * Gets the first wiki-text before the Table of Content
  * @author TSCM
  * @since 20150102
  * @param string - a Name or Booktitle , exp: "Lord of the Rings"
  * @return string - html code line
  * Explanation
  * //Base Url:
  * http://en.wikipedia.org/w/api.php?action=query
  *
  * //tell it to get revisions:
  * &prop=revisions
  *
  * //define page titles separated by pipes. In the example i used t-shirt company threadless
  * &titles=whatever|the|title|is
  *
  * //specify that we want the page content
  * &rvprop=content
  *
  * //I want my data in JSON, default is XML
  * &format=json
  *
  * //lets you choose which section you want. 0 is the first one.
  * &rvsection=0
  *
  * //tell wikipedia to parse it into html for you
  * &rvparse=1
  *
  * //only geht the "first"-Description of the wikipage, the one before the Table of Contents
  * &exintro=1
  *
  * //if I want to select something, I use action query, update / delete would be different
  * &action=query
  */
 public static function wiki($query)
 {
     // load Zend classes
     require_once 'Zend/Loader.php';
     Zend_Loader::loadClass('Zend_Rest_Client');
     $decodeUtf8 = 0;
     //is decoding needed? Default not
     // define search query
     $wikiQuery = str_replace(" ", "_", $query);
     try {
         //initialize REST client
         $lang = I18n::lang();
         $wikiLang = strtolower($lang);
         $webPagePrefix = "http://";
         $webPageUrl = ".wikipedia.org/w/api.php";
         //build the wiki api. be sure, that $wikiLang exists, exp: de or en
         $wikipedia = new Zend_Rest_Client($webPagePrefix . $wikiLang . $webPageUrl);
         $wikipedia->action('query');
         //standard action, i want to GET...
         $wikipedia->prop('extracts');
         //what do i want to extract? page info
         $wikipedia->exintro('1');
         // only extract the intro? (pre-Table of content) 1= yes, 0=now
         $wikipedia->titles($wikiQuery);
         //title is the wiki title to be found
         $wikipedia->format('xml');
         //what format should be returned? exp: json, txt, php,
         $wikipedia->continue('');
         //has to be set, otherwise wikimedia sends a warning
         // perform request
         // iterate over XML result set
         $result = $wikipedia->get();
         //print_r($result);
         $rs = $result->query->pages->page->extract;
         if ($decodeUtf8) {
             $rs = utf8_decode($rs);
         }
         //strip html Tags to get a clean string
         $rsFinal = strip_tags($rs);
         return $rsFinal;
     } catch (Exception $e) {
         die('ERROR: ' . $e->getMessage());
     }
 }
Example #29
0
 /**
  *
  * @param <type> $pString
  * @return <type>
  */
 public static function find_artist($pString)
 {
     $client = new Zend_Rest_Client("http://musicbrainz.org/ws/1/artist/");
     $client->type('xml');
     $client->name(str_replace(' ', '+', $pString));
     return $client->get();
 }
 /**
  * @param Zend_Rest_Client $request
  * @param string $path
  * @param array $params
  * @param string $method
  * @return Zend_Http_Response
  */
 protected function _doRequest($request, $path, $params, $method = 'POST')
 {
     if ($this->_isDebugMode()) {
         $message = "{$method} {$request->getUri()}{$path} with params:\n" . print_r($params, true);
         Mage::helper('codekunst_payglobe')->log($message);
     }
     switch ($method) {
         case 'POST':
         default:
             $response = $request->restPost($path, $params);
             break;
     }
     if ($this->_isDebugMode()) {
         $message = "Response: {$response->getStatus()} with body:\n{$response->getBody()}";
         Mage::helper('codekunst_payglobe')->log($message);
     }
     return $response;
 }