/** Get the HTTP Client object used to fetch RDF data * * If no HTTP Client has previously been set, then a new * default (EasyRdf_Http_Client) client will be created. * * @return object mixed The HTTP client object */ public static function getDefaultHttpClient() { if (!isset(self::$_defaultHttpClient)) { self::$_defaultHttpClient = new EasyRdf_Http_Client(); } return self::$_defaultHttpClient; }
public function setUp() { EasyRdf_Http::setDefaultHttpClient($this->_client = new EasyRdf_Http_MockClient()); $this->_graphStore = new EasyRdf_GraphStore('http://localhost:8080/data/'); // Ensure that the built-in n-triples parser is used EasyRdf_Format::registerSerialiser('ntriples', 'EasyRdf_Serialiser_Ntriples'); }
/** * Requires the following three parameters. * @param string $endpoint SPARQL endpoint address. * @param object $graph an EasyRDF SPARQL graph instance. * @param object $model a Model instance. */ public function __construct($endpoint, $graph, $model) { // if special cache control (typically no-cache) was requested by the // client, set the same type of cache control headers also in subsequent // in the SPARQL requests (this is useful for performance testing) $cache_control = filter_input(INPUT_SERVER, 'HTTP_CACHE_CONTROL', FILTER_SANITIZE_STRING); $pragma = filter_input(INPUT_SERVER, 'HTTP_PRAGMA', FILTER_SANITIZE_STRING); if ($cache_control !== null || $pragma !== null) { $val = $pragma !== null ? $pragma : $cache_control; // configure the HTTP client used by EasyRdf_Sparql_Client $httpclient = EasyRdf_Http::getDefaultHttpClient(); $httpclient->setHeaders('Cache-Control', $val); EasyRdf_Http::setDefaultHttpClient($httpclient); // actually redundant.. } // create the EasyRDF SPARQL client instance to use $this->client = new EasyRdf_Sparql_Client($endpoint); $this->graph = $graph; $this->model = $model; // set graphClause so that it can be used by all queries if ($this->isDefaultEndpoint()) { $this->graphClause = "GRAPH {$graph}"; } elseif ($graph) { $this->graphClause = "GRAPH <{$graph}>"; } else { $this->graphClause = ""; } }
/** * Set up the test suite before each test */ public function setUp() { EasyRdf_Http::setDefaultHttpClient($this->_client = new EasyRdf_Http_MockClient()); $this->_graph = new EasyRdf_Graph('http://example.com/graph'); $this->_uri = 'http://example.com/#me'; $this->_graph->setType($this->_uri, 'foaf:Person'); $this->_graph->add($this->_uri, 'rdf:test', 'Test A'); $this->_graph->add($this->_uri, 'rdf:test', new EasyRdf_Literal('Test B', 'en')); }
/** * Just an helper to use HttPClient as default EastRdf_default_client) */ public static function useIdentity($username = null, $password = null, $timeout = null) { $httpClient = \EasyRdf_Http::getDefaultHttpClient(); // if current default http client does not provide setAuth use a new instance of HttpClient if (!($httpClient instanceof \Zend_Http_Client or $httpClient instanceof HttpClient)) { $httpClient = new HttpClient(null, array('maxredirects' => 5, 'useragent' => 'BOTK HttpClient', 'timeout' => ini_get('max_execution_time') || 30)); } $httpClient->setAuth($username, $password); return \EasyRdf_Http::setDefaultHttpClient($httpClient); }
/** * Set up the test suite before each test */ public function setUp() { // Reset to built-in parsers EasyRdf_Format::registerParser('ntriples', 'EasyRdf_Parser_Ntriples'); EasyRdf_Format::registerParser('rdfxml', 'EasyRdf_Parser_RdfXml'); EasyRdf_Format::registerParser('turtle', 'EasyRdf_Parser_Turtle'); EasyRdf_Http::setDefaultHttpClient($this->_client = new EasyRdf_Http_MockClient()); $this->_graph = new EasyRdf_Graph('http://example.com/graph'); $this->_uri = 'http://example.com/#me'; $this->_graph->setType($this->_uri, 'foaf:Person'); $this->_graph->add($this->_uri, 'rdf:test', 'Test A'); $this->_graph->add($this->_uri, 'rdf:test', new EasyRdf_Literal('Test B', 'en')); }
/** * Load RDF data into the graph. * * If a URI is supplied, but no data then the data will * be fetched from the URI. * * The document type is optional and can be specified if it * can't be guessed or got from the HTTP headers. * * @param string $uri The URI of the data to load * @param string $data Optional data for the graph * @param string $format Optional format of the data */ public function load($uri = null, $data = null, $format = null) { $this->checkResourceParam($uri, true); if (!$uri) { throw new EasyRdf_Exception("No URI given to load() and the graph does not have a URI."); } if (!$data) { # No data was given - try and fetch data from URI # FIXME: prevent loading the same URI multiple times $client = EasyRdf_Http::getDefaultHttpClient(); $client->resetParameters(true); $client->setUri($uri); $client->setMethod('GET'); $client->setHeaders('Accept', EasyRdf_Format::getHttpAcceptHeader()); $response = $client->request(); if (!$response->isSuccessful()) { throw new EasyRdf_Exception("HTTP request for {$uri} failed: " . $response->getMessage()); } $data = $response->getBody(); if (!$format) { $format = $response->getHeader('Content-Type'); $format = preg_replace('/;(.+)$/', '', $format); } } // Parse the data return $this->parse($data, $format, $uri); }
/** Make a query to the SPARQL endpoint * * SELECT and ASK queries will return an object of type * EasyRdf_Sparql_Result. * * CONSTRUCT and DESCRIBE queries will return an object * of type EasyRdf_Graph. * * @param string $query The query string to be executed * @return object EasyRdf_Sparql_Result|EasyRdf_Graph Result of the query. */ public function query($query) { # Add namespaces to the queryString $prefixes = ''; foreach (EasyRdf_Namespace::namespaces() as $prefix => $uri) { if (strpos($query, "{$prefix}:") !== false and strpos($query, "PREFIX {$prefix}:") === false) { $prefixes .= "PREFIX {$prefix}: <{$uri}>\n"; } } $client = EasyRdf_Http::getDefaultHttpClient(); $client->resetParameters(); $client->setUri($this->_uri); $client->setMethod('GET'); $accept = EasyRdf_Format::getHttpAcceptHeader(array('application/sparql-results+json' => 1.0, 'application/sparql-results+xml' => 0.8)); $client->setHeaders('Accept', $accept); $client->setParameterGet('query', $prefixes . $query); $response = $client->request(); if ($response->isSuccessful()) { $type = $response->getHeader('Content-Type'); if (strpos($type, 'application/sparql-results') === 0) { return new EasyRdf_Sparql_Result($response->getBody(), $type); } else { return new EasyRdf_Graph($this->_uri, $response->getBody(), $type); } } else { throw new EasyRdf_Exception("HTTP request for SPARQL query failed: " . $response->getBody()); } }
public function testLoad() { EasyRdf_Http::setDefaultHttpClient($client = new EasyRdf_Http_MockClient()); $client->addMock('GET', 'http://example.com/foaf.json', readFixture('foaf.json')); $graph = new EasyRdf_Graph('http://example.com/'); $resource = $graph->resource('http://example.com/foaf.json'); $resource->load(); $this->assertStringEquals('Joe Bloggs', $graph->get('http://www.example.com/joe#me', 'foaf:name')); }
/** Delete a graph from the graph store * * The URI can either be a full absolute URI or * a URI relative to the URI of the graph store. * * @param string $uriRef The URI of graph to be added to * @return object EasyRdf_Http_Response The response from the graph store */ public function delete($uriRef) { $graphUri = $this->_parsedUri->resolve($uriRef)->toString(); $dataUrl = $this->urlForGraph($graphUri); $client = EasyRdf_Http::getDefaultHttpClient(); $client->resetParameters(true); $client->setUri($dataUrl); $client->setMethod('DELETE'); $response = $client->request(); if (!$response->isSuccessful()) { throw new EasyRdf_Exception("HTTP request to delete {$dataUrl} failed: " . $response->getMessage()); } return $response; }
private function fetchResourceFromUri($uri) { try { // change the timeout setting for external requests $httpclient = EasyRdf_Http::getDefaultHttpClient(); $httpclient->setConfig(array('timeout' => $this->getConfig()->getHttpTimeout())); EasyRdf_Http::setDefaultHttpClient($httpclient); $client = EasyRdf_Graph::newAndLoad(EasyRdf_Utils::removeFragmentFromUri($uri)); return $client->resource($uri); } catch (Exception $e) { return null; } }
public function setUp() { EasyRdf_Http::setDefaultHttpClient($this->_client = new EasyRdf_Http_MockClient()); $this->_sparql = new EasyRdf_Sparql_Client('http://localhost:8080/sparql'); }
* This example creates a simple graph in memory, saves it to a local * graphstore and then fetches the data back using a SPARQL SELECT query. * Zend's curl HTTP client adaptor is used to perform the HTTP requests. * * @package EasyRdf * @copyright Copyright (c) 2009-2011 Nicholas J Humfrey * @license http://unlicense.org/ */ set_include_path(get_include_path() . PATH_SEPARATOR . '../lib/'); // require the Zend Autoloader require_once 'Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->setFallbackAutoloader(true); // use the CURL based HTTP client adaptor $client = new Zend_Http_Client(null, array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'keepalive' => true, 'useragent' => "EasyRdf/zendtest")); EasyRdf_Http::setDefaultHttpClient($client); // Load the parsers and serialisers that we are going to use # FIXME: better way to do this? $autoloader->autoload('EasyRdf_Serialiser_Ntriples'); $autoloader->autoload('EasyRdf_Parser_Ntriples'); ?> <html> <head> <title>Zend Framework Example</title> </head> <body> <h1>Zend Framework Example</h1> <?php # Load some sample data into a graph
protected function request($type, $query) { // Check for undefined prefixes $prefixes = ''; foreach (EasyRdf_Namespace::namespaces() as $prefix => $uri) { if (strpos($query, "{$prefix}:") !== false and strpos($query, "PREFIX {$prefix}:") === false) { $prefixes .= "PREFIX {$prefix}: <{$uri}>\n"; } } $client = EasyRdf_Http::getDefaultHttpClient(); $client->resetParameters(); // Tell the server which response formats we can parse $accept = EasyRdf_Format::getHttpAcceptHeader(array('application/sparql-results+json' => 1.0, 'application/sparql-results+xml' => 0.8)); $client->setHeaders('Accept', $accept); if ($type == 'update') { $client->setMethod('POST'); $client->setUri($this->updateUri); $client->setRawData($prefixes . $query); $client->setHeaders('Content-Type', 'application/sparql-update'); } elseif ($type == 'query') { // Use GET if the query is less than 2kB // 2046 = 2kB minus 1 for '?' and 1 for NULL-terminated string on server $encodedQuery = 'query=' . urlencode($prefixes . $query); if (strlen($encodedQuery) + strlen($this->queryUri) <= 2046) { $delimiter = $this->queryUri_has_params ? '&' : '?'; $client->setMethod('GET'); $client->setUri($this->queryUri . $delimiter . $encodedQuery); } else { // Fall back to POST instead (which is un-cacheable) $client->setMethod('POST'); $client->setUri($this->queryUri); $client->setRawData($encodedQuery); $client->setHeaders('Content-Type', 'application/x-www-form-urlencoded'); } } $response = $client->request(); if ($response->getStatus() == 204) { // No content return $response; } elseif ($response->isSuccessful()) { list($type, $params) = EasyRdf_Utils::parseMimeType($response->getHeader('Content-Type')); if (strpos($type, 'application/sparql-results') === 0) { return new EasyRdf_Sparql_Result($response->getBody(), $type); } else { return new EasyRdf_Graph($this->queryUri, $response->getBody(), $type); } } else { throw new EasyRdf_Exception("HTTP request for SPARQL query failed: " . $response->getBody()); } }
/** A basic HTML response check using curl to check identifier exists * @access public * @return array */ public function checkType($identifier) { $key = md5($identifier . 'CheckRrcTypes'); if (!$this->getCache()->test($key)) { $client = new Zend_Http_Client(null, array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'keepalive' => true, 'useragent' => "finds.org.uk/easyrdf")); $client->setHeaders(array('accept' => 'application/sparql-results+xml')); EasyRdf_Http::setDefaultHttpClient($client); EasyRdf_Namespace::set('nm', 'http://nomisma.org/id/'); EasyRdf_Namespace::set('nmo', 'http://nomisma.org/ontology#'); EasyRdf_Namespace::set('skos', 'http://www.w3.org/2004/02/skos/core#'); EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); $sparql = new EasyRdf_Sparql_Client('http://nomisma.org/query'); $data = $sparql->query('SELECT * WHERE {' . ' ?type ?role nm:' . $identifier . ' ;' . ' a nmo:TypeSeriesItem ;' . ' skos:prefLabel ?label' . ' OPTIONAL {?type nmo:hasStartDate ?startDate}' . ' OPTIONAL {?type nmo:hasEndDate ?endDate}' . ' FILTER(langMatches(lang(?label), "en"))' . ' } ORDER BY ?label'); $this->getCache()->save($data); } else { $data = $this->getCache()->load($key); } return $data; }
public function testSetDefaultHttpClientString() { $this->setExpectedException('InvalidArgumentException', '$httpClient should be an object of class Zend_Http_Client or EasyRdf_Http_Client'); EasyRdf_Http::setDefaultHttpClient('foobar'); }
/** * Load RDF data into the graph from a URI. * * If no URI is given, then the URI of the graph will be used. * * The document type is optional but should be specified if it * can't be guessed or got from the HTTP headers. * * @param string $uri The URI of the data to load * @param string $format Optional format of the data (eg. rdfxml) * @return integer The number of triples added to the graph */ public function load($uri = null, $format = null) { $this->checkResourceParam($uri, true); if (!$uri) { throw new EasyRdf_Exception("No URI given to load() and the graph does not have a URI."); } // Setup the HTTP client $client = EasyRdf_Http::getDefaultHttpClient(); $client->resetParameters(true); $client->setConfig(array('maxredirects' => 0)); $client->setMethod('GET'); $client->setHeaders('Accept', EasyRdf_Format::getHttpAcceptHeader()); $requestUrl = $uri; $response = null; $redirectCounter = 0; do { // Have we already loaded it into the graph? $requestUrl = EasyRdf_Utils::removeFragmentFromUri($requestUrl); if (in_array($requestUrl, $this->loaded)) { return 0; } // Make the HTTP request $client->setHeaders('host', null); $client->setUri($requestUrl); $response = $client->request(); // Add the URL to the list of URLs loaded $this->loaded[] = $requestUrl; if ($response->isRedirect() and $location = $response->getHeader('location')) { // Avoid problems with buggy servers that add whitespace $location = trim($location); // Some servers return relative URLs in the location header // resolve it in relation to previous request $baseUri = new EasyRdf_ParsedUri($requestUrl); $requestUrl = $baseUri->resolve($location)->toString(); $requestUrl = EasyRdf_Utils::removeFragmentFromUri($requestUrl); // If it is a 303 then drop the parameters if ($response->getStatus() == 303) { $client->resetParameters(); } ++$redirectCounter; } elseif ($response->isSuccessful()) { // If we didn't get any location, stop redirecting break; } else { throw new EasyRdf_Http_Exception("HTTP request for {$requestUrl} failed: " . $response->getMessage(), $response->getStatus(), null, $response->getBody()); } } while ($redirectCounter < $this->maxRedirects); if (!$format or $format == 'guess') { list($format, $params) = EasyRdf_Utils::parseMimeType($response->getHeader('Content-Type')); } // Parse the data return $this->parse($response->getBody(), $format, $uri); }
/** Construct the function * @access public */ public function __construct() { $client = new Zend_Http_Client(null, array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'keepalive' => true, 'useragent' => "findsorguk", 'timeout' => 30)); EasyRdf_Http::setDefaultHttpClient($client); }