blib/lib/MOBY/RDF/Ontologies/Cache/NamespaceCache.pm untested

filter: Statementstmt 0.0% 0 / 223 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 360 CC 32 SCAR 43.5
CC
32
Cov
0%
get_rdf
156.0
update_namespace_cache
132.0
new
90.0
CRAP 77.7
1 #-----------------------------------------------------------------
2 # MOBY::RDF::Ontologies::Cache::NamespaceCache
3 # Author: Edward Kawas <edward.kawas@gmail.com>,
4 # For copyright and disclaimer see below.
5 #
6 # $Id: NamespaceCache.pm,v 1.4 2008/09/02 13:12:33 kawas Exp $
7 #-----------------------------------------------------------------
8  
9 package MOBY::RDF::Ontologies::Cache::NamespaceCache;
10  
11 use XML::LibXML;
12  
13 use RDF::Core::Model::Parser;
14 use RDF::Core::Storage::Memory;
15 use RDF::Core::Model;
16 use RDF::Core::Resource;
17 use RDF::Core::Literal;
18 use RDF::Core::Statement;
19 use RDF::Core::Model::Serializer;
20  
21 use Fcntl ':flock';
22  
23 use MOBY::RDF::Utils;
24 use MOBY::RDF::Ontologies::Namespaces;
25 use MOBY::RDF::Ontologies::Cache::CacheUtils;
26 use MOBY::Client::Central;
27  
28 use SOAP::Lite;
29  
30 use Data::Dumper;
31 use strict;
32  
33 use vars qw /$VERSION/;
34 $VERSION = sprintf "%d.%02d", q$Revision: 1.4 $ =~ /: (\d+)\.(\d+)/;
35  
36 =head1 NAME
37  
38 MOBY::RDF::Ontologies::Cache::NamespaceCache - Module for creating a cache of namespaces for use when generating RDF
39  
40 =head1 SYNOPSIS
41  
42 use MOBY::RDF::Ontologies::Cache::NamespaceCache;
43  
44 # required
45 my $cachedir = "/tmp/";
46  
47 # optional - gets default values from MOBY::Client::Central
48 my $url = "http://moby.ucalgary.ca/moby/MOBY-Central.pl";
49 my $uri = "http://moby.ucalgary.ca/MOBY/Central";
50  
51 my $x = MOBY::RDF::Ontologies::Cache::NamespaceCache->new(
52 endpoint => $url,
53 namespace => $uri,
54 cache => $cachedir,
55 );
56  
57 # create the namespace cache
58 $x->create_namespace_cache();
59  
60 # update the cache
61 $x->update_namespace_cache();
62  
63 # obtain the RDF in a thread safe manner
64 my $rdf = $x->get_rdf
65  
66 =head1 DESCRIPTION
67  
68 This module aids in the creation and maintainence of a namespace cache for use in generating datatype RDF
69  
70 =cut
71  
72 =head1 AUTHORS
73  
74 Edward Kawas (edward.kawas [at] gmail [dot] com)
75  
76 =cut
77  
78 #-----------------------------------------------------------------
79  
80 =head1 SUBROUTINES
81  
82 =cut
83  
84 #-----------------------------------------------------------------
85 # new
86 #-----------------------------------------------------------------
87  
88 =head2 new
89  
90 Instantiate a NamespaceCache object.
91  
92 Parameters:
93 * A Hash with keys:
94 -> endpoint => the BioMOBY registry endpoint to use <optional>
95 -> namespace => the BioMOBY registry namespace to use <optional>
96 -> cache => the directory to store the cache <REQUIRED>
97  
98 This subroutine attempts to create the cache directories right away
99 and if any problems occur then an Exception is thrown.
100  
101 =cut
102  
103 sub new {
104 my ( $class, %args ) = @_;
105  
106 # create an object
107 my $self = bless {}, ref($class) || $class;
108  
109 # set various variables
110 $self->{endpoint} = $args{endpoint} if $args{endpoint};
111 $self->{namespace} = $args{namespace} if $args{namespace};
112 $self->{cachedir} = $args{cache} if $args{cache};
113
114
115 eval {
116 $self->{endpoint} = MOBY::Client::Central->new()->{default_MOBY_server};
117 } unless $args{endpoint};
118
119 # if the values arent set, set to default values
120 $self->{endpoint} = "http://moby.ucalgary.ca/moby/MOBY-Central.pl"
121 unless $self->{endpoint};
122 $self->{namespace} = "http://moby.ucalgary.ca/MOBY/Central"
123 unless $self->{namespace};
124 $self->{cachedir} = "/tmp/" unless $self->{cachedir};
125  
126 $self->{utils} = MOBY::RDF::Ontologies::Cache::CacheUtils->new(
127 cache => $self->{cachedir},
128 endpoint => $self->{endpoint},
129 namespace => $self->{namespace}
130 );
131  
132 # create the cache directory if necessary
133 $self->{utils}->create_cache_dirs unless $self->{utils}->cache_exists;
134  
135 # done
136 return $self;
137 }
138  
139 #-----------------------------------------------------------------
140 # create_namespace_cache
141 #-----------------------------------------------------------------
142  
143 =head2 create_namespace_cache
144  
145 Create the namespace cache. This will over write any pre-existing
146 cache that it finds.
147  
148 This method is not thread safe.
149  
150 Throw an exception if any of the following occurs:
151 * A SOAP error as a result of calling the registry
152 * Problems writing to the cache directory
153  
154 =cut
155  
156 sub create_namespace_cache {
157 my ($self) = @_;
158  
159 # 2 steps:
160 # -> create a LIST file
161 my $xml = $self->_create_list_file;
162  
163 # 2-> foreach datatype store RDF for the authority
164 my $parser = XML::LibXML->new();
165 my $doc = $parser->parse_string($xml);
166 my %authorities_completed = ();
167 my $nodes = $doc->documentElement()->getChildrenByTagName('Namespace');
168 for ( 1 .. $nodes->size() ) {
169 my $name = $nodes->get_node($_)->getAttribute('name');
170 next if $authorities_completed{$name};
171 $authorities_completed{$name} = 1;
172  
173 $xml = MOBY::RDF::Ontologies::Namespaces->new(
174 endpoint => $self->{utils}->_endpoint );
175 $xml = $xml->createByName( { term => $name });
176 my $file = File::Spec->catfile(
177 $self->{utils}->cachedir,
178 $self->{utils}->_clean( $self->{utils}->_endpoint ),
179 $self->{utils}->NAMESPACES_CACHE,
180 $name
181 );
182 open( FILE, ">$file" )
183 or die("Can't open file '$file' for writing: $!");
184 print FILE $xml;
185 close FILE;
186 }
187 }
188  
189 #-----------------------------------------------------------------
190 # update_namespace_cache
191 #-----------------------------------------------------------------
192  
193 =head2 update_namespace_cache
194  
195 Update the namespace cache. This will update any items that are 'old',
196 by relying on the LSID for the namespace. This method is not thread safe.
197  
198 This method returns the number of changed resources or -1 if a cache had to be created for you.
199  
200 To update the cache with a thread safe method, call C<get_rdf>.
201  
202 Throw an exception if any of the following occur:
203 * There is a SOAP error calling the registry
204 * There were read/write errors on the cache directory or its contents
205  
206 =cut
207  
208 sub update_namespace_cache {
209 my ($self) = @_;
210 my $wasOld = 0;
211 my %old_services = ();
212 my %new_services = ();
213 my %changed_services = ();
214  
215 if (
216 !(
217 -e File::Spec->catfile(
218 $self->{utils}->cachedir,
219 $self->{utils}->_clean( $self->{utils}->_endpoint ),
220 $self->{utils}->NAMESPACES_CACHE
221 )
222 )
223 )
224 {
225 $self->create_namespace_cache;
226 return -1;
227 }
228  
229 if (
230 !(
231 -e File::Spec->catfile(
232 $self->{utils}->cachedir,
233 $self->{utils}->_clean( $self->{utils}->_endpoint ),
234 $self->{utils}->NAMESPACES_CACHE,
235 $self->{utils}->LIST_FILE
236 )
237 )
238 )
239 {
240 warn( "Namespace LIST_FILE doesn't exist, so I created the cache from scratch!"
241 );
242 $self->create_namespace_cache;
243 return -1;
244 }
245  
246 # steps:
247 # read in the LIST file and extract lsids for all datatypes
248 my $file = File::Spec->catfile(
249 $self->{utils}->cachedir,
250 $self->{utils}->_clean( $self->{utils}->_endpoint ),
251 $self->{utils}->NAMESPACES_CACHE,
252 $self->{utils}->LIST_FILE
253 );
254 my $parser = XML::LibXML->new();
255 my $doc;
256 eval {
257 $doc = $parser->parse_file($file);
258 };
259 warn "There was something wrong with '$file' and we couldn't parse it.\nWill attempt to create from scratch.\n" if $@;
260 $doc = $parser->parse_string($self->_create_list_file) if $@;
261
262 my $nodes = $doc->documentElement()->getChildrenByTagName('Namespace');
263 for ( 1 .. $nodes->size() ) {
264 my $name = $nodes->get_node($_)->getAttribute('name');
265 my $lsid = $nodes->get_node($_)->getAttribute('lsid');
266 $old_services{$name}{$lsid} = 1;
267 }
268  
269 # get the new LIST file and extract lsids for all objects
270 my $soap =
271 SOAP::Lite->uri( $self->{utils}->_namespace )
272 ->proxy( $self->{utils}->_endpoint )->on_fault(
273 sub {
274 my $soap = shift;
275 my $res = shift;
276 die( "There was a problem calling the registry: "
277 . $self->{utils}->_endpoint . "\@ "
278 . $self->{utils}->_namespace . ".\n"
279 . $res );
280 }
281 );
282  
283 my $xml = $soap->retrieveNamespaces()->result;
284 $parser = XML::LibXML->new();
285 $doc = $parser->parse_string($xml);
286 $nodes = $doc->documentElement()->getChildrenByTagName('Namespace');
287 for ( 1 .. $nodes->size() ) {
288 my $name = $nodes->get_node($_)->getAttribute('name');
289 my $lsid = $nodes->get_node($_)->getAttribute('lsid');
290 $new_services{$name}{$lsid} = 1;
291 }
292  
293 # go through the keys of the new one and if the keys doesnt exist or has been modified, add to 'download' queue
294 foreach my $auth ( keys %new_services ) {
295 next if $changed_services{$auth};
296 foreach my $lsid ( keys %{ $new_services{$auth} } ) {
297 next unless !$old_services{$auth}{$lsid};
298 $changed_services{$auth} = 1;
299 }
300  
301 }
302  
303 # if their where changes, save new LIST file over the old one and get changes
304 if ( keys %changed_services ) {
305  
306 # save new LIST file
307 open( FILE, ">$file" )
308 or die("Can't open file '$file' for writing: $!");
309 print FILE $xml;
310 close FILE;
311  
312 # clear used values
313 $xml = undef;
314 $file = undef;
315 $parser = undef;
316 $doc = undef;
317 $nodes = undef;
318 foreach my $authURI ( keys %changed_services ) {
319 $wasOld++;
320 $xml = MOBY::RDF::Ontologies::Namespaces->new(
321 endpoint => $self->{utils}->_endpoint, );
322  
323 $xml = $xml->createByName( { term => $authURI });
324 $file = File::Spec->catfile(
325 $self->{utils}->cachedir,
326 $self->{utils}->_clean( $self->{utils}->_endpoint ),
327 $self->{utils}->NAMESPACES_CACHE,
328 $authURI
329 );
330 open( FILE, ">$file" )
331 or die("Can't open file '$file' for writing: $!");
332 print FILE $xml;
333 close FILE;
334 }
335 }
336 # remove any old files that should not be cached
337 my $cachedir = File::Spec->catfile(
338 $self->{utils}->cachedir,
339 $self->{utils}->_clean( $self->{utils}->_endpoint ),
340 $self->{utils}->NAMESPACES_CACHE
341 );
342  
343 eval {
344 my @files = $self->{utils}->plainfiles($cachedir);
345 foreach my $path (@files) {
346 my $filename = substr $path, length($cachedir)+1;
347
348 next if -d $filename;
349 next
350 if $filename eq $self->{utils}->RDF_FILE
351 or $filename eq $self->{utils}->LIST_FILE
352 or $filename eq $self->{utils}->UPDATE_FILE;
353
354 unlink($path) unless $new_services{$filename};
355 $wasOld++;
356 }
357 };
358
359 return $wasOld;
360 }
361  
362 #-----------------------------------------------------------------
363 # get_rdf
364 # Return a cached copy of the RDF
365  
366 #-----------------------------------------------------------------
367  
368 =head2 get_rdf
369  
370 Gets the cached copy of the RDF for all namespaces. This subroutine
371 is thread safe as it performs a flock on a Lock file in the
372 directory while performing operations.
373  
374 Throw an exception if any of the following occur:
375 * There was a SOAP problem communicating with a registr
376 * There was a file read/write while performing cache related
377 activities
378 * There was a problem parsing XML
379  
380 =cut
381  
382 sub get_rdf {
383 my ($self) = @_;
384 my $xml = "";
385 my $lock = File::Spec->catfile(
386 $self->{utils}->cachedir,
387 $self->{utils}->_clean( $self->{utils}->_endpoint ),
388 $self->{utils}->NAMESPACES_CACHE,
389 $self->{utils}->UPDATE_FILE
390 );
391  
392 my $file = File::Spec->catfile(
393 $self->{utils}->cachedir,
394 $self->{utils}->_clean( $self->{utils}->_endpoint ),
395 $self->{utils}->NAMESPACES_CACHE,
396 $self->{utils}->RDF_FILE
397 );
398 my $dir = File::Spec->catfile(
399 $self->{utils}->cachedir,
400 $self->{utils}->_clean( $self->{utils}->_endpoint ),
401 $self->{utils}->NAMESPACES_CACHE
402 );
403  
404 open( LOCK, ">$lock" );
405 flock( LOCK, LOCK_EX );
406 eval {
407  
408 # check if we need to re-merge the RDF
409 my $isStale = $self->update_namespace_cache;
410 if ( $isStale or !( -e $file ) ) {
411
412 my $providers = $self->_get_object_names;
413
414 # re-merge rdf
415 my $parser = XML::LibXML->new();
416 my $doc = undef;
417 opendir DIR, $dir
418 or die "Could not open directory for reading: $!\n";
419  
420 # foreach authority, parse the rdf - add to a single document
421 foreach my $RDF ( readdir DIR ) {
422 next if -d $RDF;
423 next
424 if $RDF eq $self->{utils}->RDF_FILE
425 or $RDF eq $self->{utils}->LIST_FILE
426 or $RDF eq $self->{utils}->UPDATE_FILE;
427 #remove those authorities that dont have any objects
428 unlink(File::Spec->catfile( $dir, $RDF )) unless $providers->{$RDF};
429 do {
430 eval {
431 $doc =
432 $parser->parse_file(
433 File::Spec->catfile( $dir, $RDF ) );
434 };
435 warn $@ if $@;
436 next;
437 } unless $doc;
438 my $temp_doc = eval {
439 $parser->parse_file( File::Spec->catfile( $dir, $RDF ) );
440 };
441 warn $@ if $@;
442 next if $@;
443 foreach
444  
445 # here
446 my $service (
447 $temp_doc->findnodes('/rdf:RDF/rdf:Description') )
448 {
449 $doc->documentElement->appendChild($service);
450 }
451  
452 }
453 $xml = $doc->toString() if $doc;
454 $xml = new MOBY::RDF::Utils->empty_rdf unless $doc;
455  
456 # save new RDF file
457 open( FILE, ">$file" )
458 or die("Can't open file '$file' for writing: $!");
459 print FILE $xml;
460 close FILE;
461 } else {
462  
463 # send existing rdf
464 open( RDF_FILE, $file );
465 $xml = join "", <RDF_FILE>;
466 }
467 };
468 flock( LOCK, LOCK_UN );
469 close(LOCK);
470 die $@ if $@;
471 return $xml;
472 }
473  
474 sub _get_object_names {
475 my ($self) = @_;
476 my $soap =
477 SOAP::Lite->uri( $self->{utils}->_namespace )
478 ->proxy( $self->{utils}->_endpoint )->on_fault(
479 sub {
480 my $soap = shift;
481 my $res = shift;
482 die( "There was a problem calling the registry: "
483 . $self->{utils}->_endpoint . "\@ "
484 #. $self->{utils}->_namespace . ".\n"
485 . $res );
486 }
487 );
488  
489 my $xml = $soap->retrieveNamespaces()->result;
490 my %providers = ();
491
492 my $parser = XML::LibXML->new();
493 my $doc = $parser->parse_string($xml);
494 my $nodes = $doc->documentElement()->getChildrenByTagName('Namespace');
495 for ( 1 .. $nodes->size() ) {
496 my $name = $nodes->get_node($_)->getAttribute('name');
497 next if $providers{$name};
498 $providers{$name} = 1;
499 }
500
501 return \%providers;
502
503 }
504  
505 # creates the list file and returns it as a string
506 sub _create_list_file {
507 my ($self) = @_;
508 my $soap =
509 SOAP::Lite->uri( $self->{utils}->_namespace )
510 ->proxy( $self->{utils}->_endpoint )->on_fault(
511 sub {
512 my $soap = shift;
513 my $res = shift;
514 die( "There was a problem calling the registry: "
515 . $self->{utils}->_endpoint . "\@ "
516 . $self->{utils}->_namespace . ".\n"
517 . $res );
518 }
519 );
520  
521 my $xml = $soap->retrieveNamespaces()->result;
522  
523 # create cache dirs as needed
524 $self->{utils}->create_cache_dirs;
525 my $file = File::Spec->catfile(
526 $self->{utils}->cachedir,
527 $self->{utils}->_clean( $self->{utils}->_endpoint ),
528 $self->{utils}->NAMESPACES_CACHE,
529 $self->{utils}->LIST_FILE
530 );
531 open( FILE, ">$file" )
532 or die("Can't open file '$file' for writing: $!");
533 print FILE $xml;
534 close FILE;
535
536 return $xml;
537  
538 }
539  
540 1;
541 __END__