File Coverage

blib/lib/RDF/LinkedData.pm
Criterion Covered Total %
statement 46 48 95.8
branch n/a
condition n/a
subroutine 16 16 100.0
pod n/a
total 62 64 96.8


line stmt bran cond sub pod time code
1             package RDF::LinkedData;
2              
3 8     8   4332734 use strict;
  8         20  
  8         341  
4 8     8   52 use warnings;
  8         18  
  8         262  
5 8     8   664 use Moo;
  8         15968  
  8         65  
6 8     8   20862 use namespace::autoclean;
  8         50129  
  8         40  
7 8     8   1312 use Types::Standard qw(InstanceOf Str Bool Maybe Int HashRef);
  8         117993  
  8         102  
8              
9 8     8   9573 use RDF::Trine qw[iri literal blank statement variable];
  8         2348130  
  8         534  
10 8     8   66 use RDF::Trine::Serializer;
  8         15  
  8         178  
11 8     8   38 use RDF::Trine::Iterator::Graph;
  8         13  
  8         310  
12 8     8   2436 use Plack::Response;
  8         27042  
  8         215  
13 8     8   2197 use RDF::Helper::Properties;
  8         181091  
  8         253  
14 8     8   2081 use URI::NamespaceMap;
  8         721086  
  8         280  
15 8     8   57 use URI;
  8         17  
  8         155  
16 8     8   42 use HTTP::Headers;
  8         17  
  8         290  
17 8     8   55 use Module::Load::Conditional qw[can_load];
  8         42  
  8         424  
18 8     8   42 use Encode;
  8         15  
  8         577  
19 8     8   2323 use RDF::RDFa::Generator 0.102;
  0            
  0            
