blib/lib/MOBY/RDF/Ontologies/Cache/ObjectCache.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_object_cache
132.0
new
90.0
CRAP 77.7
1 #-----------------------------------------------------------------
2 # MOBY::RDF::Ontologies::Cache::ObjectCache
3 # Author: Edward Kawas <edward.kawas@gmail.com>,
4 # For copyright and disclaimer see below.
5 #
6 # $Id: ObjectCache.pm,v 1.5 2008/09/02 13:12:33 kawas Exp $
7 #-----------------------------------------------------------------
8  
9 package MOBY::RDF::Ontologies::Cache::ObjectCache;
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::Objects;
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.5 $ =~ /: (\d+)\.(\d+)/;
35  
36 =head1 NAME
37  
38 MOBY::RDF::Ontologies::Cache::ObjectCache - Module for creating a cache of datatypes for use when generating RDF
39  
40 =head1 SYNOPSIS
41  
42 use MOBY::RDF::Ontologies::Cache::ObjectCache;
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::ObjectCache->new(
52 endpoint => $url,
53 namespace => $uri,
54 cache => $cachedir,
55 );
56  
57 # create the object cache
58 $x->create_object_cache();
59  
60 # update the cache
61 $x->update_object_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 datatype 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 ObjectCache 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_object_cache
141 #-----------------------------------------------------------------
142  
143 =head2 create_object_cache
144  
145 Create the datatype 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_object_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('Object');
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::Objects->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}->DATATYPES_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_object_cache
191 #-----------------------------------------------------------------
192  
193 =head2 update_object_cache
194  
195 Update the object cache. This will update any items that are 'old',
196 by relying on the LSID for the datatype. This method is not thread safe.
197  
198 This method returns the number of changed resources.
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_object_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}->DATATYPES_CACHE
221 )
222 )
223 )
224 {
225 $self->create_object_cache;
226 return;
227 }
228  
229 if (
230 !(
231 -e File::Spec->catfile(
232 $self->{utils}->cachedir,
233 $self->{utils}->_clean( $self->{utils}->_endpoint ),
234 $self->{utils}->DATATYPES_CACHE,
235 $self->{utils}->LIST_FILE
236 )
237 )
238 )
239 {
240 warn( "DataTypes LIST_FILE doesn't exist, so I created the cache from scratch!"
241 );
242 $self->create_object_cache;
243 return;
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}->DATATYPES_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('Object');
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->retrieveObjectNames()->result;
284 $parser = XML::LibXML->new();
285 $doc = $parser->parse_string($xml);
286 $nodes = $doc->documentElement()->getChildrenByTagName('Object');
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::Objects->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}->DATATYPES_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
337 # remove any old files that should not be cached
338 my $cachedir = File::Spec->catfile(
339 $self->{utils}->cachedir,
340 $self->{utils}->_clean( $self->{utils}->_endpoint ),
341 $self->{utils}->DATATYPES_CACHE
342 );
343  
344 eval {
345 my @files = $self->{utils}->plainfiles($cachedir);
346 foreach my $path (@files) {
347 my $filename = substr $path, length($cachedir)+1;
348
349 next if -d $filename;
350 next
351 if $filename eq $self->{utils}->RDF_FILE
352 or $filename eq $self->{utils}->LIST_FILE
353 or $filename eq $self->{utils}->UPDATE_FILE;
354
355 unlink($path) unless $new_services{$filename};
356 $wasOld++;
357 }
358 };
359
360 return $wasOld;
361 }
362  
363 #-----------------------------------------------------------------
364 # get_rdf
365 # Return a cached copy of the RDF
366  
367 #-----------------------------------------------------------------
368  
369 =head2 get_rdf
370  
371 Gets the cached copy of the RDF for all datatypes. This subroutine
372 is thread safe as it performs a flock on a Lock file in the
373 directory while performing operations.
374  
375 Throw an exception if any of the following occur:
376 * There was a SOAP problem communicating with a registr
377 * There was a file read/write while performing cache related
378 activities
379 * There was a problem parsing XML
380  
381 =cut
382  
383 sub get_rdf {
384 my ($self) = @_;
385 my $xml = "";
386 my $lock = File::Spec->catfile(
387 $self->{utils}->cachedir,
388 $self->{utils}->_clean( $self->{utils}->_endpoint ),
389 $self->{utils}->DATATYPES_CACHE,
390 $self->{utils}->UPDATE_FILE
391 );
392  
393 my $file = File::Spec->catfile(
394 $self->{utils}->cachedir,
395 $self->{utils}->_clean( $self->{utils}->_endpoint ),
396 $self->{utils}->DATATYPES_CACHE,
397 $self->{utils}->RDF_FILE
398 );
399 my $dir = File::Spec->catfile(
400 $self->{utils}->cachedir,
401 $self->{utils}->_clean( $self->{utils}->_endpoint ),
402 $self->{utils}->DATATYPES_CACHE
403 );
404  
405 open( LOCK, ">$lock" );
406 flock( LOCK, LOCK_EX );
407 eval {
408  
409 # check if we need to re-merge the RDF
410 my $isStale = $self->update_object_cache;
411 if ( $isStale or !( -e $file ) ) {
412
413 my $providers = $self->_get_object_names;
414
415 # re-merge rdf
416 my $parser = XML::LibXML->new();
417 my $doc = undef;
418 opendir DIR, $dir
419 or die "Could not open directory for reading: $!\n";
420  
421 # foreach authority, parse the rdf - add to a single document
422 foreach my $RDF ( readdir DIR ) {
423 next if -d $RDF;
424 next
425 if $RDF eq $self->{utils}->RDF_FILE
426 or $RDF eq $self->{utils}->LIST_FILE
427 or $RDF eq $self->{utils}->UPDATE_FILE;
428 #remove those authorities that dont have any objects
429 unlink(File::Spec->catfile( $dir, $RDF )) unless $providers->{$RDF};
430 do {
431 eval {
432 $doc =
433 $parser->parse_file(
434 File::Spec->catfile( $dir, $RDF ) );
435 };
436 warn $@ if $@;
437 next;
438 } unless $doc;
439 my $temp_doc = eval {
440 $parser->parse_file( File::Spec->catfile( $dir, $RDF ) );
441 };
442 warn $@ if $@;
443 next if $@;
444 foreach
445  
446 # here
447 my $service (
448 $temp_doc->findnodes('/rdf:RDF/rdf:Description') )
449 {
450 $doc->documentElement->appendChild($service);
451 }
452  
453 }
454 $xml = $doc->toString() if $doc;
455 $xml = new MOBY::RDF::Utils->empty_rdf unless $doc;
456  
457 # save new RDF file
458 open( FILE, ">$file" )
459 or die("Can't open file '$file' for writing: $!");
460 print FILE $xml;
461 close FILE;
462 } else {
463  
464 # send existing rdf
465 open( RDF_FILE, $file );
466 $xml = join "", <RDF_FILE>;
467 }
468 };
469 flock( LOCK, LOCK_UN );
470 close(LOCK);
471 die $@ if $@;
472 return $xml;
473 }
474  
475 sub _get_object_names {
476 my ($self) = @_;
477 my $soap =
478 SOAP::Lite->uri( $self->{utils}->_namespace )
479 ->proxy( $self->{utils}->_endpoint )->on_fault(
480 sub {
481 my $soap = shift;
482 my $res = shift;
483 die( "There was a problem calling the registry: "
484 . $self->{utils}->_endpoint . "\@ "
485 #. $self->{utils}->_namespace . ".\n"
486 . $res );
487 }
488 );
489  
490 my $xml = $soap->retrieveObjectNames()->result;
491 my %providers = ();
492
493 my $parser = XML::LibXML->new();
494 my $doc = $parser->parse_string($xml);
495 my $nodes = $doc->documentElement()->getChildrenByTagName('Object');
496 for ( 1 .. $nodes->size() ) {
497 my $name = $nodes->get_node($_)->getAttribute('name');
498 next if $providers{$name};
499 $providers{$name} = 1;
500 }
501
502 return \%providers;
503
504 }
505  
506 # creates the list file and returns it as a string
507 sub _create_list_file {
508 my ($self) = @_;
509 my $soap =
510 SOAP::Lite->uri( $self->{utils}->_namespace )
511 ->proxy( $self->{utils}->_endpoint )->on_fault(
512 sub {
513 my $soap = shift;
514 my $res = shift;
515 die( "There was a problem calling the registry: "
516 . $self->{utils}->_endpoint . "\@ "
517 . $self->{utils}->_namespace . ".\n"
518 . $res );
519 }
520 );
521  
522 my $xml = $soap->retrieveObjectNames()->result;
523  
524 # create cache dirs as needed
525 $self->{utils}->create_cache_dirs;
526 my $file = File::Spec->catfile(
527 $self->{utils}->cachedir,
528 $self->{utils}->_clean( $self->{utils}->_endpoint ),
529 $self->{utils}->DATATYPES_CACHE,
530 $self->{utils}->LIST_FILE
531 );
532 open( FILE, ">$file" )
533 or die("Can't open file '$file' for writing: $!");
534 print FILE $xml;
535 close FILE;
536
537 return $xml;
538  
539 }
540  
541 1;
542 __END__