Example #1
0
 /**
  * Calls the method contained in the actions of this resource
  *
  * @param string $method
  * @param array $args
  *
  * @return \StdClass The JSON decoded response
  */
 public function __call($method, $args)
 {
     $action = $this->getActions()[$method];
     $uri = $this->getBaseUri() . $this->getPath($action, $args);
     $params = $this->getParams($args);
     $this->last_response = $this->client->request($action['method'], $uri, $params);
     $response = $this->last_response->getBody();
     return $this->parse($response);
 }
Example #2
0
 public function test_json_post()
 {
     global $TEST_SERVER_URL;
     $api = new RestClient();
     $result = $api->post($TEST_SERVER_URL, "{\"foo\":\"bar\"}", array('Content-Type' => 'application/json'));
     $response_json = $result->decode_response();
     $this->assertEquals('application/json', $response_json->headers->{"Content-Type"});
     $this->assertEquals('POST', $response_json->SERVER->REQUEST_METHOD);
     $this->assertEquals("{\"foo\":\"bar\"}", $response_json->body);
 }
Example #3
0
function get_aaa()
{
    $options = ['decoders' => array('json' => 'decode_result_as_json', 'php' => 'unserialize')];
    $api = new RestClient($options);
    $result = $api->post("https://api.naa.gov.au/naa/api/v1/person/search-series-b2455?app_id={appi}&app_key={key}", "{\"page\": 1,\"rows\": 50,\"query_fields\": {\"place_of_birth\": \"wales\"}}", array('Content-Type' => 'application/json'));
    $params = json_encode(['query_fields' => ["place_of_birth" => 'some string']]);
    $code = $result->info->http_code;
    if (!$code == 200) {
        echo "POST failed, error code: " . $code;
    }
    $response_json = $result->decode_response();
    return $response_json;
}
Example #4
0
 function createApp($appName, $orgName)
 {
     Util::throwExceptionIfNullOrBlank($appName, "App Name");
     Util::throwExceptionIfNullOrBlank($orgName, "orgName");
     $objUtil = new Util($this->apiKey, $this->secretKey);
     try {
         $params = array();
         $params['apiKey'] = $this->apiKey;
         $params['version'] = $this->version;
         date_default_timezone_set('UTC');
         $params['timeStamp'] = date("Y-m-d\\TG:i:s") . substr((string) microtime(), 1, 4) . "Z";
         $params['App Name'] = $appName;
         $params['orgName'] = $orgName;
         $signature = urlencode($objUtil->sign($params));
         //die();
         $body = null;
         $body = '{"app42":{"app":}}';
         $params['body'] = $body;
         $params['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $this->url = $this->url;
         $response = RestClient::post($this->url, $params, null, null, $contentType, $accept, $body);
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $response;
 }
 public function callAjaxReadability()
 {
     require 'lib/restclient.php';
     $base_url = 'https://www.readability.com/';
     $url_to_parse = isset($_POST['posturl']) ? urlencode($_POST['posturl']) : '';
     $readability_token = get_option('r2p_setting_token', '');
     $endpoint_url = $base_url . "api/content/v1/parser?url={$url_to_parse}&token={$readability_token}";
     $api = new RestClient(array('base_url' => $base_url));
     $result = $api->get("api/content/v1/parser?url={$url_to_parse}&token={$readability_token}");
     if ($result->response == '') {
         echo '{ "error": "Something went wrong, Please check your \'Readability Parser Token\' settings."}';
     } else {
         echo $result->response;
     }
     die;
 }
Example #6
0
 /**
  * @param $type
  * @param $url
  * @param array $data
  * @param array $headers
  * @return bool|mixed
  */
 public function request($type, $url, array $data = null, array $headers = array(), $content_type = null)
 {
     $url = trim($this->getRequestUrl($url), '/');
     if ($response = parent::request($type, $url, $data, $headers, $content_type)) {
         return $response;
     }
     return false;
 }
Example #7
0
 /**
  * Constructor
  */
 public function __construct($token, $baseUrl)
 {
     parent::__construct($token, $baseUrl);
     // API Endpoints
     $this->projects = new Endpoints\Projects($this);
     $this->users = new Endpoints\Users($this);
     $this->milestones = new Endpoints\Milestones($this);
     $this->tasks = new Endpoints\Tasks($this);
     $this->userStories = new Endpoints\UserStories($this);
 }
Example #8
0
 /**
  * API constructor.
  * @param array $options
  */
 public function __construct($options = array())
 {
     $defaultOptions = array('x' => false, 'vvv' => false);
     $this->cronOptions = array_merge($defaultOptions, $options);
     if ($this->cronOptions['x']) {
         $this->API_URL = 'http://localhost:8080';
     }
     $this->vvv('Cronalytics API constructed', $this->cronOptions);
     $this->vvv('default headers', $this->getDefaultHeaders());
     parent::__construct();
 }
Example #9
0
 public function run()
 {
     if (!parent::getApiKey()) {
         throw new PagarMe_Exception("You need to configure API key before performing requests.");
     }
     $this->parameters = array_merge($this->parameters, array("api_key" => parent::getApiKey()));
     // var_dump($this->parameters);
     // $this->headers = (PagarMe::live) ? array("X-Live" => 1) : array();
     $client = new RestClient(array("method" => $this->method, "url" => $this->full_api_url($this->path), "headers" => $this->headers, "parameters" => $this->parameters));
     $response = $client->run();
     $decode = json_decode($response["body"], true);
     if ($decode === NULL) {
         throw new Exception("Failed to decode json from response.\n\n Response: " . $response);
     } else {
         if ($response["code"] == 200) {
             return $decode;
         } else {
             throw PagarMe_Exception::buildWithFullMessage($decode);
         }
     }
 }
Example #10
0
 public function run()
 {
     if (!parent::getApiKey()) {
         throw new Exception("You need to configure API key before performing requests.");
     }
     $this->parameters = array_merge($this->parameters, array("api_key" => parent::getApiKey()));
     $client = new RestClient(array("method" => $this->method, "url" => $this->fullApiUrl($this->path), "headers" => $this->headers, "parameters" => $this->parameters));
     $response = $client->run();
     if ($response["code"] == 204) {
         return true;
     }
     $decode = json_decode($response["body"], true);
     if ($decode === null) {
         throw new Exception("Failed to decode json from response.\n\n Response: " . $response);
     } else {
         if ($response["code"] == 200 || $response["code"] == 201) {
             return $decode;
         } else {
             throw Exception::buildWithFullMessage($decode);
         }
     }
 }
Example #11
0
 protected function process($request, $operation, $jsonHelper)
 {
     $jsonRequest = $this->buildRequest($request, $operation, $jsonHelper);
     echo '<div class="col-lg-10 col-lg-offset-1"><div class="alert alert-info" role="alert"><strong>Raw Request</strong> ' . $jsonRequest . '</div></div>';
     $headers = $this->buildHeaders($jsonRequest);
     $jsonResponse = RestClient::sendRequest($this->config, $jsonRequest, $headers);
     $isValidResponse = strpos($jsonResponse, 'responseData');
     if ($isValidResponse === FALSE) {
         echo '<div class="col-lg-10 col-lg-offset-1"><div class="alert alert-danger" role="alert"><strong>Oh snap!</strong> Something Wrong The response is ' . $jsonResponse . ' </div></div>';
     } else {
         echo '<div class="col-lg-10 col-lg-offset-1"><div class="alert alert-success" role="alert"><strong>Raw Response</strong> ' . $jsonResponse . '</div></div>';
     }
     return $this->buildResponse($jsonResponse, $jsonHelper);
 }
 /**
  * Add or Update preference list on the cloud.
  *
  * @param preferenceDataList
  *            - List of PreferenceData which contains customerId, itemId,
  *            preference
  *
  * @return App42Response object
  */
 function addOrUpdatePreference($preferenceDataList)
 {
     Util::throwExceptionIfNullOrBlank($preferenceDataList, "Preference Data List");
     $responseObj = new App42Response();
     $objUtil = new Util($this->apiKey, $this->secretKey);
     $dataValue = array();
     $preferenceData = new PreferenceData();
     if (is_array($preferenceDataList)) {
         foreach ($preferenceDataList as $arrayValue) {
             $userId = $arrayValue->getUserId();
             $itemId = $arrayValue->getItemId();
             $preference = $arrayValue->getPreference();
             $array = array("UserId" => $userId, "itemId" => $itemId, "preference" => $preference);
             array_push($dataValue, $array);
         }
     } else {
         $userId = $preferenceDataList->getUserId();
         $itemId = $preferenceDataList->getItemId();
         $preference = $preferenceDataList->getPreference();
         $array = array("UserId" => $userId, "itemId" => $itemId, "preference" => $preference);
         array_push($dataValue, $array);
     }
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $headerParams = array_merge($signParams, $metaHeaders);
         $body = null;
         //$body = '{"app42":{"preferences":{"preference":"' . $preferenceDataList->getUserId() . '","itemId":"' . $preferenceDataList->getItemId() . '","preference":"' . $preferenceDataList->getPreference() . '"}}}}';
         $body = '{"app42":{"preferences":{"preference":' . json_encode($dataValue) . '}}}';
         $signParams['body'] = $body;
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/addOrUpdatePreference";
         $response = RestClient::post($baseURL, $params, null, null, $contentType, $accept, $body, $headerParams);
         $responseObj->setStrResponse($response);
         $responseObj->setResponseSuccess(true);
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $responseObj;
 }
Example #13
0
 function deleteUser($gameName)
 {
     Util::throwExceptionIfNullOrBlank($gameName, "Game Name");
     $encodedUserName = Util::encodeParams($gameName);
     $responseObj = new App42Response();
     $objUtil = new Util($this->apiKey, $this->secretKey);
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $headerParams = array_merge($signParams, $metaHeaders);
         $signParams['gameName'] = $gameName;
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/delete/" . $encodedUserName;
         $response = RestClient::delete($baseURL, $params, null, null, $contentType, $accept, $headerParams);
         $responseObj->setStrResponse($response->getResponse());
         $responseObj->setResponseSuccess(true);
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $responseObj;
 }
 /**
  * Creates the RESTClient
  * @param string $url=null [optional]
  * @return RestClient
  */
 public static function createClient($url=null) {
     $client = new RestClient;
     if($url != null) {
         $client->setUrl($url);
     }
     return $client;
 }
Example #15
0
 /**
  *
  */
 public function sync()
 {
     $this->opa_processed_records = array();
     $this->opa_processed_self_relations = array();
     $o_config = Configuration::load(__CA_CONF_DIR__ . "/synchronization.conf");
     $o_dm = Datamodel::load();
     $va_sources = $o_config->getAssoc('sources');
     foreach ($va_sources as $vs_code => $va_source) {
         $vs_base_url = $va_source['baseUrl'];
         $vs_search_expression = $va_source['searchExpression'];
         $vs_username = $va_source['username'];
         $vs_password = $va_source['password'];
         $vs_table = $va_source['table'];
         if (!$vs_base_url) {
             print "ERROR: You must pass a valid CollectiveAccess url\n";
             exit(-1);
         }
         print "[Notice] Processing {$vs_base_url}/{$vs_code}\n";
         if (!($t_instance = $o_dm->getInstanceByTableName($vs_table, false))) {
             die("Invalid table '{$vs_table}'\n");
         }
         //
         // Set up HTTP client for REST calls
         //
         $o_client = new RestClient($vs_base_url . "/service.php/search/Search/rest");
         //
         // Authenticate
         //
         $o_res = $o_client->auth($vs_username, $vs_password)->get();
         if (!$o_res->isSuccess()) {
             die("Could not authenticate to service for authentication\n");
         }
         //
         // Get userID
         //
         $o_res = $o_client->getUserID()->get();
         if (!$o_res->isSuccess()) {
             die("Could not fetch user_id\n");
         }
         $vn_user_id = (int) $o_res->getUserID->response;
         //
         // Get date/time on server
         //
         $o_res = $o_client->getServerTime()->get();
         if (!$o_res->isSuccess()) {
             die("Could not fetch server time\n");
         }
         $vn_server_timestamp = (int) $o_res->getServerTime->response;
         // Get last event
         $va_last_event = ca_data_import_events::getLastEventForSourceAndType($vs_base_url, 'SYNC');
         $vs_last_event_timestamp = null;
         if (is_array($va_last_event)) {
             if (preg_match('!\\[([^\\]]+)!', $va_last_event['description'], $va_matches)) {
                 $vs_last_event_timestamp = $va_matches[1];
                 $vs_search_expression = "({$vs_search_expression}) AND (modified:\"after {$vs_last_event_timestamp}\")";
             }
         } else {
             $vs_search_expression = "({$vs_search_expression}) AND (modified:\"after June 15 2012\")";
         }
         //$vs_search_expression = "modified:\"after 2/24/2013\"";
         //$vs_search_expression = "ca_objects:idno:10180";
         $vs_search_expression = "ca_objects.type_id:48";
         print "\t[Notice] Search is for [{$vs_search_expression}]\n";
         try {
             $o_res = $o_client->queryRest($vs_table, $vs_search_expression, array("ca_objects.status" => array("convertCodesToDisplayText" => 1)))->get();
         } catch (exception $e) {
             print "\t[Error] Search failed: " . $e->getMessage() . "\n";
             continue;
         }
         // TODO: check for errors here
         //parse results
         $vs_pk = $t_instance->primaryKey();
         $va_items = array();
         $o_xml = $o_res->CaSearchResult;
         foreach ($o_xml->children() as $vn_i => $o_item) {
             $o_attributes = $o_item->attributes();
             $vn_id = (int) $o_attributes->{$vs_pk};
             $vs_idno = (string) $o_item->idno;
             $vs_label = (string) $o_item->ca_labels->ca_label[0];
             $va_items[$vs_table . '/' . $vn_id] = array('table' => $vs_table, 'id' => $vn_id, 'idno' => $vs_idno);
         }
         print "\t\t[Notice] Found " . sizeof($va_items) . " items\n";
         //print_R($va_items);
         // Ok... now fetch and import each
         $o_client->setUri($vs_base_url . "/service.php/iteminfo/ItemInfo/rest");
         $this->fetchAndImport($va_items, $o_client, $va_source, array(), $vs_code);
         // TODO: handle deletes
         // Create new import event
         ca_data_import_events::newEvent($vn_user_id, 'SYNC', $vs_base_url, 'Sync process synchronization at [' . date("c", $vn_server_timestamp) . ']');
     }
 }
Example #16
0
 function getCurrentTime()
 {
     $objUtil = new Util($this->apiKey, $this->secretKey);
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $headerParams = array_merge($signParams, $metaHeaders);
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/currentTime";
         $response = RestClient::get($baseURL, $params, null, null, $contentType, $accept, $headerParams);
         $timerResponseObj = new TimerResponseBuilder();
         $timerObj = $timerResponseObj->buildResponse($response->getResponse());
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $timerObj;
 }
Example #17
0
 /**
  * Perform REST POST request to API
  * @param string $path Absolute resource path
  * @param array $params Post params
  * @return array
  */
 protected function _post($path, $params)
 {
     $uri = self::getBaseUri() . $path;
     $client = RestClient::post($uri, $params, $this->_user, $this->_password, "multipart/form-data", self::$baseHeaders);
     if ($client->getResponseCode() !== 200) {
         throw new Exception(trim($client->getResponseMessage()) . ": " . trim($client->getResponse()));
     }
     if ($client->getResponseContentType() != 'application/json') {
         throw new Exception("Unexpected response type: " . $client->getResponseContentType());
     }
     $result = json_decode($client->getResponse());
     if ($result->success === false) {
         throw new Exception("Nets fees request failed: {$result->message}");
     }
     return $result->data;
 }
Example #18
0
 function isActive($testName)
 {
     Util::throwExceptionIfNullOrBlank($testName, "testName");
     $objUtil = new Util($this->apiKey, $this->secretKey);
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $signParams['testName'] = $testName;
         $headerParams = array_merge($signParams, $metaHeaders);
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/isActive/" . $testName;
         $response = RestClient::get($baseURL, $params, null, null, $contentType, $accept, $headerParams);
         $abTestRespObj = new ABTestResponseBuilder();
         $abTestObj = $abTestRespObj->buildResponse($response->getResponse());
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $abTestObj;
 }
 function getAllDevicesOfUser($userName)
 {
     Util::throwExceptionIfNullOrBlank($userName, "User Name");
     $encodedUserName = Util::encodeParams($userName);
     $objUtil = new Util($this->apiKey, $this->secretKey);
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $headerParams = array_merge($signParams, $metaHeaders);
         $signParams['userName'] = $userName;
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/getAllDevices/" . $encodedUserName;
         $response = RestClient::get($baseURL, $params, null, null, $contentType, $accept, $headerParams);
         $pushResponseObj = new PushNotificationResponseBuilder();
         $pushObj = $pushResponseObj->buildArrayResponse($response->getResponse());
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $pushObj;
 }
Example #20
0
<?php

include_once 'rest/client.php';
$accessToken = 'ACCESS_TOKEN';
// XML
$client = new RestClient($accessToken, RestClient::OUTPUT_FORMAT_XML);
$client->getSystems();
echo "\r\n";
$client->getSystemClassGetPropertiesCommands('NXS3E63FF30', 'sys');
echo "\r\n";
$client->setSystemClassProperty('NXS3E63FF30', 'sys', 'var', 'TestVar,1');
echo "\r\n";
$client->executeRaw('NXS3E63FF30', '{"version":1,"method":"command","class":"sys","command":[{"name":"hello","value":""}]}');
// JSON
$client = new RestClient($accessToken, RestClient::OUTPUT_FORMAT_JSON);
echo "\r\n\r\n";
$client->getUser();
echo "\r\n";
$client->getSystemClassValues('NXS3E63FF30', 'zwave');
echo "\r\n";
$client->executeSystemClassCommand('NXS3E63FF30', 'sys', 'hello');
// JSONP
$client = new RestClient($accessToken, RestClient::OUTPUT_FORMAT_JSONP, 'testFunctionName');
echo "\r\n\r\n";
$client->getSystem('NXS3E63FF30');
echo "\r\n";
$client->getSystemClassProperty('NXS3E63FF30', 'sys', 'date');
require_once 'util/constantes.php';
//Inicialização de variáveis.
$aluno = $_POST['nome_aluno'];
$matricula = $_POST['matricula'];
$nascimento = $_POST['nascimento'];
$sexo = $_POST['sexo'];
$nivel = $_POST['nivel'];
$senha1 = $_POST['senha1'];
$login = $_POST['login'];
//Verificar os campos obrigatórios, os tipos e formatos dos dados avaliados
if (validarCamposNaoVazios()) {
    if (validaFormCadastrarAluno()) {
        $json = array("nome" => $aluno, "login" => $login, "senha" => $senha1, "matricula" => $matricula, "nascimento" => $nascimento, "nivel" => $nivel, "sexo" => $sexo);
        // Instaciação do objeto RestClient. A url base é passada como parâmetro
        // via array.
        $restClient = new RestClient(array('base_url' => "http://localhost/NutrIF_service"));
        /*
         * Informar qual é o serviço ('cadastrarAluno'), os dados do json ($json) e
         * o header do HTTP ($header);
         */
        $header = array('user_agent' => "nutrif-php/1.0", 'content-type' => "application/json");
        // Método POST.
        $result = $restClient->post('cadastrarAluno', $json, $header);
        $code = $result->info->http_code;
        if ($code == 200 || $code == 201) {
            echo '<script language="javascript" type="text/javascript">';
            echo 'window.alert("Cadastro realizado com sucesso!");';
            echo 'window.location.href="index.php";';
            echo '</script>';
        } else {
            header("location: mensagem_erro.php");
 function testUnpreciseBench()
 {
     $c = RestClient::get($this->url . "/Foo/bench");
     echo $c->getResponse();
 }
<?php

include '../includes/settings.inc.php';
include '../fcts/restclient.class.php';
$rest = new RestClient();
if (isset($_GET['action']) && $_GET['action'] == "logout") {
    $_SESSION = array();
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
    }
    session_destroy();
}
if (isset($_GET['code'])) {
    $_SESSION['meetupToken'] = $_GET['code'];
    $authorisationData = array("client_id" => $_CONFIG['meetupKey'], "client_secret" => $_CONFIG['meetupSecret'], "grant_type" => "authorization_code", "redirect_uri" => $_CONFIG['meetupWebsite'], "code" => $_SESSION['meetupToken']);
    //Reset application authorisation
    $reply = $rest->setUrl('https://secure.meetup.com/oauth2/access')->post($authorisationData);
    $_SESSION['access_token'] = $reply['access_token'];
    //Read profile
    $profil = $rest->setUrl('https://api.meetup.com/2/member/self/?access_token=' . $_SESSION['access_token'])->get();
    $_SESSION['name'] = $profil['name'];
    $_SESSION['thumb_link'] = $profil['photo']['thumb_link'];
    $_SESSION['id'] = $profil['id'];
}
 //////	sentiment
 $url = "http://173.254.41.118:8080/mycorpus/sentiment";
 $response = \Httpful\Request::post($url)->sendsJson()->body($lsa_post)->send();
 // And you're ready to go!
 $code = $response->code;
 //http://173.254.41.118:8080/mycorpus /sentiment
 if ($code == 200) {
     $url = "http://173.254.41.118:8080/mycorpus/sentiment/" . $id;
     $response = \Httpful\Request::get($url)->send();
     $sentiment = $response->body->sentiment;
     $code = $response->code;
     //http://173.254.41.118:8080/mycorpus /sentiment/ + myPost["_id"]
     //print_r($sentiment);
     if ($code == 200) {
         $url = "http://173.254.41.118:8080/mycorpus/lsa/" . $id;
         $restclient = new RestClient();
         $result = $restclient->get($url);
         $lsa = json_decode($result->response, true);
         //print_r($lsa);
         $lsa_post = $lsa['post_assignments'];
         $lsa_topic = $lsa['topic_assignments'];
         //print_r($lsa_topic);
         foreach ($lsa_topic['0'] as $value) {
             $str = strlen($value);
             if ($str >= 4) {
                 $topic_01[] = $value;
             }
         }
         foreach ($lsa_topic['1'] as $value) {
             $str = strlen($value);
             if ($str >= 4) {
<?php

require 'oauth_common/lib/OAuth.php';
require 'oauth_common/includes/OAuthSignatureMethod_HMAC.inc';
require 'rest_client/includes/RestClient.php';
require 'rest_client/includes/RestClientRequest.php';
require 'rest_client/includes/RestClientOAuth.php';
$consumer = new OAuthConsumer('', '');
$token = new OAuthToken('', '');
$oauth = new RestClientOAuth($consumer, $token, new OAuthSignatureMethod_HMAC('sha1'), TRUE);
$client = new RestClient($oauth, new RestClientBaseFormatter(RestClientBaseFormatter::FORMAT_JSON));
$time = microtime(TRUE);
var_dump($client->get('http://localhost:8000/some/res', array()));
$time = (microtime(TRUE) - $time) * 1000;
print "Ay, that took {$time} milliseconds";
Example #26
0
 /**
  *
  * Delete a AuthIdsType from the backend
  * @param string $policyID	id of the bucket
  * @throws Exception
  * @return bool
  */
 public function deleteAuthBucket($policyId, $bucketId)
 {
     $method = "DELETE";
     $url = E3_PROV_URL_POLICY . "/" . rawurlencode($policyId) . "/quotaRLBuckets/" . rawurlencode($bucketId);
     $restClient = new RestClient();
     $reply = $restClient->makeCall($url, $method);
     if ($reply->getHTTPCode() === "200") {
         return true;
     } else {
         $xml = simplexml_load_string($reply->getPayload());
         drupal_set_message((string) $xml->status, 'error');
         return false;
     }
 }
require_once 'validate/validate.php';
require_once 'util/date.php';
require_once 'util/constantes.php';
$matricula = $_POST['matricula'];
if (validaFormCalculaVCT()) {
    function capturarDadosVCT($matricula)
    {
        $dao = new dao_class();
        // $rowEntrevistado = $dao->selectEntrevistado($matricula);
        $rowDadosAntropometricos = $dao->selectDadosAntropometricos($matricula);
        $vetor = array('peso' => $rowDadosAntropometricos['nr_peso'], 'alturaCm' => $rowDadosAntropometricos['nr_altura'], 'sexo' => $rowDadosAntropometricos['tp_sexo'], 'idade' => getIdade($rowDadosAntropometricos['dt_nascimento']) / 12, 'nivel_esporte' => $rowDadosAntropometricos['nr_nivel_esporte']);
        return $vetor;
    }
    $dados = capturarDadosVCT($matricula);
    if ($dados && $dados['idade'] != 0) {
        $restClient = new RestClient(array('base_url' => "http://localhost/NutrIF_service"));
        $header = array('user_agent' => "nutrif-php/1.0", 'content-type' => "application/json");
        // Método get.
        $result = $restClient->get('analisarVCT', $vetor, $header);
        $vct = $result->info->http_code;
        $_SESSION['vct'] = $vct;
        header("location: formCalculaVCT.php");
    } else {
        $msg = "Matrícula não encontrada";
        $_SESSION['erro'] = $msg;
        header("location: formCalculaVCT.php");
    }
} else {
    header("location: formCalculaVCT.php");
}
/* }  else {
Example #28
0
 /**
  * Removes all the attributes for a given session id
  *
  * @param sessionId
  *            - The session id for which the attributes has to be removed
  *
  * @return App42Response if removed successfully
  */
 function removeAllAttributes($sessionId)
 {
     Util::throwExceptionIfNullOrBlank($sessionId, "session Id");
     $encodedSessionId = Util::encodeParams($sessionId);
     $responseObj = new App42Response();
     $objUtil = new Util($this->apiKey, $this->secretKey);
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $headerParams = array_merge($signParams, $metaHeaders);
         $signParams['sessionId'] = $sessionId;
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/id/" . $encodedSessionId;
         $response = RestClient::delete($baseURL, $params, null, null, $contentType, $accept, $headerParams);
         $sessionResponseObj = new SessionResponseBuilder();
         $sessionObj = $sessionResponseObj->buildResponse($response->getResponse());
         $responseObj->setStrResponse($sessionObj);
         $responseObj->setResponseSuccess(true);
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $responseObj;
 }
Example #29
0
 function getFacebookProfilesFromIds($facebookIds)
 {
     Util::throwExceptionIfNullOrBlank($facebookIds, "FacebookIds");
     $objUtil = new Util($this->apiKey, $this->secretKey);
     $body = null;
     try {
         $params = null;
         $headerParams = array();
         $queryParams = array();
         $signParams = $this->populateSignParams();
         $metaHeaders = $this->populateMetaHeaderParams();
         $headerParams = array_merge($signParams, $metaHeaders);
         if (is_array($facebookIds)) {
             $headerParams['userList'] = json_encode($facebookIds);
         } else {
             $headerParams['userList'] = $facebookIds;
         }
         $signature = urlencode($objUtil->sign($signParams));
         //die();
         $headerParams['signature'] = $signature;
         $contentType = $this->content_type;
         $accept = $this->accept;
         $baseURL = $this->url;
         $baseURL = $baseURL . "/facebook/ids";
         $response = RestClient::get($baseURL, $params, null, null, $contentType, $accept, $headerParams);
         $socialResponseObj = new SocialResponseBuilder();
         $socialObj = $socialResponseObj->buildResponse($response->getResponse());
     } catch (App42Exception $e) {
         throw $e;
     } catch (Exception $e) {
         throw new App42Exception($e);
     }
     return $socialObj;
 }
Example #30
0
<?php

// dummy example of RestClient
require_once 'include/untis/CommonUtils.php';
require_once 'include/RestClient.class.php';
$enteredUsername = "******";
//test account
$enteredPassword = "******";
$paras = array();
//$paras["callback"] = "?";
$paras["method"] = "login";
$paras["input_type"] = "JSON";
$paras["response_type"] = "JSON";
$json = getJSONObj();
$paras["rest_data"] = $json->encode(array(array("password" => $enteredPassword, "user_name" => $enteredUsername), "C3CRM", array("name" => "language", "value" => "en_US")));
$twitter = RestClient::post('http://crm123.sinaapp.com/rest.php', $paras);
//$twitter = RestClient::post( // Same for RestClient::get()
//            'http://crm123.sinaapp.com/rest.php?callback=?'
//            ,'{
//				method: "login",
//				input_type: "JSON",
//				response_type: "JSON",
//				rest_data: \'[{"password":"******","user_name":"'.$enteredUsername.'"},"C3CRM",{"name":"language","value":"en_US"}]\'
//			}'
//            ,''
//            ,''
//			,'application/json');
var_dump($twitter->getResponse());
echo "<br>aaaaaaaaaaaa<br>";
var_dump($twitter->getResponseCode());
echo "<br>bbbbbbbbbbb<br>";