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

filter: Statementstmt 0.0% 0 / 229 Branchbran 0.0% 0 / 72 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 / 376 CC 37 SCAR 47.5
CC
37
Cov
0%
update_service_cache
240.0
get_rdf
182.0
new
90.0
CRAP 115.9
1 #-----------------------------------------------------------------
2 # MOBY::RDF::Ontologies::Cache::ServiceCache
3 # Author: Edward Kawas <edward.kawas@gmail.com>,
4 # For copyright and disclaimer see below.
5 #
6 # $Id: ServiceCache.pm,v 1.6 2008/09/02 13:12:33 kawas Exp $
7 #-----------------------------------------------------------------
8  
9 package MOBY::RDF::Ontologies::Cache::ServiceCache;
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::Services;
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.6 $ =~ /: (\d+)\.(\d+)/;
35  
36 =head1 NAME
37  
38 MOBY::RDF::Ontologies::Cache::ServiceCache - Module for creating a cache of service instances for use when generating RDF
39  
40 =head1 SYNOPSIS
41  
42 use MOBY::RDF::Ontologies::Cache::ServiceCache;
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::ServiceCache->new(
52 endpoint => $url,
53 namespace => $uri,
54 cache => $cachedir,
55 );
56  
57 # create the service cache
58 $x->create_service_cache();
59  
60 # update the cache
61 $x->update_service_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 service instance cache for use in generating service 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 ServiceCache 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_service_cache
141 #-----------------------------------------------------------------
142  
143 =head2 create_service_cache
144  
145 Create the service 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_service_cache {
157 my ($self) = @_;
158  
159 # 2 steps:
160 # -> create a LIST file
161 my $xml = $self->_create_list_file;
162  
163 # 2-> foreach service 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('serviceName');
168 for ( 1 .. $nodes->size() ) {
169 my $name = $nodes->get_node($_)->getAttribute('authURI');
170 next if $authorities_completed{$name};
171 $authorities_completed{$name} = 1;
172  
173 $xml = MOBY::RDF::Ontologies::Services->new(
174 endpoint => $self->{utils}->_endpoint );
175 $xml = $xml->findService( { authURI => $name, isAlive => 'no' } );
176 my $file = File::Spec->catfile(
177 $self->{utils}->cachedir,
178 $self->{utils}->_clean( $self->{utils}->_endpoint ),
179 $self->{utils}->SERVICES_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_service_cache
191 #-----------------------------------------------------------------
192  
193 =head2 update_service_cache
194  
195 Update the services 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_service_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}->SERVICES_CACHE
221 )
222 )
223 )
224 {
225 $self->create_service_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}->SERVICES_CACHE,
235 $self->{utils}->LIST_FILE
236 )
237 )
238 )
239 {
240 warn( "Services LIST_FILE doesn't exist, so I created the cache from scratch!"
241 );
242 $self->create_service_cache;
243 return;
244 }
245  
246 # steps:
247 # read in the LIST file and extract lsids for all services
248 my $file = File::Spec->catfile(
249 $self->{utils}->cachedir,
250 $self->{utils}->_clean( $self->{utils}->_endpoint ),
251 $self->{utils}->SERVICES_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('serviceName');
263 for ( 1 .. $nodes->size() ) {
264 my $name = $nodes->get_node($_)->getAttribute('authURI');
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 services
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->retrieveServiceNames()->result;
284 $parser = XML::LibXML->new();
285 $doc = $parser->parse_string($xml);
286 $nodes = $doc->documentElement()->getChildrenByTagName('serviceName');
287 for ( 1 .. $nodes->size() ) {
288 my $name = $nodes->get_node($_)->getAttribute('authURI');
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 $changed_services{$auth} = 1 unless $old_services{$auth}{$lsid};
298 delete $old_services{$auth}{$lsid} if $old_services{$auth}{$lsid};
299
300 }
301 }
302  
303 # iterate over old_services and add their authority to changed_services
304 # old services should only have authorities with services that have been removed
305 foreach my $auth ( keys %old_services ) {
306 next if $changed_services{$auth};
307 foreach my $lsid ( keys %{ $old_services{$auth} } ) {
308 next if $changed_services{$auth};
309 $changed_services{$auth} = 1;
310 }
311 }
312
313 # if their where changes, save new LIST file over the old one and get changes
314 if ( keys %changed_services ) {
315  
316 # save new LIST file
317 open( FILE, ">$file" )
318 or die("Can't open file '$file' for writing: $!");
319 print FILE $xml;
320 close FILE;
321  
322 # clear used values
323 $xml = undef;
324 $file = undef;
325 $parser = undef;
326 $doc = undef;
327 $nodes = undef;
328 foreach my $authURI ( keys %changed_services ) {
329 $wasOld++;
330 $xml = MOBY::RDF::Ontologies::Services->new(
331 endpoint => $self->{utils}->_endpoint, );
332  
333 $xml = $xml->findService( { authURI => $authURI, isAlive => 'no' } );
334 $file = File::Spec->catfile(
335 $self->{utils}->cachedir,
336 $self->{utils}->_clean( $self->{utils}->_endpoint ),
337 $self->{utils}->SERVICES_CACHE,
338 $authURI
339 );
340 open( FILE, ">$file" )
341 or die("Can't open file '$file' for writing: $!");
342 print FILE $xml;
343 close FILE;
344 }
345 }
346
347 # iterate through file system list and if the authority is missing from new_services delete it from the cache
348 my $cachedir = File::Spec->catfile(
349 $self->{utils}->cachedir,
350 $self->{utils}->_clean( $self->{utils}->_endpoint ),
351 $self->{utils}->SERVICES_CACHE
352 );
353
354 eval {
355 my @files = $self->{utils}->plainfiles($cachedir);
356 foreach my $path (@files) {
357 my $filename = substr $path, length($cachedir)+1;
358
359 # dont remove the RDF, LIST or update file
360 next if -d $filename;
361 next
362 if $filename eq $self->{utils}->RDF_FILE
363 or $filename eq $self->{utils}->LIST_FILE
364 or $filename eq $self->{utils}->UPDATE_FILE;
365
366 unlink($path) unless $new_services{$filename};
367 $wasOld++ unless $new_services{$filename};
368 }
369 };
370 return $wasOld;
371 }
372  
373 #-----------------------------------------------------------------
374 # get_rdf
375 # Return a cached copy of the RDF
376  
377 #-----------------------------------------------------------------
378  
379 =head2 get_rdf
380  
381 Gets the cached copy of the RDF for all services. This subroutine
382 is thread safe as it performs a flock on a Lock file in the
383 directory while performing operations.
384  
385 Throw an exception if any of the following occur:
386 * There was a SOAP problem communicating with a registr
387 * There was a file read/write while performing cache related
388 activities
389 * There was a problem parsing XML
390  
391 =cut
392  
393 sub get_rdf {
394 my ($self) = @_;
395 my $xml = "";
396 my $lock = File::Spec->catfile(
397 $self->{utils}->cachedir,
398 $self->{utils}->_clean( $self->{utils}->_endpoint ),
399 $self->{utils}->SERVICES_CACHE,
400 $self->{utils}->UPDATE_FILE
401 );
402  
403 my $file = File::Spec->catfile(
404 $self->{utils}->cachedir,
405 $self->{utils}->_clean( $self->{utils}->_endpoint ),
406 $self->{utils}->SERVICES_CACHE,
407 $self->{utils}->RDF_FILE
408 );
409 my $dir = File::Spec->catfile(
410 $self->{utils}->cachedir,
411 $self->{utils}->_clean( $self->{utils}->_endpoint ),
412 $self->{utils}->SERVICES_CACHE
413 );
414  
415 open( LOCK, ">$lock" );
416 flock( LOCK, LOCK_EX );
417 eval {
418  
419 # check if we need to re-merge the RDF
420 my $isStale = $self->update_service_cache;
421 if ( $isStale or !( -e $file ) ) {
422
423 my $providers = $self->_get_service_providers;
424
425 # re-merge rdf
426 my $parser = XML::LibXML->new();
427 my $doc = undef;
428 opendir DIR, $dir
429 or die "Could not open directory for reading: $!\n";
430  
431 # foreach authority, parse the rdf - add to a single document
432 foreach my $RDF ( readdir DIR ) {
433 next if -d $RDF;
434 next
435 if $RDF eq $self->{utils}->RDF_FILE
436 or $RDF eq $self->{utils}->LIST_FILE
437 or $RDF eq $self->{utils}->UPDATE_FILE;
438 #remove those authorities that dont have any services
439 unlink(File::Spec->catfile( $dir, $RDF )) unless $providers->{$RDF};
440 do {
441 eval {
442 $doc =
443 $parser->parse_file(
444 File::Spec->catfile( $dir, $RDF ) );
445 };
446 warn $@ if $@;
447 # if it didnt parse correctly, reset to null
448 $doc = undef if $@;
449 next;
450 } unless $doc;
451 my $temp_doc = eval {
452 $parser->parse_file( File::Spec->catfile( $dir, $RDF ) );
453 };
454 warn $@ if $@;
455 next if $@;
456 foreach
457  
458 # here
459 my $service (
460 $temp_doc->findnodes('/rdf:RDF/rdf:Description') )
461 {
462 $doc->documentElement->appendChild($service);
463 }
464  
465 }
466 $xml = $doc->toString() if $doc;
467 $xml = new MOBY::RDF::Utils->empty_rdf unless $doc;
468  
469 # save new RDF file
470 open( FILE, ">$file" )
471 or die("Can't open file '$file' for writing: $!");
472 print FILE $xml;
473 close FILE;
474 } else {
475  
476 # send existing rdf
477 open( RDF_FILE, $file );
478 $xml = join "", <RDF_FILE>;
479 }
480 };
481 #flock( LOCK, LOCK_UN );
482 close(LOCK);
483 die $@ if $@;
484 return $xml;
485 }
486  
487 sub _get_service_providers {
488 my ($self) = @_;
489 my $soap =
490 SOAP::Lite->uri( $self->{utils}->_namespace )
491 ->proxy( $self->{utils}->_endpoint )->on_fault(
492 sub {
493 my $soap = shift;
494 my $res = shift;
495 die( "There was a problem calling the registry: "
496 . $self->{utils}->_endpoint . "\@ "
497 #. $self->{utils}->_namespace . ".\n"
498 . $res );
499 }
500 );
501  
502 my $xml = $soap->retrieveServiceProviders()->result;
503 my %providers = ();
504
505 my $parser = XML::LibXML->new();
506 my $doc = $parser->parse_string($xml);
507 my $nodes = $doc->documentElement()->getChildrenByTagName('serviceProvider');
508 for ( 1 .. $nodes->size() ) {
509 my $name = $nodes->get_node($_)->getAttribute('name');
510 next if $providers{$name};
511 $providers{$name} = 1;
512 }
513
514 return \%providers;
515
516 }
517  
518 # creates the list file and returns it as a string
519 sub _create_list_file {
520 my ($self) = @_;
521 my $soap =
522 SOAP::Lite->uri( $self->{utils}->_namespace )
523 ->proxy( $self->{utils}->_endpoint )->on_fault(
524 sub {
525 my $soap = shift;
526 my $res = shift;
527 die( "There was a problem calling the registry: "
528 . $self->{utils}->_endpoint . "\@ "
529 . $self->{utils}->_namespace . ".\n"
530 . $res );
531 }
532 );
533  
534 my $xml = $soap->retrieveServiceNames()->result;
535  
536 # create cache dirs as needed
537 $self->{utils}->create_cache_dirs;
538 my $file = File::Spec->catfile(
539 $self->{utils}->cachedir,
540 $self->{utils}->_clean( $self->{utils}->_endpoint ),
541 $self->{utils}->SERVICES_CACHE,
542 $self->{utils}->LIST_FILE
543 );
544 open( FILE, ">$file" )
545 or die("Can't open file '$file' for writing: $!");
546 print FILE $xml;
547 close FILE;
548
549 return $xml;
550  
551 }
552  
553 1;
554 __END__