20             use HTML::HTML5::Writer qw(DOCTYPE_XHTML_RDFA);
21             use Data::Dumper;
22             use Digest::MD5 ('md5_base64');
23             use Carp;
24             use Try::Tiny;
25             use List::Util qw(any);
26              
27             with 'MooX::Log::Any';
28              
29             =head1 NAME
30              
31             RDF::LinkedData - A Linked Data server implementation
32              
33             =head1 VERSION
34              
35             Version 0.99_02
36              
37             =cut
38              
39             our $VERSION = '0.99_02';
40              
41              
42             =head1 SYNOPSIS
43              
44             For just setting this up and get it to run, you would just use the
45             C<linked_data.psgi> script in this distribution. The usage of that is
46             documented in L<Plack::App::RDF::LinkedData>, with the README being a
47             quick start guide. If you want to try and use this directly, you'd do
48             stuff like:
49              
50             my $ld = RDF::LinkedData->new(store => $config->{store},
51             endpoint_config => $config->{endpoint},
52             base_uri => $config->{base_uri}
53             );
54             $ld->namespaces($config->{namespaces}) if ($config->{namespaces});
55             $ld->request($req);
56             return $ld->response($uri)->finalize;
57              
58             See L<Plack::App::RDF::LinkedData> for a complete example.
59              
60             =head1 DESCRIPTION
61              
62             This module is used to create a Linked Data server that can
63             serve RDF data out of an L<RDF::Trine::Model>. It will look up URIs in
64             the model and do the right thing (known as the 303 dance) and mint
65             URLs for that, as well as perform content negotiation. Thus, you can
66             concentrate on URIs for your things, and you need not be concerned about
67             minting URLs for the pages to serve it. In addition, optional modules
68             can provide other important functionality: Cross-origin resource
69             sharing, VoID description, cache headers, SPARQL Endpoint, Triple
70             Pattern Fragments, etc. As such, it encompasses a fair share of
71             Semantic Web best practices, but possibly not in a very flexible "Big
72             Data" manner.
73              
74              
75             =head1 METHODS
76              
77             =over
78              
79             =item C<< new ( store => $store, model => $model, base_uri => $base_uri,
80             hypermedia => 1, namespaces_as_vocabularies => 1,
81             request => $request, endpoint_config => $endpoint_config,
82             void_config => $void_config ) >>
83              
84             Creates a new handler object based on the named parameters, given a store
85             config (recommended usage is to pass a hashref of the type that can be
86             passed to L<RDF::Trine::Store>->new_with_config, but a simple string
87             can also be used) or a model and a base URI. Optionally, you may pass a
88             L<Plack::Request> object (which must be passed before you call C<content>)
89             and an C<endpoint_config> hashref if you want to have a SPARQL
90             Endpoint running using the recommended module L<RDF::Endpoint>.
91              
92             This module can also provide additional triples to turn the response
93             into a hypermedia type. If you don't want this, set the C<hypermedia>
94             argument to false. Currently this entails setting the SPARQL endpoint
95             and vocabularies used using the L<VoID vocabulary|http://vocab.deri.ie/void>.
96              
97             Finally, it can provide experimental L<Triple Pattern
98             Fragments|http://www.hydra-cg.com/spec/latest/triple-pattern-fragments/>
99             support.
100              
101             =item C<< BUILD >>
102              
103             Called by Moo to initialize an object.
104              
105             =cut
106              
107             sub BUILD {
108             my $self = shift;
109              
110             # A model will be passed or built by the _build_model, so we can check directly if we have one
111             unless ($self->model->isa('RDF::Trine::Model')) {
112             croak "No valid RDF::Trine::Model, need either a store config hashref or a model.";
113             }
114              
115             if ($self->has_endpoint_config) {
116             $self->log->debug('Endpoint config found with parameters: ' . Dumper($self->endpoint_config) );
117              
118             unless (can_load( modules => { 'RDF::Endpoint' => 0.03 })) {
119             croak "RDF::Endpoint not installed. Please install or remove its configuration.";
120             }
121              
122             unless (defined($self->endpoint_config->{endpoint_path})) {
123             $self->endpoint_config->{endpoint_path} = '/sparql';
124             }
125              
126             $self->endpoint(RDF::Endpoint->new($self->model, $self->endpoint_config));
127             } else {
128             $self->log->info('No endpoint config found');
129             }
130              
131             if ($self->has_void_config) {
132             $self->log->debug('VoID config found with parameters: ' . Dumper($self->void_config) );
133              
134             unless (can_load( modules => { 'RDF::Generator::Void' => 0.04 })) {
135             croak "RDF::Generator::Void not installed. Please install or remove its configuration.";
136             }
137             my $dataset_uri = (defined($self->void_config->{dataset_uri}))
138             ? $self->void_config->{dataset_uri}
139             : URI->new($self->base_uri . '#dataset-0')->canonical;
140             $self->_last_extvoid_mtime(0);
141             $self->void(RDF::Generator::Void->new(inmodel => $self->model,
142             dataset_uri => $dataset_uri,
143             namespaces_as_vocabularies => $self->void_config->{namespaces_as_vocabularies}));
144             if ($self->has_fragments) {
145             $self->log->debug('Triple Pattern Fragments config found with parameters: ' . Dumper($self->fragments_config) );
146             }
147             } else {
148             $self->log->info('No VoID config found');
149             }
150             }
151              
152             =item C<< BUILDARGS >>
153              
154             Called by Moo to ensure that some attributes can be left unset.
155              
156             =cut
157              
158             around BUILDARGS => sub
159             {
160             my ($next, $self) = (shift, shift);
161             my $args = $self->$next(@_);
162             for (keys %$args) {
163             delete $args->{$_} if not defined $args->{$_};
164             }
165             return $args;
166             };
167              
168             has store => (is => 'rw', isa => HashRef | Str );
169              
170              
171             =item C<< model >>
172              
173             Returns the RDF::Trine::Model object.
174              
175             =cut
176              
177             has model => (is => 'ro', isa => InstanceOf['RDF::Trine::Model'], lazy => 1, builder => '_build_model',
178             handles => { current_etag => 'etag' });
179              
180             sub _build_model {
181             my $self = shift;
182             return $self->_load_model($self->store);
183             }
184              
185             sub _load_model {
186             my ($self, $store_config) = @_;
187             # First, set the base if none is configured
188             my $i = 0;
189             if (ref($store_config) eq 'HASH') {
190             foreach my $source (@{$store_config->{sources}}) {
191             unless ($source->{base_uri}) {
192             ${$store_config->{sources}}[$i]->{base_uri} = $self->base_uri;
193             }
194             $i++;
195             }
196             }
197             my $store = RDF::Trine::Store->new( $store_config );
198             return RDF::Trine::Model->new( $store );
199             }
200              
201              
202             =item C<< base_uri >>
203              
204             Returns or sets the base URI for this handler.
205              
206             =cut
207              
208             has base_uri => (is => 'rw', isa => Str, default => '' );
209              
210             has hypermedia => (is => 'ro', isa => Bool, default => 1);
211              
212             has namespaces_as_vocabularies => (is => 'ro', isa => Bool, default => 1);
213              
214             has endpoint_config => (is => 'rw', isa=>Maybe[HashRef], predicate => 'has_endpoint_config');
215              
216             has void_config => (is => 'rw', isa=>Maybe[HashRef], predicate => 'has_void_config');
217              
218             has fragments_config => (is => 'rw', isa=>Maybe[HashRef], predicate => 'has_fragments');
219              
220              
221              
222             =item C<< request ( [ $request ] ) >>
223              
224             Returns the L<Plack::Request> object, if it exists; or sets it if a L<Plack::Request> object is given as parameter.
225              
226             =cut
227              
228             has request => ( is => 'rw', isa => InstanceOf['Plack::Request']);
229              
230              
231             =item C<< current_etag >>
232              
233             Returns the current Etag of the model suitable for use in a HTTP header. This is a read-only attribute.
234              
235             =item C<< last_etag >>, C<< has_last_etag >>
236              
237             Returns or sets the last Etag of so that changes to the model can be detected.
238              
239             =cut
240              
241             has last_etag => ( is => 'rw', isa => Str, predicate => 'has_last_etag');
242              
243              
244             =item namespaces ( $namespace_map )
245              
246             Gets or sets the namespaces that some serializers use for
247             pretty-printing. Should be handed a L<URI::NamespaceMap> object.
248              
249             =cut
250              
251             has 'namespaces' => (is => 'rw',
252             isa => InstanceOf['URI::NamespaceMap'],
253             builder => '_build_namespaces',
254             lazy => 1,
255             handles => {
256             'add_namespace_mapping' => 'add_mapping',
257             'guess_namespaces' => 'guess_and_add',
258             'list_namespaces' => 'list_namespaces'
259             });
260              
261              
262             sub _build_namespaces {
263             my $self = shift;
264             return shift || URI::NamespaceMap->new();
265             }
266              
267             # Just a temporary compatibility hack
268             sub _namespace_hashref {
269             my $self = shift;
270             my %hash;
271             foreach my $prefix ($self->namespaces->list_prefixes) {
272             $hash{$prefix} = $self->namespaces->namespace_uri($prefix)->as_string;
273             }
274             return \%hash;
275             }
276              
277            
278              
279              
280             =item C<< response ( $uri ) >>
281              
282             Will look up what to do with the given URI object and populate the
283             response object.
284              
285             =cut
286              
287             sub response {
288             my $self = shift;
289             my $uri = URI->new(shift);
290             my $response = Plack::Response->new;
291              
292             my $headers_in = $self->request->headers;
293              
294             my $server = "RDF::LinkedData/$VERSION";
295             $server .= " " . $response->headers->header('Server') if defined($response->headers->header('Server'));
296             $response->headers->header('Server' => $server);
297              
298             my $endpoint_path;
299             if ($self->has_endpoint) {
300             $endpoint_path = $self->endpoint_config->{endpoint_path};
301             if (($uri->path eq $endpoint_path) || ($self->request->path eq $endpoint_path)) {
302             return $self->endpoint->run( $self->request );
303             }
304             }
305              
306             if ($self->has_fragments && (($uri->path eq $self->fragments_config->{fragments_path}) || ($self->request->path eq $self->fragments_config->{fragments_path}))) {
307             croak 'A VoID description is needed when using Triple Pattern Fragments' unless ($self->has_void);
308              
309             # First compute the selectors from the query parameters
310             my %params = $uri->query_form;
311             my %statement = (subject => undef,
312             predicate => undef,
313             object => undef);
314             foreach my $term (keys(%statement)) {
315             my $value = $params{$term};
316             next unless $value;
317             return _client_error($response, "$term is invalid") if ref($value); # E.g. an array would be invalid
318             if ($value =~ m/^\?(\S+)$/) { # Regexp matching variable
319             $statement{$term} = variable($1);
320             } elsif (($term eq 'object') && ($value =~ m/^\"(.+)\"((\@|\^\^)(\S+))?$/)) { # regexp matching literal
321             my $string = $1;
322             my $lang_or_datatype = $3;
323             my $rest = $4;
324             if (defined($lang_or_datatype) && ($lang_or_datatype eq '@')) {
325             $statement{$term} = literal($string, $rest);
326             } else {
327             $statement{$term} = literal($string, undef, $rest);
328             }
329             } else { # Now, it may be an IRI
330             try {
331             $statement{$term} = iri($value);
332             } catch {
333             return _client_error($response, 'Was not able to parse subject as a IRI');
334             }
335             }
336             }
337              
338             $self->log->debug('Getting fragment with this selector ' . Dumper(\%statement) );
339             my $output_model = $self->_common_fragments_control;
340             my $iterator;
341             my $counter = 0;
342             if ($params{allow_dump_dataset} || $self->fragments_config->{allow_dump_dataset} || any { defined } values(%statement)) {
343             $iterator = $self->model->get_statements($statement{subject}, $statement{predicate}, $statement{object});
344             } else {
345             $counter = $self->model->size - 1;
346             my $nexturi = $uri;
347             $nexturi->query_form('allow_dump_dataset' => 1);
348             $iterator = RDF::Trine::Iterator::Graph->new([
349             statement(iri($uri),
350             iri('http://www.w3.org/ns/hydra/core#next'),
351             iri($nexturi))
352             ]);
353             }
354              
355             $output_model->begin_bulk_ops;
356             while (my $st = $iterator->next) {
357             $counter++;
358             # TODO: Paging goes here
359             $output_model->add_statement($st);
360             }
361             my $cl = literal($counter, undef, 'http://www.w3.org/2001/XMLSchema#integer');
362             $self->guess_namespaces('void');
363             my $void = $self->namespaces->void;
364             $output_model->add_statement(statement(iri($uri),
365             iri($void->triples),
366             $cl));
367             $output_model->add_statement(statement(iri($uri),
368             iri('http://www.w3.org/ns/hydra/core#totalItems'),
369             $cl));
370             $output_model->add_statement(statement(iri($uri),
371             iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
372             iri($void->Dataset)));
373             $output_model->add_statement(statement($self->void->dataset_uri,
374             iri($void->subset),
375             iri($uri)));
376             $output_model->add_statement(statement(iri($uri),
377             iri('http://purl.org/dc/terms/source'),
378             $self->void->dataset_uri
379             ));
380             $output_model->end_bulk_ops;
381             my ($ct, $s);
382             try {
383             ($ct, $s) = RDF::Trine::Serializer->negotiate('request_headers' => $headers_in,
384             base_uri => $self->base_uri,
385             namespaces => $self->_namespace_hashref);
386             } catch {
387             $response->status(406);
388             $response->headers->content_type('text/plain');
389             $response->body('HTTP 406: No serialization available any specified content type');
390             return $response;
391             };
392              
393             $response->status(200);
394             $response->headers->header('Vary' => join(", ", qw(Accept)));
395             if ($self->has_last_etag) {
396             $response->headers->header('ETag' => '"' . md5_base64($self->last_etag . $ct) . '"');
397             }
398             my $body = $s->serialize_model_to_string($output_model);
399             $self->log->trace("Fragment message body is $body" );
400             $response->headers->content_type($ct);
401             $response->body(encode_utf8($body));
402             return $response;
403             }
404              
405             if ($self->has_void) {
406             my $void_resp = $self->_void_content($uri, $endpoint_path);
407             return $void_resp if (defined($void_resp));
408             }
409              
410             my $type = $self->type;
411             $self->type('');
412             my $node = $self->my_node($uri);
413             $self->log->info("Try rendering '$type' page for subject node: " . $node->as_string);
414             if ($self->count($node) > 0) {
415             if ($type) {
416             my $preds = $self->helper_properties;
417             my $page = $preds->page($node);
418             if (($type eq 'page') && ($page ne $node->uri_value . '/page')) {
419             # Then, we have a foaf:page set that we should redirect to
420             $response->status(301);
421             $response->headers->header('Location' => $page);
422             return $response;
423             }
424              
425             $self->log->debug("Will render '$type' page " );
426             if ($headers_in->can('header') && $headers_in->header('Accept')) {
427             $self->log->debug('Found Accept header: ' . $headers_in->header('Accept') );
428             } else {
429             $headers_in->header('Accept' => 'text/turtle');
430             if ($headers_in->header('Accept')) {
431             $self->log->warn('Setting Accept header: ' . $headers_in->header('Accept') );
432             } else {
433             $self->log->warn('No content type header can be set' );
434             }
435             }
436             $response->status(200);
437             my $content = $self->_content($node, $type, $endpoint_path);
438             $response->headers->header('Vary' => join(", ", qw(Accept)));
439             if (defined($self->current_etag)) {
440             $response->headers->header('ETag' => '"' . md5_base64($self->current_etag . $content->{content_type}) . '"');
441             }
442             $response->headers->content_type($content->{content_type});
443             $response->body(encode_utf8($content->{body}));
444             } else {
445             $response->status(303);
446             my ($ct, $s) = $self->_negotiate($headers_in);
447             return $ct if ($ct->isa('Plack::Response')); # A hack to allow for the failed conneg case
448             my $newurl = $uri . '/data';
449             unless ($s->isa('RDF::Trine::Serializer')) {
450             my $preds = $self->helper_properties;
451             $newurl = $preds->page($node);
452             }
453             $self->log->debug('Will do a 303 redirect to ' . $newurl );
454             $response->headers->header('Location' => $newurl);
455             $response->headers->header('Vary' => join(", ", qw(Accept)));
456             }
457             return $response;
458             } else {
459             $response->status(404);
460             $response->headers->content_type('text/plain');
461             $response->body('HTTP 404: Unknown resource');
462             return $response;
463             }
464             # We should never get here.
465             $response->status(500);
466             $response->headers->content_type('text/plain');
467             $response->body('HTTP 500: No such functionality.');
468             return $response;
469             }
470              
471             sub _client_error {
472             my ($response, $msg) = @_;
473             $response->status(400);
474             $response->headers->content_type('text/plain');
475             $response->body("HTTP 400: $msg");
476             return $response;
477             }
478              
479              
480              
481             =item C<< helper_properties ( ) >>
482              
483             Returns the L<RDF::Helper::Properties> object. if it exists; or sets
484             it if an L<RDF::Helper::Properties> object is given as a parameter.
485              
486             =cut
487              
488             has helper_properties => ( is => 'rw', isa => InstanceOf['RDF::Helper::Properties'], lazy => 1, builder => '_build_helper_properties');
489              
490             sub _build_helper_properties {
491             my $self = shift;
492             return RDF::Helper::Properties->new(model => $self->model);
493             }
494              
495              
496              
497             =item C<< type >>
498              
499             Returns or sets the type of result to return, i.e. C<page>, in the case of a human-intended page or C<data> for machine consumption, or an empty string if it is an actual resource URI that should be redirected.
500              
501             =cut
502              
503             has 'type' => (is => 'rw', isa => Str, default => '');
504              
505              
506             =item C<< my_node >>
507              
508             A node for the requested URI. This node is typically used as the
509             subject to find which statements to return as data. This expects to
510             get a URI object containing the full URI of the node.
511              
512             =cut
513              
514             sub my_node {
515             my ($self, $iri) = @_;
516             $self->log->info("Subject URI to be used: $iri" );
517             return RDF::Trine::Node::Resource->new( $iri );
518             }
519              
520             =item C<< count ( $node) >>
521              
522             Returns the number of statements that has the $node as subject, or all if $node is undef.
523              
524             =cut
525              
526              
527             sub count {
528             my $self = shift;
529             my $node = shift;
530             return $self->model->count_statements( $node, undef, undef );
531             }
532              
533              
534             # =item C<< _content ( $node, $type, $endpoint_path) >>
535             #
536             # Private method to return the a hashref with content for this URI,
537             # based on the $node subject, and the type of node, which may be either
538             # C<data> or C<page>. In the first case, an RDF document serialized to a
539             # format set by content negotiation. In the latter, a simple HTML
540             # document will be returned. Finally, you may pass the endpoint path if
541             # it is available. The returned hashref has two keys: C<content_type>
542             # and C<body>. The former is self-explanatory, the latter contains the
543             # actual content.
544              
545             sub _content {
546             my ($self, $node, $type, $endpoint_path) = @_;
547            
548             my $model = $self->model;
549             my $iter = $model->bounded_description($node);
550             my %output;
551             if ($type eq 'data') {
552             $self->{_type} = 'data';
553             my ($ctype, $s) = RDF::Trine::Serializer->negotiate('request_headers' => $self->request->headers,
554             base => $self->base_uri,
555             namespaces => $self->_namespace_hashref);
556             $output{content_type} = $ctype;
557             if ($self->hypermedia) {
558             my $data_iri = iri($node->uri_value . '/data');
559             my $hmmodel = RDF::Trine::Model->temporary_model;
560             if($self->has_void) {
561             $hmmodel->add_statement(statement($data_iri,
562             iri('http://rdfs.org/ns/void#inDataset'),
563             $self->void->dataset_uri));
564             } else {
565             if($self->has_endpoint) {
566             $hmmodel->add_statement(statement($data_iri,
567             iri('http://rdfs.org/ns/void#inDataset'),
568             blank('void')));
569             $hmmodel->add_statement(statement(blank('void'),
570             iri('http://rdfs.org/ns/void#sparqlEndpoint'),
571             iri($self->base_uri . $endpoint_path)));
572             }
573             if($self->namespaces_as_vocabularies) {
574             $hmmodel->add_statement(statement($data_iri,
575             iri('http://rdfs.org/ns/void#inDataset'),
576             blank('void')));
577             foreach my $nsuri ($self->list_namespaces) {
578             $hmmodel->add_statement(statement(blank('void'),
579             iri('http://rdfs.org/ns/void#vocabulary'),
580             iri($nsuri->uri)));
581             }
582             }
583             }
584             $iter = $iter->concat($hmmodel->as_stream);
585             }
586             $output{body} = $s->serialize_iterator_to_string ( $iter );
587             $self->log->trace("Message body is $output{body}" );
588              
589             } else {
590             $self->{_type} = 'page';
591             my $returnmodel = RDF::Trine::Model->temporary_model;
592             while (my $st = $iter->next) {
593             $returnmodel->add_statement($st);
594             }
595             my $preds = $self->helper_properties;
596             my $gen = RDF::RDFa::Generator->new( style => 'HTML::Pretty',
597             title => $preds->title( $node ),
598             base => $self->base_uri,
599             namespaces => $self->_namespace_hashref);
600             my $writer = HTML::HTML5::Writer->new( charset => 'ascii', markup => 'html' );
601             $output{body} = $writer->document($gen->create_document($returnmodel));
602             $output{content_type} = 'text/html';
603             }
604             return \%output;
605             }
606              
607              
608              
609             =item C<< endpoint ( [ $endpoint ] ) >>
610              
611             Returns the L<RDF::Endpoint> object if it exists or sets it if a
612             L<RDF::Endpoint> object is given as parameter. In most cases, it will
613             be created for you if you pass a C<endpoint_config> hashref to the
614             constructor, so you would most likely not use this method.
615              
616             =cut
617              
618              
619             has endpoint => (is => 'rw', isa => InstanceOf['RDF::Endpoint'], predicate => 'has_endpoint');
620              
621              
622             =item C<< void ( [ $voidg ] ) >>
623              
624             Returns the L<RDF::Generator::Void> object, if it exists; or sets it if
625             an L<RDF::Generator::Void> object is given as parameter. Like
626             C<endpoint>, it will be created for you if you pass a C<void_config>
627             hashref to the constructor, so you would most likely not use this
628             method.
629              
630             =cut
631              
632              
633             has void => (is => 'rw', isa => InstanceOf['RDF::Generator::Void'], predicate => 'has_void');
634              
635              
636             sub _negotiate {
637             my ($self, $headers_in) = @_;
638             my ($ct, $s);
639             try {
640             ($ct, $s) = RDF::Trine::Serializer->negotiate('request_headers' => $headers_in,
641             base_uri => $self->base_uri,
642             namespaces => $self->_namespace_hashref,
643             extend => {
644             'text/html' => 'html',
645             'application/xhtml+xml' => 'xhtml'
646             }
647             );
648             $self->log->debug("Got $ct content type" );
649             } catch {
650             my $response = Plack::Response->new;
651             $response->status(406);
652             $response->headers->content_type('text/plain');
653             $response->body('HTTP 406: No serialization available any specified content type');
654             return $response;
655             };
656             return ($ct, $s)
657             }
658              
659             sub _void_content {
660             my ($self, $uri, $endpoint_path) = @_;
661             my $generator = $self->void;
662             my $dataset_uri = URI->new($generator->dataset_uri);
663             my $fragment = $dataset_uri->fragment;
664             $dataset_uri =~ s/(\#$fragment)$//;
665             if ($uri->eq($dataset_uri)) {
666              
667             # First check if the model has changed, the etag will have
668             # changed, and we will have to regenerate at some point. If
669             # there is no current etag, we clear anyway
670             if ((! defined($self->current_etag)) || ($self->has_last_etag && ($self->last_etag ne $self->current_etag))) {
671             $self->_clear_voidmodel;
672             }
673              
674             # First see if we should read some static stuff from file
675             my $file_model = undef;
676             if ($self->void_config->{add_void}) {
677             $self->_current_extvoid_mtime((stat($self->void_config->{add_void}->{file}))[9]);
678             if ($self->_current_extvoid_mtime != $self->_last_extvoid_mtime) {
679             $self->_clear_voidmodel;
680             $file_model = RDF::Trine::Model->temporary_model;
681             my $parser = RDF::Trine::Parser->new($self->void_config->{add_void}->{syntax});
682             $parser->parse_file_into_model($self->base_uri, $self->void_config->{add_void}->{file}, $file_model);
683             $self->_last_extvoid_mtime((stat($self->void_config->{add_void}->{file}))[9]);
684             }
685             }
686              
687              
688              
689             # Now really regenerate if there is no model now
690             unless ($self->_has_voidmodel) {
691              
692             # Use the methods of the generator to add stuff from config, etc
693             if ($self->void_config->{urispace}) {
694             $generator->urispace($self->void_config->{urispace});
695             } else {
696             $generator->urispace($self->base_uri);
697             }
698             if ($self->namespaces_as_vocabularies) {
699             foreach my $nsuri ($self->list_namespaces) {
700             $generator->add_vocabularies($nsuri->as_string); # TODO: Should be fixed in RDF::Generator::Void, but we fix it here for now
701             }
702             }
703             if ($self->has_endpoint) {
704             $generator->add_endpoints($self->base_uri . $endpoint_path);
705             }
706             if ($self->void_config->{licenses}) {
707             $generator->add_licenses($self->void_config->{licenses});
708             }
709             foreach my $title (@{$self->void_config->{titles}}) {
710             $generator->add_titles(literal(@{$title}));
711             }
712             if ($self->void_config->{endpoints}) {
713             $generator->add_endpoints($self->void_config->{endpoints});
714             }
715             if ($self->void_config->{vocabularies}) {
716             $generator->add_vocabularies($self->void_config->{vocabularies});
717             }
718              
719             # Do the stats and statements
720             $self->_voidmodel($generator->generate($file_model));
721             $self->last_etag($self->current_etag);
722             }
723              
724             if ($self->has_fragments) {
725             $self->_common_fragments_control($self->_voidmodel);
726             }
727              
728             # Now start serializing.
729             my ($ct, $s) = $self->_negotiate($self->request->headers);
730             return $ct if ($ct->isa('Plack::Response')); # A hack to allow for the failed conneg case
731             my $body;
732             if ($s->isa('RDF::Trine::Serializer')) { # Then we just serialize since we have a serializer.
733             $body = $s->serialize_model_to_string($self->_voidmodel);
734             } else {
735             # For (X)HTML, we need to do extra work
736             my $gen = RDF::RDFa::Generator->new( style => 'HTML::Pretty',
737             title => $self->void_config->{pagetitle} || 'VoID Description',
738             base => $self->base_uri,
739             namespaces => $self->_namespace_hashref);
740             my $markup = ($ct eq 'application/xhtml+xml') ? 'xhtml' : 'html';
741             my $writer = HTML::HTML5::Writer->new( charset => 'ascii', markup => $markup );
742             $body = $writer->document($gen->create_document($self->_voidmodel));
743             }
744             my $response = Plack::Response->new;
745             $response->status(200);
746             $response->headers->header('Vary' => join(", ", qw(Accept)));
747             my $etag;
748             $etag = $self->_last_extvoid_mtime if ($self->void_config->{add_void});
749             $etag .= $self->last_etag if (defined($self->last_etag));
750             if ($etag) {
751             $response->headers->header('ETag' => '"' . md5_base64($etag . $ct) . '"');
752             }
753             $response->headers->content_type($ct);
754             $response->body(encode_utf8($body));
755             return $response;
756             } else {
757             return;
758             }
759             }
760              
761             has _voidmodel => (is => 'rw', isa => InstanceOf['RDF::Trine::Model'], predicate => '_has_voidmodel', clearer => '_clear_voidmodel');
762              
763             has _current_extvoid_mtime => (is => 'rw', isa => Int);
764              
765             has _last_extvoid_mtime => (is => 'rw', isa => Int);
766              
767             sub _common_fragments_control {
768             my $self = shift;
769             my $model = shift || RDF::Trine::Model->temporary_model;
770             $self->guess_namespaces('rdf', 'void');
771             $self->add_namespace_mapping(hydra => 'http://www.w3.org/ns/hydra/core#');
772             my $void = $self->namespaces->void;
773             my $hydra = $self->namespaces->hydra;
774             my $rdf = $self->namespaces->rdf;
775             $model->begin_bulk_ops;
776             my $void_subject = $self->void->dataset_uri;
777             $model->add_statement(statement($void_subject,
778             iri($rdf->type),
779             iri($hydra->Collection)));
780             $model->add_statement(statement($void_subject,
781             iri($rdf->type),
782             iri($void->Dataset)));
783             $model->add_statement(statement($void_subject,
784             iri($hydra->search),
785             blank('template')));
786             $model->add_statement(statement($void_subject,
787             iri($void->uriLookupEndpoint),
788             literal($self->base_uri . $self->fragments_config->{fragments_path}
789             . '{?subject,predicate,object}')));
790             $model->add_statement(statement(blank('template'),
791             iri($hydra->template),
792             literal($self->base_uri . $self->fragments_config->{fragments_path}
793             . '{?subject,predicate,object}')));
794            
795             $model->add_statement(statement(blank('template'),
796             iri($hydra->mapping),
797             blank('subject')));
798             $model->add_statement(statement(blank('template'),
799             iri($hydra->mapping),
800             blank('predicate')));
801             $model->add_statement(statement(blank('template'),
802             iri($hydra->mapping),
803             blank('object')));
804              
805             $model->add_statement(statement(blank('subject'),
806             iri($hydra->property),
807             iri($rdf->subject)));
808             $model->add_statement(statement(blank('subject'),
809             iri($hydra->variable),
810             literal('subject')));
811              
812             $model->add_statement(statement(blank('predicate'),
813             iri($hydra->property),
814             iri($rdf->predicate)));
815             $model->add_statement(statement(blank('predicate'),
816             iri($hydra->variable),
817             literal('predicate')));
818              
819             $model->add_statement(statement(blank('object'),
820             iri($hydra->property),
821             iri($rdf->object)));
822             $model->add_statement(statement(blank('object'),
823             iri($hydra->variable),
824             literal('object')));
825             $model->end_bulk_ops;
826             return $model;
827             }
828              
829             =back
830              
831              
832             =head1 AUTHOR
833              
834             Kjetil Kjernsmo, C<< <kjetilk@cpan.org> >>
835              
836             =head1 CONTRIBUTORS
837              
838             Toby Inkster
839              
840             =head1 BUGS
841              
842             Please report any bugs using L<github|https://github.com/kjetilk/RDF-LinkedData/issues>
843              
844              
845             =head1 SUPPORT
846              
847             You can find documentation for this module with the perldoc command.
848              
849             perldoc RDF::LinkedData
850              
851             The perlrdf mailing list is the right place to seek help and discuss this module:
852              
853             L<http://lists.perlrdf.org/listinfo/dev>
854              
855             =head1 TODO
856              
857             This module does what it is supposed to do rather well, and has thus
858             reached the 1.0 milestone. To support a wider variety of use cases,
859             the current module isn't flexible enough, so future version will need
860             substantial changes, but the version number is intended to reflect
861             that.
862              
863             =head1 ACKNOWLEDGMENTS
864              
865             This module was started by Gregory Todd Williams C<<
866             <gwilliams@cpan.org> >> for RDF::LinkedData::Apache, but has been
867             almost totally rewritten.
868              
869             =head1 COPYRIGHT & LICENSE
870              
871             Copyright 2010 Gregory Todd Williams
872              
873             Copyright 2010 ABC Startsiden AS
874              
875             Copyright 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Kjetil Kjernsmo
876              
877             This program is free software; you can redistribute it and/or modify it
878             under the same terms as Perl itself.
879              
880              
881             =cut
882              
883             1;