| 1 | =head1 NAME | ||
| 2 | |||
| 3 | RDF::Endpoint - A SPARQL Protocol Endpoint implementation | ||
| 4 | |||
| 5 | =head1 VERSION | ||
| 6 | |||
| 7 | This document describes RDF::Endpoint version 0.11. | ||
| 8 | |||
| 9 | =head1 SYNOPSIS | ||
| 10 | |||
| 11 | plackup /usr/local/bin/endpoint.psgi | ||
| 12 | |||
| 13 | =head1 DESCRIPTION | ||
| 14 | |||
| 15 | This modules implements the SPARQL Protocol for RDF using the PSGI | ||
| 16 | interface provided by L<Plack>. It may be run with any Plack handler. | ||
| 17 | See L<Plack::Handler> for more details. | ||
| 18 | |||
| 19 | When this module is used to create a SPARQL endpoint, configuration variables | ||
| 20 | are loaded using L<Config::ZOMG>. An example configuration file rdf_endpoint.json | ||
| 21 | is included with this package. Valid top-level configuration keys include: | ||
| 22 | |||
| 23 | =over 4 | ||
| 24 | |||
| 25 | =item store | ||
| 26 | |||
| 27 | This is used to define the underlying L<RDF::Trine::Store> for the | ||
| 28 | endpoint. It can be a hashref of the type that can be passed to | ||
| 29 | L<RDF::Trine::Store>->new_with_config, but a simple string can also be | ||
| 30 | used. | ||
| 31 | |||
| 32 | =item endpoint | ||
| 33 | |||
| 34 | A hash of endpoint-specific configuration variables. Valid keys for this hash | ||
| 35 | include: | ||
| 36 | |||
| 37 | =over 8 | ||
| 38 | |||
| 39 | =item update | ||
| 40 | |||
| 41 | A boolean value indicating whether Update operations should be allowed to be | ||
| 42 | executed by the endpoint. | ||
| 43 | |||
| 44 | =item load_data | ||
| 45 | |||
| 46 | A boolean value indicating whether the endpoint should use URLs that appear in | ||
| 47 | FROM and FROM NAMED clauses to construct a SPARQL dataset by dereferencing the | ||
| 48 | URLs and loading the retrieved RDF content. | ||
| 49 | |||
| 50 | =item service_description | ||
| 51 | |||
| 52 | An associative array (hash) containing details on which and how much information | ||
| 53 | to include in the service description provided by the endpoint if no query is | ||
| 54 | included for execution. The boolean values 'default' and 'named_graphs' indicate | ||
| 55 | that the respective SPARQL dataset graphs should be described by the service | ||
| 56 | description. | ||
| 57 | |||
| 58 | =item html | ||
| 59 | |||
| 60 | An associative array (hash) containing details on how results should be | ||
| 61 | serialized when the output media type is HTML. The boolean value 'resource_links' | ||
| 62 | specifies whether URI values should be serialized as HTML anchors (links). | ||
| 63 | The boolean value 'embed_images' specifies whether URI values that are typed as | ||
| 64 | foaf:Image should be serialized as HTML images. If 'embed_images' is true, the | ||
| 65 | integer value 'image_width' specifies the image width to be used in the HTML | ||
| 66 | markup (letting the image height scale appropriately). | ||
| 67 | |||
| 68 | =back | ||
| 69 | |||
| 70 | =back | ||
| 71 | |||
| 72 | =head1 EXAMPLE CONFIGURATIONS | ||
| 73 | |||
| 74 | =head2 Using L<Plack::Handler::Apache2> | ||
| 75 | |||
| 76 | Using L<Plack::Handler::Apache2>, mod_perl2 can be configured to serve and | ||
| 77 | endpoint using the following configuration: | ||
| 78 | |||
| 79 | <Location /sparql> | ||
| 80 | SetHandler perl-script | ||
| 81 | PerlResponseHandler Plack::Handler::Apache2 | ||
| 82 | PerlSetVar psgi_app /path/to/endpoint.psgi | ||
| 83 | PerlSetEnv RDF_ENDPOINT_CONFIG /path/to/rdf_endpoint.json | ||
| 84 | </Location> | ||
| 85 | |||
| 86 | To get syntax highlighting and other pretty features, in the | ||
| 87 | VirtualHost section of your server, add three aliases: | ||
| 88 | |||
| 89 | Alias /js/ /path/to/share/www/js/ | ||
| 90 | Alias /favicon.ico /path/to/share/www/favicon.ico | ||
| 91 | Alias /css/ /path/to/share/www/css/ | ||
| 92 | |||
| 93 | The exact location can be determined by finding where the file C<sparql_form.js>. | ||
| 94 | |||
| 95 | =head1 METHODS | ||
| 96 | |||
| 97 | =over 4 | ||
| 98 | |||
| 99 | =cut | ||
| 100 | |||
| 101 | package RDF::Endpoint; | ||
| 102 | |||
| 103 | 4 | ▶ | use 5.008; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 104 | 4 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 105 | 4 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 106 | our $VERSION = '0.11'; | ||
| 107 | |||
| 108 | 4 | ▶ | use RDF::Query 2.905; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 109 | 4 | ▶ | use RDF::Trine 0.134 qw(statement iri blank literal); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 110 | |||
| 111 | 4 | ▶ | use JSON; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 112 | 4 | ▶ | use Encode; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 113 | 4 | ▶ | use File::Spec; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 114 | 4 | ▶ | use Data::Dumper; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 115 | 4 | ▶ | use Digest::MD5 qw(md5_base64); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 116 | 4 | ▶ | use XML::LibXML 1.70; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 117 | 4 | ▶ | use Plack::Request; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 118 | 4 | ▶ | use Plack::Response; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 119 | 4 | ▶ | use Scalar::Util qw(blessed refaddr); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 120 | 4 | ▶ | use File::ShareDir qw(dist_dir); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 121 | 4 | ▶ | use HTTP::Negotiate qw(choose); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 122 | 4 | ▶ | use RDF::Trine::Namespace qw(rdf xsd); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 123 | 0 | ▶ | use RDF::RDFa::Generator 0.200; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 124 | use RDF::TrineX::Compatibility::Attean; | ||
| 125 | use IO::Compress::Gzip qw(gzip); | ||
| 126 | use HTML::HTML5::Writer qw(DOCTYPE_XHTML_RDFA); | ||
| 127 | use Hash::Merge::Simple qw/ merge /; | ||
| 128 | use Fcntl qw(:flock SEEK_END); | ||
| 129 | use Carp qw(croak); | ||
| 130 | |||
| 131 | |||
| 132 | my $NAMESPACES = { | ||
| 133 | xsd => 'http://www.w3.org/2001/XMLSchema#', | ||
| 134 | 'format' => 'http://www.w3.org/ns/formats/', | ||
| 135 | void => 'http://rdfs.org/ns/void#', | ||
| 136 | scovo => 'http://purl.org/NET/scovo#', | ||
| 137 | sd => 'http://www.w3.org/ns/sparql-service-description#', | ||
| 138 | jena => 'java:com.hp.hpl.jena.query.function.library.', | ||
| 139 | arq => 'http://jena.hpl.hp.com/ARQ/function#', | ||
| 140 | ldodds => 'java:com.ldodds.sparql.', | ||
| 141 | fn => 'http://www.w3.org/2005/xpath-functions#', | ||
| 142 | sparql => 'http://www.w3.org/ns/sparql#', | ||
| 143 | vann => 'http://purl.org/vocab/vann/', | ||
| 144 | sde => 'http://kasei.us/ns/service-description-extension#', | ||
| 145 | }; | ||
| 146 | |||
| 147 | =item C<< new ( \%conf ) >> | ||
| 148 | |||
| 149 | =item C<< new ( $model, \%conf ) >> | ||
| 150 | |||
| 151 | Returns a new Endpoint object. C<< \%conf >> should be a HASH reference with | ||
| 152 | configuration settings. | ||
| 153 | |||
| 154 | =cut | ||
| 155 | |||
| 156 | sub new { | ||
| 157 | my $class = shift; | ||
| 158 | my $arg = shift; | ||
| 159 | my ($model, $config); | ||
| 160 | if (blessed($arg) and $arg->isa('RDF::Trine::Model')) { | ||
| 161 | $model = $arg; | ||
| 162 | $config = shift; | ||
| 163 | delete $config->{store}; | ||
| 164 | } else { | ||
| 165 | $config = $arg; | ||
| 166 | my $store = RDF::Trine::Store->new( $config->{store} ); | ||
| 167 | unless ($store) { | ||
| 168 | warn "Failed to construct RDF Store object"; | ||
| 169 | return; | ||
| 170 | } | ||
| 171 | $model = RDF::Trine::Model->new( $store ); | ||
| 172 | unless ($model) { | ||
| 173 | warn "Failed to construct RDF Model object"; | ||
| 174 | return; | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | unless ($config->{endpoint}) { | ||
| 179 | $config->{endpoint} = { %$config }; | ||
| 180 | } | ||
| 181 | |||
| 182 | if ($config->{endpoint}{load_data} and $config->{endpoint}{update}) { | ||
| 183 | die "The load_data and update configuration options cannot be specified together."; | ||
| 184 | } | ||
| 185 | |||
| 186 | my $self = bless( { | ||
| 187 | conf => $config, | ||
| 188 | model => $model, | ||
| 189 | start_time => time, | ||
| 190 | }, $class ); | ||
| 191 | $self->service_description(); # pre-generate the service description | ||
| 192 | return $self; | ||
| 193 | } | ||
| 194 | |||
| 195 | =item C<< run ( $req ) >> | ||
| 196 | |||
| 197 | Handles the request specified by the supplied Plack::Request object, returning | ||
| 198 | an appropriate Plack::Response object. | ||
| 199 | |||
| 200 | =cut | ||
| 201 | |||
| 202 | sub run { | ||
| 203 | my $self = shift; | ||
| 204 | my $req = shift; | ||
| 205 | |||
| 206 | my $config = $self->{conf}; | ||
| 207 | my $endpoint_path = $config->{endpoint}{endpoint_path} || '/sparql'; | ||
| 208 | $config->{resource_links} = 1 unless (exists $config->{resource_links}); | ||
| 209 | my $model = $self->{model}; | ||
| 210 | |||
| 211 | my $content; | ||
| 212 | my $response = Plack::Response->new; | ||
| 213 | |||
| 214 | my $server = "RDF::Endpoint/$VERSION"; | ||
| 215 | $server .= " " . $response->headers->header('Server') if defined($response->headers->header('Server')); | ||
| 216 | $response->headers->header('Server' => $server); | ||
| 217 | |||
| 218 | unless ($req->path eq $endpoint_path) { | ||
| 219 | my $path = $req->path_info; | ||
| 220 | $path =~ s#^/##; | ||
| 221 | my $dir = $ENV{RDF_ENDPOINT_SHAREDIR} || eval { dist_dir('RDF-Endpoint') } || 'share'; | ||
| 222 | my $file = File::Spec->catfile($dir, 'www', $path); | ||
| 223 | if (-r $file) { | ||
| 224 | open( my $fh, '<', $file ) or croak $!; | ||
| 225 | $response->status(200); | ||
| 226 | $content = $fh; | ||
| 227 | } else { | ||
| 228 | my $path = $req->path; | ||
| 229 | $response->status(404); | ||
| 230 | $content = <<"END"; | ||
| 231 | <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>404 Not Found</title>\n</head><body>\n | ||
| 232 | <h1>Not Found</h1>\n<p>The requested URL $path was not found on this server.</p>\n</body></html> | ||
| 233 | END | ||
| 234 | } | ||
| 235 | $response->body($content); | ||
| 236 | return $response; | ||
| 237 | } | ||
| 238 | |||
| 239 | my $headers = $req->headers; | ||
| 240 | my $type = $headers->header('Accept') || 'application/sparql-results+xml'; | ||
| 241 | if (my $t = $req->param('media-type')) { | ||
| 242 | $type = $t; | ||
| 243 | $headers->header('Accept' => $type); | ||
| 244 | } | ||
| 245 | |||
| 246 | my $ae = $req->headers->header('Accept-Encoding') || ''; | ||
| 247 | |||
| 248 | my $sparql; | ||
| 249 | my $ct = $req->header('Content-type'); | ||
| 250 | if ($req->method !~ /^(GET|POST)$/i) { | ||
| 251 | my $method = uc($req->method); | ||
| 252 | $content = "Unexpected method $method (expecting GET or POST)"; | ||
| 253 | $self->log_error( $req, $content ); | ||
| 254 | $self->_set_response_error($req, $response, 405, { | ||
| 255 | title => 'Method not allowed', | ||
| 256 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/bad_http_method', | ||
| 257 | }); | ||
| 258 | $response->header('Allow' => 'GET, POST'); | ||
| 259 | goto CLEANUP; | ||
| 260 | } elsif (defined($ct) and $ct eq 'application/sparql-query') { | ||
| 261 | $sparql = $req->content; | ||
| 262 | } elsif (defined($ct) and $ct eq 'application/sparql-update') { | ||
| 263 | if ($config->{endpoint}{update} and $req->method eq 'POST') { | ||
| 264 | $sparql = $req->content; | ||
| 265 | } | ||
| 266 | } elsif ($req->param('query')) { | ||
| 267 | my @sparql = $req->param('query'); | ||
| 268 | if (scalar(@sparql) > 1) { | ||
| 269 | $content = "More than one query string submitted"; | ||
| 270 | $self->log_error( $req, $content ); | ||
| 271 | $self->_set_response_error($req, $response, 400, { | ||
| 272 | title => 'Multiple query strings not allowed', | ||
| 273 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/multiple_queries', | ||
| 274 | }); | ||
| 275 | goto CLEANUP; | ||
| 276 | } else { | ||
| 277 | $sparql = $sparql[0]; | ||
| 278 | } | ||
| 279 | } elsif ($req->param('update')) { | ||
| 280 | my @sparql = $req->param('update'); | ||
| 281 | if (scalar(@sparql) > 1) { | ||
| 282 | $content = "More than one update string submitted"; | ||
| 283 | $self->log_error( $req, $content ); | ||
| 284 | $self->_set_response_error($req, $response, 400, { | ||
| 285 | title => 'Multiple update strings not allowed', | ||
| 286 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/multiple_updates', | ||
| 287 | }); | ||
| 288 | goto CLEANUP; | ||
| 289 | } | ||
| 290 | |||
| 291 | if ($config->{endpoint}{update} and $req->method eq 'POST') { | ||
| 292 | $sparql = $sparql[0]; | ||
| 293 | } elsif ($req->method ne 'POST') { | ||
| 294 | my $method = $req->method; | ||
| 295 | $content = "Update operations must use POST"; | ||
| 296 | $self->log_error( $req, $content ); | ||
| 297 | $self->_set_response_error($req, $response, 405, { | ||
| 298 | title => "$method Not Allowed for Update Operation", | ||
| 299 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/bad_http_method_update', | ||
| 300 | }); | ||
| 301 | $response->header('Allow' => 'POST'); | ||
| 302 | goto CLEANUP; | ||
| 303 | } | ||
| 304 | } | ||
| 305 | |||
| 306 | my $ns = merge $config->{namespaces}, $NAMESPACES; | ||
| 307 | |||
| 308 | if ($sparql) { | ||
| 309 | my %args; | ||
| 310 | $args{ update } = 1 if ($config->{endpoint}{update} and $req->method eq 'POST'); | ||
| 311 | $args{ load_data } = 1 if ($config->{endpoint}{load_data}); | ||
| 312 | |||
| 313 | { | ||
| 314 | my @default = $req->param('default-graph-uri'); | ||
| 315 | my @named = $req->param('named-graph-uri'); | ||
| 316 | if (scalar(@default) or scalar(@named)) { | ||
| 317 | delete $args{ load_data }; | ||
| 318 | $model = RDF::Trine::Model->new( RDF::Trine::Store::Memory->new() ); | ||
| 319 | foreach my $url (@named) { | ||
| 320 | RDF::Trine::Parser->parse_url_into_model( $url, $model, context => iri($url) ); | ||
| 321 | } | ||
| 322 | foreach my $url (@default) { | ||
| 323 | RDF::Trine::Parser->parse_url_into_model( $url, $model ); | ||
| 324 | } | ||
| 325 | } | ||
| 326 | } | ||
| 327 | |||
| 328 | my $protocol_specifies_update_dataset = 0; | ||
| 329 | { | ||
| 330 | my @default = $req->param('using-graph-uri'); | ||
| 331 | my @named = $req->param('using-named-graph-uri'); | ||
| 332 | if (scalar(@named) or scalar(@default)) { | ||
| 333 | $protocol_specifies_update_dataset = 1; | ||
| 334 | $model = RDF::Trine::Model::Dataset->new( $model ); | ||
| 335 | $model->push_dataset( default => \@default, named => \@named ); | ||
| 336 | } | ||
| 337 | } | ||
| 338 | |||
| 339 | my $match = $headers->header('if-none-match') || ''; | ||
| 340 | my $etag = md5_base64( join('#', $self->run_tag, $model->etag, $type, $ae, $sparql) ); | ||
| 341 | if (length($match)) { | ||
| 342 | if (defined($etag) and ($etag eq $match)) { | ||
| 343 | $response->status(304); | ||
| 344 | return $response; | ||
| 345 | } | ||
| 346 | } | ||
| 347 | |||
| 348 | my $base = $req->base; | ||
| 349 | my $query = RDF::Query->new( $sparql, { lang => 'sparql11', base => $base, %args } ); | ||
| 350 | $self->log_query( $req, $sparql ); | ||
| 351 | if ($query) { | ||
| 352 | if ($protocol_specifies_update_dataset and $query->specifies_update_dataset) { | ||
| 353 | my $method = $req->method; | ||
| 354 | $content = "Update operations cannot specify a dataset in both the query and with protocol parameters"; | ||
| 355 | $self->log_error( $req, $content ); | ||
| 356 | $self->_set_response_error($req, $response, 400, { | ||
| 357 | title => "Multiple datasets specified for update", | ||
| 358 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/update_specifies_multiple_datasets', | ||
| 359 | detail => $content, | ||
| 360 | }); | ||
| 361 | goto CLEANUP; | ||
| 362 | } | ||
| 363 | my ($plan, $ctx) = $query->prepare( $model ); | ||
| 364 | # warn $plan->sse; | ||
| 365 | my $iter = $query->execute_plan( $plan, $ctx ); | ||
| 366 | if ($iter) { | ||
| 367 | $response->status(200); | ||
| 368 | if (defined($etag)) { | ||
| 369 | if ($etag !~ /"/) { | ||
| 370 | $etag = qq["$etag"]; | ||
| 371 | } | ||
| 372 | if ($etag =~ qr[^(W/)?"[\x{21}\x{23}-\x{7e}\x{80}-\x{FF}]*"$]) { | ||
| 373 | $response->headers->header( ETag => $etag ); | ||
| 374 | } else { | ||
| 375 | warn "ETag value is not syntactically valid: " . Dumper($etag); | ||
| 376 | } | ||
| 377 | } | ||
| 378 | if ($iter->isa('RDF::Trine::Iterator::Graph')) { | ||
| 379 | my @variants = (['text/html', 0.99, 'text/html']); | ||
| 380 | my %media_types = %RDF::Trine::Serializer::media_types; | ||
| 381 | while (my($type, $sclass) = each(%media_types)) { | ||
| 382 | next if ($type =~ /html/); | ||
| 383 | my $value = ($type =~ m#application/rdf[+]xml#) ? 1.00 : 0.98; | ||
| 384 | push(@variants, [$type, $value, $type]); | ||
| 385 | } | ||
| 386 | my $stype = choose( \@variants, $headers ); | ||
| 387 | if ($stype !~ /html/ and my $sclass = $RDF::Trine::Serializer::media_types{ $stype }) { | ||
| 388 | my $s = $sclass->new( namespaces => $ns ); | ||
| 389 | $response->status(200); | ||
| 390 | $response->headers->content_type($stype); | ||
| 391 | $content = encode_utf8($s->serialize_iterator_to_string($iter)); | ||
| 392 | } else { | ||
| 393 | $response->headers->content_type( 'text/html' ); | ||
| 394 | my $html = $self->iter_as_html($iter, $model); | ||
| 395 | $content = encode_utf8($html); | ||
| 396 | } | ||
| 397 | } else { | ||
| 398 | my @variants = ( | ||
| 399 | ['text/html', 0.99, 'text/html'], | ||
| 400 | ['application/sparql-results+xml', 1.0, 'application/sparql-results+xml'], | ||
| 401 | ['application/json', 0.95, 'application/json'], | ||
| 402 | ['application/rdf+xml', 0.95, 'application/rdf+xml'], | ||
| 403 | ['text/turtle', 0.95, 'text/turtle'], | ||
| 404 | ['text/xml', 0.8, 'text/xml'], | ||
| 405 | ['application/xml', 0.4, 'application/xml'], | ||
| 406 | ['text/plain', 0.2, 'text/plain'], | ||
| 407 | ); | ||
| 408 | my $stype = choose( \@variants, $headers ) || 'application/sparql-results+xml'; | ||
| 409 | if ($stype =~ /html/) { | ||
| 410 | $response->headers->content_type( 'text/html' ); | ||
| 411 | my $html = $self->iter_as_html($iter, $model, $sparql); | ||
| 412 | $content = encode_utf8($html); | ||
| 413 | } elsif ($stype =~ /xml/) { | ||
| 414 | $response->headers->content_type( $stype ); | ||
| 415 | my $xml = $self->iter_as_xml($iter, $model); | ||
| 416 | $content = encode_utf8($xml); | ||
| 417 | } elsif ($stype =~ /json/) { | ||
| 418 | $response->headers->content_type( $stype ); | ||
| 419 | my $json = $self->iter_as_json($iter, $model); | ||
| 420 | $content = encode_utf8($json); | ||
| 421 | } else { | ||
| 422 | $response->headers->content_type( 'text/plain' ); | ||
| 423 | my $text = $self->iter_as_text($iter, $model); | ||
| 424 | $content = encode_utf8($text); | ||
| 425 | } | ||
| 426 | } | ||
| 427 | } else { | ||
| 428 | my $error = $query->error; | ||
| 429 | $self->_set_response_error($req, $response, 500, { | ||
| 430 | title => "SPARQL query/update execution error", | ||
| 431 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/execution_error', | ||
| 432 | detail => "$error; $sparql", | ||
| 433 | }); | ||
| 434 | $content = RDF::Query->error; | ||
| 435 | } | ||
| 436 | } else { | ||
| 437 | $content = RDF::Query->error; | ||
| 438 | $self->log_error( $req, $content ); | ||
| 439 | my $code = ($content =~ /Syntax/) ? 400 : 500; | ||
| 440 | if ($req->method ne 'POST' and $content =~ /read-only queries/sm) { | ||
| 441 | $content = 'Updates must use a HTTP POST request.'; | ||
| 442 | $self->_set_response_error($req, $response, $code, { | ||
| 443 | title => $content, | ||
| 444 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/bad_http_method_update', | ||
| 445 | }); | ||
| 446 | } else { | ||
| 447 | $self->_set_response_error($req, $response, $code, { | ||
| 448 | title => "SPARQL query/update parse error", | ||
| 449 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/parse_error', | ||
| 450 | detail => $content, | ||
| 451 | }); | ||
| 452 | } | ||
| 453 | } | ||
| 454 | } elsif ($req->method eq 'POST') { | ||
| 455 | $content = "POST without recognized query or update"; | ||
| 456 | $self->log_error( $req, $content ); | ||
| 457 | $self->_set_response_error($req, $response, 400, { | ||
| 458 | title => "Missing SPARQL Query/Update String", | ||
| 459 | describedby => 'http://id.kasei.us/perl/rdf-endpoint/error/missing_sparql_string', | ||
| 460 | }); | ||
| 461 | } else { | ||
| 462 | my @variants; | ||
| 463 | my %media_types = %RDF::Trine::Serializer::media_types; | ||
| 464 | while (my($type, $sclass) = each(%media_types)) { | ||
| 465 | next if ($type =~ /html/); | ||
| 466 | push(@variants, [$type, 0.99, $type]); | ||
| 467 | } | ||
| 468 | push(@variants, ['text/html', 1.0, 'text/html']); | ||
| 469 | my $stype = choose( \@variants, $headers ); | ||
| 470 | my $sdmodel = $self->service_description(); | ||
| 471 | if ($stype !~ /html/ and my $sclass = $RDF::Trine::Serializer::media_types{ $stype }) { | ||
| 472 | my $s = $sclass->new( namespaces => $ns ); | ||
| 473 | $response->status(200); | ||
| 474 | $response->headers->content_type($stype); | ||
| 475 | $content = encode_utf8($s->serialize_model_to_string($sdmodel)); | ||
| 476 | } else { | ||
| 477 | my $dir = $ENV{RDF_ENDPOINT_SHAREDIR} || eval { dist_dir('RDF-Endpoint') } || 'share'; | ||
| 478 | my $template = File::Spec->catfile($dir, 'index.html'); | ||
| 479 | my $parser = XML::LibXML->new(validation => 0, suppress_errors => 1, no_network => 1, recover => 2) ; | ||
| 480 | my $doc = $parser->parse_file( $template ); | ||
| 481 | my $gen = RDF::RDFa::Generator->new( style => 'HTML::Head', namespaces => { %$ns } ); | ||
| 482 | $gen->inject_document($doc, $sdmodel); | ||
| 483 | |||
| 484 | my $writer = HTML::HTML5::Writer->new( markup => 'xhtml', doctype => DOCTYPE_XHTML_RDFA ); | ||
| 485 | $content = encode_utf8( $writer->document($doc) ); | ||
| 486 | $response->status(200); | ||
| 487 | $response->headers->content_type('text/html'); | ||
| 488 | } | ||
| 489 | } | ||
| 490 | |||
| 491 | CLEANUP: | ||
| 492 | # warn Dumper($model); | ||
| 493 | # warn $model->as_string; | ||
| 494 | $content = $response->body || $content; | ||
| 495 | my $length = 0; | ||
| 496 | my %ae = map { $_ => 1 } split(/\s*,\s*/, $ae); | ||
| 497 | if ($ae{'gzip'}) { | ||
| 498 | my ($rh, $wh); | ||
| 499 | pipe($rh, $wh); | ||
| 500 | if (ref($content)) { | ||
| 501 | gzip $content => $wh; | ||
| 502 | } else { | ||
| 503 | gzip \$content => $wh; | ||
| 504 | } | ||
| 505 | close($wh); | ||
| 506 | local($/) = undef; | ||
| 507 | my $body = <$rh>; | ||
| 508 | $length = bytes::length($body); | ||
| 509 | $response->headers->header('Content-Encoding' => 'gzip'); | ||
| 510 | $response->headers->header('Content-Length' => $length); | ||
| 511 | $response->body( $body ) unless ($req->method eq 'HEAD'); | ||
| 512 | } else { | ||
| 513 | local($/) = undef; | ||
| 514 | my $body = ref($content) ? <$content> : $content; | ||
| 515 | $length = bytes::length($body); | ||
| 516 | $response->headers->header('Content-Length' => $length); | ||
| 517 | $response->body( $body ) unless ($req->method eq 'HEAD'); | ||
| 518 | } | ||
| 519 | return $response; | ||
| 520 | } | ||
| 521 | |||
| 522 | =item C<< run_tag >> | ||
| 523 | |||
| 524 | Returns a unique key for each instantiation of this service. | ||
| 525 | |||
| 526 | =cut | ||
| 527 | |||
| 528 | sub run_tag { | ||
| 529 | my $self = shift; | ||
| 530 | return md5_base64(refaddr($self) . $self->{start_time}); | ||
| 531 | } | ||
| 532 | |||
| 533 | =item C<< service_description ( $request, $model ) >> | ||
| 534 | |||
| 535 | Returns a new RDF::Trine::Model object containing a service description of this | ||
| 536 | endpoint, generating dataset statistics from C<< $model >>. | ||
| 537 | |||
| 538 | =cut | ||
| 539 | |||
| 540 | sub service_description { | ||
| 541 | my $self = shift; | ||
| 542 | my $model = $self->{model}; | ||
| 543 | my $etag = $model->etag || ''; | ||
| 544 | |||
| 545 | if (exists $self->{ sd_cache }) { | ||
| 546 | my ($cached_etag, $model) = @{ $self->{ sd_cache } }; | ||
| 547 | if (defined($cached_etag) and $etag eq $cached_etag) { | ||
| 548 | return $model; | ||
| 549 | } | ||
| 550 | } | ||
| 551 | |||
| 552 | my $config = $self->{conf}; | ||
| 553 | my $doap = RDF::Trine::Namespace->new('http://usefulinc.com/ns/doap#'); | ||
| 554 | my $sd = RDF::Trine::Namespace->new('http://www.w3.org/ns/sparql-service-description#'); | ||
| 555 | my $sde = RDF::Trine::Namespace->new('http://kasei.us/ns/service-description-extension#'); | ||
| 556 | my $vann = RDF::Trine::Namespace->new('http://purl.org/vocab/vann/'); | ||
| 557 | my $void = RDF::Trine::Namespace->new('http://rdfs.org/ns/void#'); | ||
| 558 | my $scovo = RDF::Trine::Namespace->new('http://purl.org/NET/scovo#'); | ||
| 559 | my $count = $model->count_statements( undef, undef, undef, RDF::Trine::Node::Nil->new ); | ||
| 560 | |||
| 561 | my @extensions = grep { !/kasei[.]us/ } RDF::Query->supported_extensions; | ||
| 562 | my @functions = grep { !/kasei[.]us/ } RDF::Query->supported_functions; | ||
| 563 | my @formats = keys %RDF::Trine::Serializer::format_uris; | ||
| 564 | |||
| 565 | my $sdmodel = RDF::Trine::Model->temporary_model; | ||
| 566 | my $s = blank('service'); | ||
| 567 | $sdmodel->add_statement( statement( $s, $rdf->type, $sd->Service ) ); | ||
| 568 | |||
| 569 | $sdmodel->add_statement( statement( $s, $sd->supportedLanguage, $sd->SPARQL11Query ) ); | ||
| 570 | if ($config->{endpoint}{update}) { | ||
| 571 | $sdmodel->add_statement( statement( $s, $sd->supportedLanguage, $sd->SPARQL11Update ) ); | ||
| 572 | } | ||
| 573 | if ($config->{endpoint}{load_data}) { | ||
| 574 | $sdmodel->add_statement( statement( $s, $sd->feature, $sd->DereferencesURIs ) ); | ||
| 575 | } | ||
| 576 | |||
| 577 | foreach my $ext (@extensions) { | ||
| 578 | $sdmodel->add_statement( statement( $s, $sd->languageExtension, iri($ext) ) ); | ||
| 579 | } | ||
| 580 | foreach my $func (@functions) { | ||
| 581 | $sdmodel->add_statement( statement( $s, $sd->extensionFunction, iri($func) ) ); | ||
| 582 | } | ||
| 583 | |||
| 584 | $sdmodel->add_statement( statement( $s, $sd->resultFormat, iri('http://www.w3.org/ns/formats/SPARQL_Results_XML') ) ); | ||
| 585 | $sdmodel->add_statement( statement( $s, $sd->resultFormat, iri('http://www.w3.org/ns/formats/SPARQL_Results_JSON') ) ); | ||
| 586 | foreach my $format (@formats) { | ||
| 587 | $sdmodel->add_statement( statement( $s, $sd->resultFormat, iri($format) ) ); | ||
| 588 | } | ||
| 589 | |||
| 590 | my $dataset = blank('dataset'); | ||
| 591 | $sdmodel->add_statement( statement( $s, $sd->endpoint, iri('') ) ); | ||
| 592 | $sdmodel->add_statement( statement( $s, $sd->defaultDataset, $dataset ) ); | ||
| 593 | $sdmodel->add_statement( statement( $dataset, $rdf->type, $sd->Dataset ) ); | ||
| 594 | if (my $d = $config->{endpoint}{service_description}{default}) { | ||
| 595 | my $def_graph = ($d =~ /^\w+:/) ? iri($d) : blank('defaultGraph'); | ||
| 596 | $sdmodel->add_statement( statement( $dataset, $sd->defaultGraph, $def_graph ) ); | ||
| 597 | $sdmodel->add_statement( statement( $def_graph, $rdf->type, $sd->Graph ) ); | ||
| 598 | $sdmodel->add_statement( statement( $def_graph, $rdf->type, $void->Dataset ) ); | ||
| 599 | $sdmodel->add_statement( statement( $def_graph, $void->triples, literal( $count, undef, $xsd->integer ) ) ); | ||
| 600 | } | ||
| 601 | if ($config->{endpoint}{service_description}{named_graphs}) { | ||
| 602 | my $iter = $model->get_contexts; | ||
| 603 | while (my $g = $iter->next) { | ||
| 604 | my $ng = blank(); | ||
| 605 | my $graph = blank(); | ||
| 606 | my $count = $model->count_statements( undef, undef, undef, $g ); | ||
| 607 | $sdmodel->add_statement( statement( $dataset, $sd->namedGraph, $ng ) ); | ||
| 608 | $sdmodel->add_statement( statement( $ng, $sd->name, $g ) ); | ||
| 609 | $sdmodel->add_statement( statement( $ng, $sd->graph, $graph ) ); | ||
| 610 | $sdmodel->add_statement( statement( $graph, $rdf->type, $sd->Graph ) ); | ||
| 611 | $sdmodel->add_statement( statement( $graph, $rdf->type, $void->Dataset ) ); | ||
| 612 | $sdmodel->add_statement( statement( $graph, $void->triples, literal( $count, undef, $xsd->integer ) ) ); | ||
| 613 | } | ||
| 614 | } | ||
| 615 | |||
| 616 | if (my $software = $config->{endpoint}{service_description}{software}) { | ||
| 617 | $sdmodel->add_statement( statement( $s, $sde->software, iri($software) ) ); | ||
| 618 | } | ||
| 619 | |||
| 620 | if (my $related = $config->{endpoint}{service_description}{related}) { | ||
| 621 | foreach my $r (@$related) { | ||
| 622 | $sdmodel->add_statement( statement( $s, $sde->relatedEndpoint, iri($r) ) ); | ||
| 623 | } | ||
| 624 | } | ||
| 625 | |||
| 626 | if (my $namespaces = $config->{endpoint}{service_description}{namespaces}) { | ||
| 627 | while (my($ns,$uri) = each(%$namespaces)) { | ||
| 628 | my $b = RDF::Trine::Node::Blank->new(); | ||
| 629 | $sdmodel->add_statement( statement( $s, $sde->namespace, $b ) ); | ||
| 630 | $sdmodel->add_statement( statement( $b, $vann->preferredNamespacePrefix, literal($ns) ) ); | ||
| 631 | $sdmodel->add_statement( statement( $b, $vann->preferredNamespaceUri, literal($uri) ) ); | ||
| 632 | } | ||
| 633 | } | ||
| 634 | |||
| 635 | $self->{ sd_cache } = [ $etag, $sdmodel ]; | ||
| 636 | return $sdmodel; | ||
| 637 | } | ||
| 638 | |||
| 639 | =begin private | ||
| 640 | |||
| 641 | =item C<< iter_as_html ( $iter, $model ) >> | ||
| 642 | |||
| 643 | =cut | ||
| 644 | |||
| 645 | sub iter_as_html { | ||
| 646 | my $self = shift; | ||
| 647 | my $stream = shift; | ||
| 648 | my $model = shift; | ||
| 649 | my $query = shift; | ||
| 650 | |||
| 651 | my $dir = $ENV{RDF_ENDPOINT_SHAREDIR} || eval { dist_dir('RDF-Endpoint') } || 'share'; | ||
| 652 | my $file = File::Spec->catfile($dir, 'results.html'); | ||
| 653 | my $html; | ||
| 654 | |||
| 655 | if (-r $file) { | ||
| 656 | open( my $fh, '<', $file ) or croak $!; | ||
| 657 | $html = do { local $/; <$fh>; }; | ||
| 658 | close $fh; | ||
| 659 | } else { | ||
| 660 | $html = <<HTML | ||
| 661 | <html><head><title>SPARQL Results</title></head><body> | ||
| 662 | <div id="result" /> | ||
| 663 | <h2>Query</h2> | ||
| 664 | <form id="queryform" action="" method="get"> | ||
| 665 | <p><textarea id="query" name="query" rows="10" cols="60"></textarea> | ||
| 666 | <br/> | ||
| 667 | <select id="media-type" name="media-type"> | ||
| 668 | <option value="">Result Format...</option> | ||
| 669 | <option label="HTML" value="text/html">HTML</option> | ||
| 670 | <option label="Turtle" value="text/turtle">Turtle</option> | ||
| 671 | <option label="XML" value="text/xml">XML</option> | ||
| 672 | <option label="JSON" value="application/json">JSON</option> | ||
| 673 | </select> | ||
| 674 | <input name="submit" id="submit" type="submit" value="Submit" /> | ||
| 675 | </p> | ||
| 676 | </form> | ||
| 677 | </body></html> | ||
| 678 | HTML | ||
| 679 | } | ||
| 680 | |||
| 681 | my $result = "<h2>Result</h2>\n"; | ||
| 682 | |||
| 683 | if ($stream->isa('RDF::Trine::Iterator::Boolean')) { | ||
| 684 | $result = (($stream->get_boolean) ? "True" : "False"); | ||
| 685 | } elsif ($stream->isa('RDF::Trine::Iterator::Bindings')) { | ||
| 686 | $result = "<table class='tablesorter'>\n<thead><tr>\n"; | ||
| 687 | |||
| 688 | my @names = $stream->binding_names; | ||
| 689 | my $columns = scalar(@names); | ||
| 690 | foreach my $name (@names) { | ||
| 691 | $result .= "\t<th>" . $name . "</th>\n"; | ||
| 692 | } | ||
| 693 | $result .= "</tr></thead>\n"; | ||
| 694 | |||
| 695 | my $count = 0; | ||
| 696 | while (my $row = $stream->next) { | ||
| 697 | $count++; | ||
| 698 | $result .= "<tr>\n"; | ||
| 699 | foreach my $k (@names) { | ||
| 700 | my $node = $row->{ $k }; | ||
| 701 | my $value = $self->node_as_html($node, $model); | ||
| 702 | $result .= "\t<td>" . $value . "</td>\n"; | ||
| 703 | } | ||
| 704 | $result .= "</tr>\n"; | ||
| 705 | } | ||
| 706 | $result .= "<tfoot><tr><th colspan=\"$columns\">Total: $count</th></tr></tfoot>\n</table>\n"; | ||
| 707 | } | ||
| 708 | |||
| 709 | $html =~ s/<div\s+id\s*=\s*["']result["']\s*\/>/<div id="result">$result<\/div>/; | ||
| 710 | $html =~ s/(<textarea[^>]*>)(.|\n)*(<\/textarea>)/$1$query$3/sm; | ||
| 711 | |||
| 712 | return $html; | ||
| 713 | } | ||
| 714 | |||
| 715 | =item C<< iter_as_text ( $iter ) >> | ||
| 716 | |||
| 717 | =cut | ||
| 718 | |||
| 719 | sub iter_as_text { | ||
| 720 | my $self = shift; | ||
| 721 | my $iter = shift; | ||
| 722 | if ($iter->isa('RDF::Trine::Iterator::Graph')) { | ||
| 723 | my $serializer = RDF::Trine::Serializer->new('ntriples'); | ||
| 724 | return $serializer->serialize_iterator_to_string( $iter ); | ||
| 725 | } else { | ||
| 726 | return $iter->as_string; | ||
| 727 | } | ||
| 728 | } | ||
| 729 | |||
| 730 | =item C<< iter_as_xml ( $iter ) >> | ||
| 731 | |||
| 732 | =cut | ||
| 733 | |||
| 734 | sub iter_as_xml { | ||
| 735 | my $self = shift; | ||
| 736 | my $iter = shift; | ||
| 737 | return $iter->as_xml; | ||
| 738 | } | ||
| 739 | |||
| 740 | =item C<< iter_as_json ( $iter ) >> | ||
| 741 | |||
| 742 | =cut | ||
| 743 | |||
| 744 | sub iter_as_json { | ||
| 745 | my $self = shift; | ||
| 746 | my $iter = shift; | ||
| 747 | return $iter->as_json; | ||
| 748 | } | ||
| 749 | |||
| 750 | =item C<< node_as_html ( $node, $model ) >> | ||
| 751 | |||
| 752 | =cut | ||
| 753 | |||
| 754 | sub node_as_html { | ||
| 755 | my $self = shift; | ||
| 756 | my $node = shift; | ||
| 757 | my $model = shift; | ||
| 758 | my $config = $self->{conf}; | ||
| 759 | return '' unless (blessed($node)); | ||
| 760 | if ($node->isa('RDF::Trine::Node::Resource')) { | ||
| 761 | my $uri = $node->uri_value; | ||
| 762 | for ($uri) { | ||
| 763 | s/&/&/g; | ||
| 764 | s/</</g; | ||
| 765 | } | ||
| 766 | my $link = $config->{endpoint}{html}{resource_links}; | ||
| 767 | my $html; | ||
| 768 | if ($config->{endpoint}{html}{embed_images}) { | ||
| 769 | if ($model->count_statements( $node, iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), iri('http://xmlns.com/foaf/0.1/Image') )) { | ||
| 770 | my $width = $config->{endpoint}{html}{image_width} || 200; | ||
| 771 | $html = qq[<img src="${uri}" width="${width}" />]; | ||
| 772 | } else { | ||
| 773 | $html = $uri; | ||
| 774 | } | ||
| 775 | } else { | ||
| 776 | $html = $uri; | ||
| 777 | } | ||
| 778 | if ($link) { | ||
| 779 | $html = qq[<a href="${uri}">$html</a>]; | ||
| 780 | } | ||
| 781 | return $html; | ||
| 782 | } elsif ($node->isa('RDF::Trine::Node::Literal')) { | ||
| 783 | my $html = $node->literal_value; | ||
| 784 | for ($html) { | ||
| 785 | s/&/&/g; | ||
| 786 | s/</</g; | ||
| 787 | } | ||
| 788 | return $html; | ||
| 789 | } else { | ||
| 790 | my $html = $node->as_string; | ||
| 791 | for ($html) { | ||
| 792 | s/&/&/g; | ||
| 793 | s/</</g; | ||
| 794 | } | ||
| 795 | return $html; | ||
| 796 | } | ||
| 797 | } | ||
| 798 | |||
| 799 | =item C<< log_query ( $message ) >> | ||
| 800 | |||
| 801 | =cut | ||
| 802 | |||
| 803 | sub log_query { | ||
| 804 | my $self = shift; | ||
| 805 | my $req = shift; | ||
| 806 | my $message = shift; | ||
| 807 | $self->_log( $req, { level => 'info', message => $message } ); | ||
| 808 | } | ||
| 809 | |||
| 810 | =item C<< log_error ( $message ) >> | ||
| 811 | |||
| 812 | =cut | ||
| 813 | |||
| 814 | sub log_error { | ||
| 815 | my $self = shift; | ||
| 816 | my $req = shift; | ||
| 817 | my $message = shift; | ||
| 818 | $self->_log( $req, { level => 'error', message => $message } ); | ||
| 819 | } | ||
| 820 | |||
| 821 | sub _log { | ||
| 822 | my $self = shift; | ||
| 823 | my $req = shift; | ||
| 824 | my $data = shift; | ||
| 825 | my $logger = $req->logger || sub {}; | ||
| 826 | |||
| 827 | $logger->($data); | ||
| 828 | } | ||
| 829 | |||
| 830 | sub _set_response_error { | ||
| 831 | my $self = shift; | ||
| 832 | my $req = shift; | ||
| 833 | my $resp = shift; | ||
| 834 | my $code = shift; | ||
| 835 | my $error = shift; | ||
| 836 | my @variants = ( | ||
| 837 | ['text/plain', 1.0, 'text/plain'], | ||
| 838 | ['application/json-problem', 0.99, 'application/json-problem'], | ||
| 839 | ); | ||
| 840 | my $headers = $req->headers; | ||
| 841 | my $stype = choose( \@variants, $headers ) || 'text/plain'; | ||
| 842 | if ($stype eq 'application/json-problem') { | ||
| 843 | $resp->headers->content_type( 'application/json-problem' ); | ||
| 844 | $resp->status($code); | ||
| 845 | my $content = encode_json($error); | ||
| 846 | $resp->body($content); | ||
| 847 | } else { | ||
| 848 | $resp->headers->content_type( 'text/plain' ); | ||
| 849 | $resp->status($code); | ||
| 850 | my @messages = grep { defined($_) } @{ $error }{ qw(title detail) }; | ||
| 851 | my $content = join("\n\n", @messages); | ||
| 852 | $resp->body($content); | ||
| 853 | } | ||
| 854 | return; | ||
| 855 | } | ||
| 856 | |||
| 857 | =end private | ||
| 858 | |||
| 859 | =cut | ||
| 860 | |||
| 861 | 1; | ||
| 862 | |||
| 863 | __END__ | ||