Query/ServiceDescription.pm untested

filter: Statementstmt 0.0% 0 / 246 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 364 CC 40 SCAR 49.4
CC
40
Cov
0%
computed_statement_generator
272.0
new_with_model
182.0
answers_triple_pattern
132.0
CRAP 139.4
1 # RDF::Query::ServiceDescription
2 # -----------------------------------------------------------------------------
3  
4 =head1 NAME
5  
6 RDF::Query::ServiceDescription - Class for describing federated query data sources.
7  
8 =head1 VERSION
9  
10 This document describes RDF::Query::ServiceDescription version 2.919.
11  
12 =head1 METHODS
13  
14 =over 4
15  
16 =cut
17  
18 package RDF::Query::ServiceDescription;
19  
20 our ($VERSION);
21 BEGIN {
22 $VERSION = '2.919';
23 }
24  
25 use strict;
26 use warnings;
27 no warnings 'redefine';
28  
29 use URI::file;
30 use RDF::Trine::Iterator qw(smap swatch);
31 use Scalar::Util qw(blessed);
32 use LWP::UserAgent;
33 use Data::Dumper;
34  
35 =item C<< new ( $service_uri, %data ) >>
36  
37 =cut
38  
39 sub new {
40 my $class = shift;
41 my $uri = shift;
42 my %data = @_;
43 unless ($data{capabilities}) {
44 $data{capabilities} = [ { type => RDF::Query::Node::Resource->new('http://kasei.us/2008/04/sparql#any_triple') } ];
45  
46 }
47 my $data = {
48 url => $uri,
49 label => "SPARQL Endpoint $uri",
50 definitive => 0,
51 %data,
52 };
53 my $self = bless( $data, $class );
54 return $self;
55 }
56  
57 =item C<< new_from_uri ( $url ) >>
58  
59 Creates a new service description object using the DARQ-style service description
60 data located at C<< $url >>.
61  
62 =cut
63  
64 sub new_from_uri {
65 my $class = shift;
66 my $uri = shift;
67
68 my $ua = LWP::UserAgent->new( agent => "RDF::Query/$RDF::Query::VERSION" );
69 $ua->default_headers->push_header( 'Accept' => "application/rdf+xml;q=0.5,text/turtle;q=0.7,text/xml" );
70 my $resp = $ua->get( $uri );
71 unless ($resp->is_success) {
72 warn "No content available from $uri: " . $resp->status_line;
73 return;
74 }
75 my $content = $resp->content;
76
77 my $store = RDF::Trine::Store::DBI->temporary_store();
78 my $model = RDF::Trine::Model->new( $store );
79 my $parser = RDF::Trine::Parser->new('turtle');
80 $parser->parse_into_model( $uri, $content, $model );
81 return $class->new_with_model( $model );
82 }
83  
84 =item C<< new_with_model ( $model ) >>
85  
86 Creates a new service description object using the DARQ-style service description
87 data loaded in the supplied C<< $model >> object.
88  
89 =cut
90  
91 sub new_with_model {
92 my $class = shift;
93 my $model = shift;
94 my ($label, $url, $triples, $definitive, @capabilities, @patterns);
95 my $l = Log::Log4perl->get_logger("rdf.query.servicedescription");
96 my $infoquery = RDF::Query->new( <<"END" );
97 PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
98 PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
99 PREFIX foaf: <http://xmlns.com/foaf/0.1/#>
100 PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
101 PREFIX sd: <http://darq.sf.net/dose/0.1#>
102 SELECT ?label ?url ?size ?def
103 WHERE {
104 ?s a sd:Service ;
105 rdfs:label ?label ;
106 sd:url ?url .
107 OPTIONAL { ?s sd:totalTriples ?size . FILTER( ISLITERAL(?size) ) }
108 OPTIONAL { ?s sd:isDefinitive ?def . FILTER( ISLITERAL(?def) ) }
109 FILTER( ISLITERAL(?label) && ISURI(?url) ).
110 }
111 LIMIT 1
112 END
113 ($label, $url, $triples, my $def) = $infoquery->get( $model );
114 return undef unless (defined $label);
115 $definitive = (defined($def) ? ($def->literal_value eq 'true' ? 1 : 0) : 0);
116
117 {
118 my $capquery = RDF::Query->new( <<"END" );
119 PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
120 PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
121 PREFIX foaf: <http://xmlns.com/foaf/0.1/#>
122 PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
123 PREFIX sd: <http://darq.sf.net/dose/0.1#>
124 PREFIX sparql: <http://kasei.us/2008/04/sparql#>
125 SELECT DISTINCT ?pred ?type ?sofilter ?ssel ?osel ?triples
126 WHERE {
127 [] a sd:Service ;
128 sd:capability ?cap .
129 {
130 ?cap sd:predicate ?pred .
131 } UNION {
132 ?cap a ?type .
133 FILTER(?type = sparql:any_triple)
134 }
135 OPTIONAL { ?cap sd:sofilter ?sofilter }
136 OPTIONAL { ?cap sd:objectSelectivity ?osel }
137 OPTIONAL { ?cap sd:subjectSelectivity ?ssel }
138 OPTIONAL { ?cap sd:triples ?triples }
139 }
140 END
141 my $iter = $capquery->execute( $model );
142 while (my $row = $iter->next) {
143 my ($p, $type, $f, $ss, $os, $t) = @{ $row }{ qw(pred type sofilter ssel osel triples) };
144 my $data = ($p)
145 ? { pred => $p }
146 : { type => $type };
147 $data->{ object_selectivity } = $os if (defined $os);
148 $data->{ subject_selectivity } = $ss if (defined $ss);
149 $data->{ size } = $t if (defined $t);
150 if (defined $f) {
151 my $base;
152 my $parser = RDF::Query::Parser::SPARQL->new();
153 my $expr = $parser->parse_expr( $f->literal_value, $base, {} );
154 $data->{ sofilter } = $expr;
155 }
156 push(@capabilities, $data);
157 }
158 }
159
160 {
161 my $var_id = 1;
162 my @statements;
163 my %patterns;
164 my %bnode_map;
165
166 my $patterns = $model->get_statements( undef, RDF::Trine::Node::Resource->new('http://kasei.us/2008/04/sparql#pattern'), undef );
167 while (my $st = $patterns->next) {
168 my $pattern = $st->object;
169 my @queue = ($pattern);
170 while (my $subj = shift(@queue)) {
171 my $stream = $model->get_statements( $subj, undef, undef );
172 while (my $st = $stream->next) {
173 push(@queue, $st->object);
174 my @nodes = ($subj, $st->predicate, $st->object);
175 foreach my $i (0 .. $#nodes) {
176 if ($nodes[$i]->isa('RDF::Query::Node::Blank')) {
177 if (exists($bnode_map{ $nodes[$i]->as_string })) {
178 $nodes[$i] = $bnode_map{ $nodes[$i]->as_string };
179 } else {
180 $nodes[$i] = $bnode_map{ $nodes[$i]->as_string } = RDF::Query::Node::Variable->new('p' . $var_id++);
181 }
182 }
183 }
184 my $st = RDF::Query::Algebra::Triple->new( @nodes );
185 push(@{ $patterns{ $pattern->as_string } }, $st );
186 }
187 }
188 }
189 foreach my $k (keys %patterns) {
190 my $bgp = RDF::Query::Algebra::BasicGraphPattern->new( @{ $patterns{ $k } } );
191 $l->debug("SERVICE BGP: " . $bgp->as_sparql({}, ''));
192 push( @patterns, $bgp );
193 }
194 }
195
196 my %data = (
197 label => (ref($label) ? $label->literal_value : ''),
198 size => (ref($triples) ? $triples->literal_value : ''),
199 definitive => $definitive,
200 capabilities => \@capabilities,
201 patterns => \@patterns,
202 );
203 return $class->new( $url->uri_value, %data );
204 }
205  
206 =item C<< url >>
207  
208 Returns the endpoint URL of the service.
209  
210 =cut
211  
212 sub url {
213 my $self = shift;
214 return $self->{url};
215 }
216  
217 =item C<< size >>
218  
219 Returns the number of triples the service claims to have.
220  
221 =cut
222  
223 sub size {
224 my $self = shift;
225 return $self->{size};
226 }
227  
228 =item C<< label >>
229  
230 Returns the label of the service.
231  
232 =cut
233  
234 sub label {
235 my $self = shift;
236 return $self->{label};
237 }
238  
239 =item C<< definitive >>
240  
241 Returns true if the endpoint claims to have definitive information.
242  
243 =cut
244  
245 sub definitive {
246 my $self = shift;
247 return $self->{definitive};
248 }
249  
250 =item C<< capabilities >>
251  
252 Returns an ARRAY reference of capabilities (as HASH references) of the service.
253 Each capability will contain information on size, selectivity, any subject-object
254 filter, and required predicate, with the following classes:
255  
256 $capability->{object_selectivity} # RDF::Trine::Node::Literal xsd:double
257 $capability->{sofilter} # RDF::Query::Expression
258 $capability->{size} # RDF::Trine::Node::Literal xsd:integer
259 $capability->{pred} # RDF::Trine::Node::Resource
260  
261 =cut
262  
263 sub capabilities {
264 my $self = shift;
265 return $self->{capabilities};
266 }
267  
268 =item C<< patterns >>
269  
270 Returns an ARRAY reference of RDF::Query::Algebra::BasicGraphPattern objects
271 representing common patterns used by the endpoint.
272  
273 =cut
274  
275 sub patterns {
276 my $self = shift;
277 return $self->{patterns};
278 }
279  
280 =item C<< computed_statement_generator >>
281  
282 Returns a closure appropriate for passing to C<< RDF::Query->add_computed_statement_generator >>
283 to generate statement iterators for the remote service.
284  
285 This closure takes C<< ($query, $bridge, \%bound, $subj, $pred, $obj [, $context ] ) >>
286 as arguments and returns either C<< undef >> if no statements can be generated given
287 the arguments, or a C<< RDF::Trine::Iterator::Graph >> iterator containing
288 statements matching C<< $subj, $pred, $obj [, $context ] >>.
289  
290 =cut
291  
292 sub computed_statement_generator {
293 my $self = shift;
294 my $caps = $self->capabilities;
295 my %preds = map { $_->{pred}->uri_value => $_ } grep { exists $_->{pred} } @$caps;
296 my $l = Log::Log4perl->get_logger("rdf.query.servicedescription");
297
298 return sub {
299 my $query = shift;
300 my $bridge = shift;
301 my $bound = shift;
302 my $_cast = $bridge->can('_cast_to_local');
303 my $cast = sub { my $n = shift; return unless $n; $n->isa('RDF::Query::Node') ? $n : $_cast->( $n ) };
304 my $s = $cast->( shift );
305 my $p = $cast->( shift );
306 my $o = $cast->( shift );
307 my $c = $cast->( shift );
308 return undef if ($c); # named statements can't be retrieved from another endpoint.
309 return undef unless ($p); # we need a predicate for matching against service capabilities.
310 my $puri = $p->uri_value;
311
312 my $cap = $preds{ $puri };
313 if ($self->definitive) {
314 return unless ($cap); # no capability matches this predicate.
315 } else {
316 $cap ||= {};
317 }
318
319 my $ok = 1;
320 my $sofilter = $cap->{ sofilter };
321 if ($sofilter) {
322 my %vars = map { $_ => 1 } $sofilter->referenced_variables;
323 my $runnable = 1;
324 if ($vars{ subject }) {
325 unless ($bound->{subject}) {
326 $runnable = 0;
327 $l->debug( "statement generator isn't runnable: subject is not bound" );
328 }
329 }
330 if ($vars{ object }) {
331 unless ($bound->{object}) {
332 $runnable = 0;
333 $l->debug( "statement generator isn't runnable: object is not bound" );
334 }
335 }
336 if ($runnable) {
337 my $bound = { subject => $s, object => $o };
338 my $bool = RDF::Query::Node::Resource->new( "sparql:ebv" );
339 my $filter = RDF::Query::Expression::Function->new( $bool, $sofilter );
340 my $value = $filter->evaluate( $query, $bound );
341 my $nok = ($value->literal_value eq 'false');
342 if ($nok) {
343 $ok = 0;
344 $l->debug( "statement generator didn't pass sofilter: " . $sofilter->sse({}, '') );
345 }
346 }
347 }
348
349 if ($ok) {
350 my @triple = ($s,$p,$o);
351 foreach my $i (0 .. $#triple) {
352 my $node = $triple[$i];
353 if ($node->isa('RDF::Query::Node::Blank')) {
354 # blank nodes need special handling, since we can't directly reference
355 # blank nodes on a remote endpoint.
356
357 # for now, we'll just assume that this is a losing battle, and no
358 # results are possible when trying to use a blank node to identify
359 # remote nodes (which is an acceptable reading of the spec). so return
360 # an empty iterator without actually making the remote call.
361 return RDF::Trine::Iterator::Bindings->new();
362 }
363 }
364
365 my $st = RDF::Query::Algebra::Triple->new( @triple );
366 $l->debug( "running statement generator for " . $st->sse({}, '') );
367 $l->debug( "running statement generator with pre-bound data: " . Dumper($bound) );
368
369 my $ggp = RDF::Query::Algebra::GroupGraphPattern->new( $st );
370 my $service = RDF::Query::Algebra::Service->new(
371 RDF::Query::Node::Resource->new( $self->url ),
372 $ggp
373 );
374 my $context = RDF::Query::ExecutionContext->new(
375 bound => {},
376 );
377 my ($plan) = RDF::Query::Plan->generate_plans( $service, $context );
378 $plan->execute( $context );
379 my $bindings = RDF::Trine::Iterator::Bindings->new( sub {
380 my $vb = $plan->next;
381 return $vb;
382 } );
383 my $iter = smap {
384 my $bound = shift;
385 my $triple = $st->bind_variables( $bound );
386 $triple->label( origin => $self->url );
387 $triple;
388 } $bindings;
389 return $iter;
390 } else {
391 return undef;
392 }
393 };
394 }
395  
396  
397 =item C<< answers_triple_pattern ( $triple ) >>
398  
399 Returns true if the service described by this object can answer queries
400 comprised of the supplied triple pattern.
401  
402 =cut
403  
404 sub answers_triple_pattern {
405 my $self = shift;
406 my $triple = shift;
407 my $l = Log::Log4perl->get_logger("rdf.query.servicedescription");
408 $l->debug( 'checking triple for service compatability: ' . $triple->sse );
409
410 my $caps = $self->capabilities;
411
412 my @wildcards = grep { exists $_->{type} and $_->{type}->uri_value eq 'http://kasei.us/2008/04/sparql#any_triple' } @$caps;
413 if (@wildcards) {
414 # service can answer any triple pattern, so return true.
415 return 1;
416 }
417
418 my @pred_caps = grep { exists $_->{pred} } @$caps;
419 my $p = $triple->predicate;
420 if (not($p->isa('RDF::Trine::Node::Variable'))) { # if predicate is bound (not a variable)
421 my $puri = $p->uri_value;
422 $l->trace(" service compatability based on predicate: $puri");
423 my %preds = map { $_->{pred}->uri_value => $_ } @pred_caps;
424 $l->trace(" service supports predicates: " . join(', ', keys %preds));
425 my $cap = $preds{ $puri };
426 unless ($cap) {
427 # no capability matches this predicate.
428 $l->debug("*** service doesn't support the predicate $puri");
429 return 0;
430 }
431
432 my $ok = 1;
433 my $sofilter = $cap->{ sofilter };
434 if ($sofilter) {
435 my %vars = map { $_ => 1 } $sofilter->referenced_variables;
436 my $runnable = 1;
437 if ($vars{ subject }) {
438 unless ($triple->subject) {
439 $l->debug( "triple pattern doesn't match the subject filter" );
440 $runnable = 0;
441 }
442 }
443 if ($vars{ object }) {
444 unless ($triple->object) {
445 $l->debug( "triple pattern doesn't match the object filter" );
446 $runnable = 0;
447 }
448 }
449 if ($runnable) {
450 my $bridge = RDF::Query->new_bridge;
451 my $bound = { subject => $triple->subject, object => $triple->object };
452 my $bool = RDF::Query::Node::Resource->new( "sparql:ebv" );
453 my $filter = RDF::Query::Expression::Function->new( $bool, $sofilter );
454
455 # XXX "ASK {}" is just a simple stand-in query allowing us to have a valid query
456 # XXX object to pass to $filter->evaluate below. evaluating a filter really
457 # XXX shouldn't require a query object in this case, since it's not going
458 # XXX to even touch a datastore, but the code needs to be changed to allow for that.
459 my $query = RDF::Query->new("ASK {}");
460 my $value = $filter->evaluate( $query, $bound );
461 my $nok = ($value->literal_value eq 'false');
462 if ($nok) {
463 $l->debug( "triple pattern doesn't match the sofilter" );
464 $ok = 0;
465 }
466 }
467 }
468
469 return $ok;
470 } else {
471 # predicate is a variable in the triple pattern. can we matchit based on sparql:pattern?
472 $l->trace("service doesn't handle triple patterns with unbound predicates");
473 return 0;
474 }
475 }
476  
477  
478  
479 1;
480  
481 __END__