blib/lib/Apache/SPARQL/RDFStore.pm

filter: Statementstmt 100% 6 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 8 / 8 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Apache::SPARQL::RDFStore;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use base qw (Apache::SPARQL);
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 $Apache::SPARQL::RDFStore::VERSION = '0.3';
7  
8 use RDFStore::Model;
9  
10 use DBI;
11  
12 # for output-xslt parameter fancyness
13 use XML::LibXML;
14 use XML::LibXSLT;
15  
16 sub query {
17 my ($class, $ap, $query, $query_uri, $graph_id, $output_xslt, $output_type, $format, $limit ) = @_;
18  
19 $query = $class->_cat($ap, $query_uri)
20 if( ! $query or
21 $query eq '' or
22 $query =~ m/^\s+$/ );
23  
24 my $smart = $class->_param($ap, 'smart'); #1/0 flag whether or not use simple RDF/S inferencing
25 $smart = ( $smart and $smart !~ m/(0|no|off)/ ) ? 1 : 0 ;
26  
27 if( defined $limit and $limit < 0 ) {
28 $class->_error( $ap, "Negative LIMIT $limit" );
29 return $Apache::SPARQL::Responses{ 'OperationPointError' };
30 };
31  
32 if( $format !~ s/^\s*(rdfxml|ntriples|xml)\s*$/$1/ ) {
33 $class->_error( $ap, "Format $format is not supported" );
34 return $Apache::SPARQL::Responses{ 'OperationPointError' };
35 };
36  
37 #
38 # more advanced stuff
39 #
40 # Any other CGI paramter starting with the 'rdflet_' prefix is passed down to the SPARQL query itself, and can be referred
41 # into the SPARQL query as $$param_name. Multiple parameters result into a OR-ed list of value - each value can be either
42 # a full qulified URI resource or a literal (with it xml:lang or rdf:datatype attached), using some N-Triples/Turtle like syntax.
43 #
44 # Example:
45 #
46 # Given /sparql/?sparqlet_URL=<http://foo.bar/com.html>
47 #
48 # and the following SPARQL '&query' paramter
49 #
50 # prefix dc: <http://purl.org/dc/elements/1.1/>
51 # select ?title
52 # where ( $$URL dc:title ?title )
53 #
54 # would re-write the query as:
55 #
56 # prefix dc: <http://purl.org/dc/elements/1.1/>
57 # select ?title
58 # where ( <http://foo.bar/com.html> dc:title ?title )
59 #
60 # which will get the title of item 'http://foo.bar/com.html' - similarly if sparqler_title="foo bar title"@ch and so on..
61  
62 my %sparqlet_parameters = ();
63 my @params = $class->_param( $ap ); #any param
64 map {
65 my $name = $_;
66 if ( $name =~ s/^sparqlet_// ) {
67 $sparqlet_parameters{ $name } = { 'r' => [], 'l' => [] }
68 unless( exists $sparqlet_parameters{ $name } );
69  
70 my @values = $class->_param( $ap, 'sparqlet_'.$name );
71 foreach my $value ( @values ) {
72 if ( $value =~ s/^\s*\<([^>]+)\>\s*// ) {
73 push @{ $sparqlet_parameters{ $name }->{ 'r' } }, $1;
74 } elsif( $value =~ s/^\s*(%?[\"\']((([^\"\'\\\n\r])|(\\([ntbrf\\'\"])|([0-7][0-7?)|([0-3][0-7][0-7])))*)[\"\'](\@([a-z0-9]+(-[a-z0-9]+)?))?%?)\s*// ) {
75 push @{ $sparqlet_parameters{ $name }->{ 'l' } }, $1;
76 };
77 };
78 };
79 } @params;
80  
81 # merge graph-id/s and
82 #if( $class->_SPARQLhas_Source( $query ) ) {
83 #} else {
84 # };
85 my $data = new RDFStore::Model;
86 if($graph_id) {
87 foreach my $graph_id ( @{ $graph_id } ) {
88 # bad - try to guess out format from file extension
89 eval {
90 $data->getReader( ($graph_id =~ /\.(nt|ntriples)$/) ? 'N-Triples' : 'RDF/XML' )->parsestring(
91 $class->_cat( $ap, $graph_id ) );
92 };
93 if($@) {
94 $class->_error( $ap, "Cannot process graph-id $graph_id: $@ " );
95 return $Apache::SPARQL::Responses{ 'OperationPointError' };
96 };
97 };
98 };
99  
100 my $dbh = DBI->connect("DBI:RDFStore:", "sparqler", 0, {
101 'sourceModel' => $data,
102 'smarter' => $smart } );
103  
104 unless($dbh) {
105 $class->_error( $ap, "Oh dear, can not connect to rdfstore: $!" );
106 return $Apache::SPARQL::Responses{ 'OperationPointError' };
107 };
108  
109 $query = $class->_preprocess_SPARQL_query( $ap, $query, %sparqlet_parameters );
110  
111 my $sth;
112 eval {
113 $sth=$dbh->prepare($query);
114 $sth->execute();
115 };
116  
117 if($@) {
118 $sth->finish;
119 $class->_error( $ap, "Malformed query: $@ " );
120 return $Apache::SPARQL::Responses{ 'MalformedQuery' };
121 };
122  
123 my $serialization_format;
124 if( $sth->func('getQueryStatement')->getQueryType eq 'SELECT' ) {
125 if( $format eq 'rdfxml' ) {
126 # which is the RDF/XML result format
127 # see http://www.w3.org/2001/sw/DataAccess/tests/result-set#
128 $serialization_format = 'dawg-results';
129 } elsif( $format eq 'xml' ) {
130 # see http://www.w3.org/2001/sw/DataAccess/rf1/
131 $serialization_format = 'dawg-xml';
132 } elsif( $format eq 'ntriples' ) {
133 if( $output_xslt ) {
134 $sth->finish;
135 $class->_error( $ap, "N-Triples output can be applied to XSLT style-sheet $output_xslt" );
136 return $Apache::SPARQL::Responses{ 'OperationPointError' };
137 };
138
139 $serialization_format = 'N-Triples';
140 };
141  
142 # XSLT and limit make sense only for SELECT queries due we do return dawg-xml format
143 my $tot=0;
144 if( $output_xslt ) {
145  
146 # prepare to output things
147 $ap->content_type( ( $output_type ) ? $output_type : $class->_get_content_type( $format ) );
148  
149 if (! $class->_mp2 ) {
150 $ap->send_http_header();
151 };
152  
153 $output_xslt = $class->_cat( $ap, $output_xslt );
154 unless( $output_xslt ) {
155 $sth->finish;
156 $class->_error( $ap, "Cannot fetch XSLT style-sheet $output_xslt" );
157 return $Apache::SPARQL::Responses{ 'OperationPointError' };
158 };
159  
160 # need to read the whole result string in-memory becuase XSLT does not stream - need to look at STX?
161 my $whole_xml;
162  
163 eval {
164  
165 if( defined $limit and $limit == 0 ) {
166 # HACK due we do not do LIMIT into our SPARQL engine yet
167 $whole_xml = $sth->func( $serialization_format, 'fetchrow_XML' );
168 $whole_xml =~ m|<results>|;
169 $whole_xml = $` . $& . '</results></sparql>';
170 } else {
171 while ( my $xml = $sth->func( $serialization_format, 'fetchrow_XML' ) ) {
172 $whole_xml .= $xml;
173 $tot++;
174 if( defined $limit and $tot == $limit ) {
175 $whole_xml .= '</results></sparql>'
176 unless( $whole_xml =~ m|</results>\s*</sparql>\s*$|m ); # HACK!
177 last;
178 };
179 };
180 };
181  
182 }; # end eval
183  
184 if($@) {
185 $sth->finish;
186 $class->_error( $ap, "Cannot process query: $@ " );
187 return $Apache::SPARQL::Responses{ 'OperationPointError' };
188 };
189  
190 my $parser = XML::LibXML->new();
191 my $xslt_engine = XML::LibXSLT->new();
192  
193 my($source, $style_doc, $stylesheet, $results);
194  
195 eval {
196  
197 $source = $parser->parse_string($whole_xml);
198 $style_doc = $parser->parse_string($output_xslt);
199  
200 $stylesheet = $xslt_engine->parse_stylesheet($style_doc);
201 $results = $stylesheet->transform($source);
202  
203 $ap->print( $stylesheet->output_string($results) );
204  
205 }; # end eval
206  
207 if($@) {
208 $sth->finish;
209 $class->_error( $ap, "Cannot process query output with $output_xslt XSLT style-sheet: $@ " );
210 return $Apache::SPARQL::Responses{ 'OperationPointError' };
211 };
212 } else {
213 # prepare to output things
214 $ap->content_type( $class->_get_content_type( $format ) );
215  
216 if (! $class->_mp2 ) {
217 $ap->send_http_header();
218 };
219  
220 # we stream otherwise
221  
222 eval {
223  
224 if( defined $limit and $limit == 0 ) {
225 # HACK due we do not do LIMIT into our SPARQL engine yet
226 my $xml = $sth->func( $serialization_format, 'fetchrow_XML' );
227 $xml =~ m|<results>|;
228 $xml = $` . $& . '</results></sparql>';
229 $ap->print( $xml );
230 } else {
231 while ( my $xml = $sth->func( $serialization_format, 'fetchrow_XML' ) ) {
232 $tot++;
233 if( defined $limit and $tot == $limit ) {
234 $xml .= '</results></sparql>'
235 unless( $xml =~ m|</results>\s*</sparql>\s*$|m ); # HACK!
236  
237 $ap->print( $xml );
238  
239 last;
240 } else {
241 $ap->print( $xml );
242 };
243 };
244 };
245
246 }; # end eval
247  
248 if($@) {
249 $sth->finish;
250 $class->_error( $ap, "Cannot process query output with $output_xslt XSLT style-sheet: $@ " );
251 return $Apache::SPARQL::Responses{ 'OperationPointError' };
252 };
253 };
254 } else {
255 # prepare to output things
256 $ap->content_type( $class->_get_content_type( $format ) );
257  
258 if (! $class->_mp2 ) {
259 $ap->send_http_header();
260 };
261  
262 # we need to reject output-xslt param here I guess
263  
264 if( $format eq 'rdfxml' ) {
265 $serialization_format = 'RDF/XML';
266 } elsif( $format eq 'xml' ) {
267 $sth->finish;
268 $class->_error( $ap, "XML output is not possible but SELECT queries" );
269 return $Apache::SPARQL::Responses{ 'OperationPointError' };
270 } elsif( $format eq 'ntriples' ) {
271 $serialization_format = 'N-Triples';
272 };
273  
274 eval {
275  
276 while (my $rdf = $sth->func( $serialization_format, 'fetchsubgraph_serialize' )) {
277 # we stream otherwise
278 $ap->print( $rdf );
279 };
280  
281 }; # end eval
282 };
283  
284 $sth->finish;
285  
286 return $Apache::SPARQL::Responses{ 'OK' };
287 };
288  
289 sub _preprocess_SPARQL_query {
290 my ( $class, $ap, $query, %parameters ) = @_;
291  
292 my $preprocessed_query = $query;
293  
294 foreach my $param ( keys %parameters ) {
295 my $to_substitute = '';
296 if ( scalar( @{$parameters{ $param }->{'r'}} ) > 0 ) {
297 $to_substitute = '<' . join(' , ', @{ $parameters{ $param }->{'r'} } ) . '>';
298 } elsif( scalar( @{$parameters{ $param }->{'l'}} ) == 1 ) {
299 $to_substitute = $parameters{ $param }->{'l'}->[0];
300 } elsif( scalar( @{$parameters{ $param }->{'l'}} ) > 1 ) {
301 $to_substitute = '<' . join(' , ', @{ $parameters{ $param }->{'l'} } ) . '>';
302 };
303  
304 $preprocessed_query =~ s|\$\$$param|$to_substitute|mig;
305 };
306  
307 #$class->_debug( $ap, "PREPROCESSED_QUERY:\n\n$preprocessed_query\n\n" );
308  
309 return $preprocessed_query;
310 };
311  
312 sub _error {
313 my ($class, $ap, $err ) = @_;
314  
315 $ap->log()->error( " [ Apache::SPARQL::RDFStore ERROR ] $err " );
316 };
317  
318 sub _debug {
319 my ($class, $ap, $msg ) = @_;
320  
321 $ap->log()->error( " [ Apache::SPARQL::RDFStore DEBUG ] $msg " );
322 };
323  
324 sub _SPARQLhas_Source {
325 my ($class, $query) = @_;
326  
327 return ( $query =~ m/\s*(FROM|FROM NAMED|LOAD|WITH)\s*((\<[^>]*\>)|(([a-zA-Z0-9\-_$\.]+)?:([a-zA-Z0-9\-_$\.]+)))\s+/i );
328 };
329  
330 # format "rdfxml", "xml", "turtle", "ntriples" ... [defaults vary] (1)
331 sub _get_content_type {
332 my ($class, $format) = @_;
333  
334 my $content_type;
335 if( $format eq 'rdfxml' ) {
336 $content_type = 'application/rdf+xml';
337 } elsif( $format eq 'xml' ) {
338 $content_type = 'application/sparql-results+xml';
339 } elsif( $format eq 'turtle' ) {
340 $content_type = 'application/x-turtle';
341 } elsif( $format eq 'ntriples' ) {
342 $content_type = 'application/ntriples';
343 } else {
344 $content_type = 'text/plain';
345 };
346 };
347  
348 sub getGraph {
349 my ($class, $ap, $graph_id, $format ) = @_;
350  
351 return $Apache::SPARQL::Responses{ 'MalformedRequest' };
352 };
353  
354 sub getServiceDescription {
355 my ($class, $ap) = @_;
356  
357 return $Apache::SPARQL::Responses{ 'MalformedRequest' };
358 };
359  
360 =cut
361  
362 =head1 NAME
363  
364 Apache::SPARQL::RDFStore - A mod_perl handler which implements SPARQL HTTP bindings with RDFStore
365  
366  
367 =head1 SYNOPSIS
368  
369 <Location /rdfstore>
370  
371 SetHandler perl-script
372 PerlHandler Apache::SPARQL::RDFStore
373  
374 </Location>
375  
376 #
377  
378 my $ua = LWP::UserAgent->new();
379 my $req = HTTP::Request->new(GET => "http://pim.example/rdfstore?query=PREFIX+foaf%3A+%3Chttp%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2F%3E%0
380 D%0ASELECT+%3Fpg%0D%0AWHERE%0D%0A++%28%3Fwho+foaf%3Aname+%22Norm+Walsh%22%29%0D%0A++%28%3Fwho+foaf%3Aweblog+%3Fpg%29%0D%0A");
381  
382 my $res = $ua->request($req);
383  
384 =head1 DESCRIPTION
385  
386 Apache::SPARQL::RDFStore is a mod_perl handler which implements SPARQL HTTP bindings with RDFStore...
387  
388 =head1 MOD_PERL COMPATIBILITY
389  
390 This handler will work with both mod_perl 1.x and mod_perl 2.x.
391  
392 =head1 AUTHOR
393  
394 Alberto Reggiori <alberto@asemantics.com>
395  
396 =head1 SEE ALSO
397  
398 Apache::SPARQL
399 http://www.w3.org/TR/rdf-sparql-protocol/
400 http://www.w3.org/2001/sw/DataAccess/proto-wd/ (editor working draft)
401 http://www.w3.org/2001/sw/DataAccess/prot26
402 http://www.w3.org/TR/rdf-sparql-query/
403 http://www.w3.org/2001/sw/DataAccess/rq23/ (edit working draft)
404  
405 =head1 LICENSE
406  
407 see LICENSE file included into this distribution
408  
409 =cut
410  
411 return 1;
↑ Summary