1 package OpenILS::Utils::ScriptRunner;
2 use strict; use warnings;
3 use OpenSRF::Utils::Logger qw(:logger);
4 use OpenSRF::EX qw(:try);
6 use JavaScript::SpiderMonkey;
9 use Time::HiRes qw/time/;
16 $class = ref($class) || $class;
17 $params{paths} ||= [];
18 $params{reset_count} ||= 0;
20 my $self = bless { file => $params{file},
21 libs => $params{libs},
22 reset_count => $params{reset_count},
24 _path => {%_paths} } => $class;
26 $self->add_path($_) for @{$params{paths}};
31 my( $self, $context ) = @_;
32 $self->{ctx} = $context if $context;
38 $self->context( new JavaScript::SpiderMonkey );
39 $self->context->init();
44 # eating our own dog food with insert
45 $self->insert(perl_print => sub { print "@_\n"; } );
46 $self->insert(perl_warn => sub { warn "@_\n"; } );
47 $self->insert(log_activity => sub { $logger->activity("script_runner: @_"); return 1;} );
48 $self->insert(log_error => sub { $logger->error("script_runner: @_"); return 1;} );
49 $self->insert(log_warn => sub { $logger->warn("script_runner: @_"); return 1;} );
50 $self->insert(log_info => sub { $logger->info("script_runner: @_"); return 1;} );
51 $self->insert(log_debug => sub { $logger->debug("script_runner: @_"); return 1;} );
52 $self->insert(log_internal => sub { $logger->internal("script_runner: @_"); return 1;} );
53 $self->insert(debug => sub { $logger->debug("script_runner: @_"); return 1;} );
54 $self->insert(alert => sub { $logger->warn("script_runner: @_"); return 1;} );
55 $self->insert(load_lib => sub { $self->load_lib(@_); });
57 # OpenSRF support function
59 _OILS_FUNC_jsonopensrfrequest_send =>
60 sub { $self->_jsonopensrfrequest_send(@_); }
63 # XML support functions
65 _OILS_FUNC_xmlhttprequest_send =>
66 sub { $self->_xmlhttprequest_send(@_); }
69 _OILS_FUNC_xml_parse_string =>
70 sub { $self->_parse_xml_string(@_); }
73 $self->load_lib($_) for @{$self->{libs}};
80 $self->context->destroy;
81 $self->{_loaded} = {};
86 my( $self, $filename ) = @_;
87 $self->{file} = $filename;
90 sub runs { shift()->{_runs} }
96 $self->{reset_count} = $count if ($count);
97 return $self->{reset_count};
102 my $file = shift() || $self->{file};
103 my $js = $self->context;
107 $self->refresh_context
108 if ($self->reset_count && $self->runs > $self->reset_count);
112 $file = $self->_find_file($file);
113 $logger->debug("full script file path: $file");
115 if( ! open(F, $file) ) {
116 $logger->error("Error opening script file: $file");
123 if( !$js || !$content || !$js->eval($content) ) {
124 $logger->error("$file Eval failed: $@");
127 $logger->debug("eval of $file took ". sprintf('%0.3f', time - $s) . " seconds");
135 my( $self, $path ) = @_;
137 if ($self->{_path}{$path}) {
138 $self->{_path}{$path} = 0;
140 return $self->{_path}{$path};
142 if ($_paths{$path}) {
145 return $_paths{$path};
150 my( $self, $path ) = @_;
152 if (!$self->{_path}{$path}) {
153 $self->{_path}{$path} = 1;
156 if (!$_paths{$path}) {
166 for my $p ( keys %{ $self->{_path} } ) {
167 next unless ($self->{_path}{$p});
168 my $full = join('/',$p,$file);
169 return $full if (-e $full);
174 my( $self, $file ) = @_;
176 push @{ $self->{libs} }, $file
177 if (! grep {$_ eq $file} @{ $self->{libs} });
179 if (!$self->{_loaded}{$file} && $self->run( $file )) {
180 $self->{_loaded}{$file} = 1;
182 return $self->{_loaded}{$file};
192 my( $self, $key ) = @_;
193 return $self->context->property_get($key);
197 my( $self, $obj_key, $meth_name, $sub ) = @_;
198 my $obj = $self->context->object_by_path( $obj_key );
199 $self->context->function_set( $meth_name, $sub, $obj ) if $obj;
204 my( $self, $key, $val, $RO ) = @_;
205 return unless defined($key);
207 if (ref($val) =~ /^Fieldmapper/o) {
208 $self->insert_fm($key, $val, $RO);
209 } elsif (ref($val) and $val =~ /ARRAY/o) {
210 $self->insert_array($key, $val, $RO);
211 } elsif (ref($val) and $val =~ /HASH/o) {
212 $self->insert_hash($key, $val, $RO);
213 } elsif (ref($val) and $val =~ /CODE/o) {
214 $self->context->function_set( $key, $val );
215 } elsif (!ref($val)) {
216 if( defined($val) ) {
217 $self->context->property_by_path(
221 sub { my( $k, $v ) = @_; $val = $v; } :
226 $self->context->property_by_path($key, "");
238 my( $self, $key, $fm, $RO ) = @_;
239 my $ctx = $self->context;
240 return undef unless ($ctx and $key and $fm);
241 my $o = $ctx->object_by_path($key);
243 for my $f ( $fm->properties ) {
246 $self->insert("$key.$f", $val);
248 $ctx->property_by_path(
252 my $k = _js_prop_name(shift());
258 my $k = _js_prop_name(shift());
271 my( $self, $key, $hash, $RO ) = @_;
272 my $ctx = $self->context;
273 return undef unless ($ctx and $key and $hash);
274 $ctx->object_by_path($key);
276 for my $k ( keys %$hash ) {
279 $self->insert("$key.$k", $v);
281 $ctx->property_by_path(
283 sub { $hash->{_js_prop_name(shift())} },
286 my( $hashkey, $val ) = @_;
287 $hash->{_js_prop_name($hashkey)} = $val;
299 my( $self, $key, $array ) = @_;
300 my $ctx = $self->context;
301 return undef unless ($ctx and $key and $array);
303 my $a = $ctx->array_by_path($key);
306 for my $v ( @$array ) {
308 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$__array_id);
309 $self->insert('__tmp_arr_el'.$__array_id, $v);
310 $ctx->array_set_element_as_object( $a, $ind, $elobj );
313 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
319 sub _xmlhttprequest_send {
324 my $blocking = shift;
325 my $headerlist = shift;
328 my $ctx = $self->context;
330 # just so perl has access to it...
331 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
333 my $headers = new HTTP::Headers;
334 my @lines = split(/\n/so, $headerlist);
335 for my $line (@lines) {
336 if ($line =~ /^(.+?)|(.+)$/o) {
337 $headers->header($1 => $2);
341 my $ua = LWP::UserAgent->new;
342 $ua->agent("OpenILS/0.1");
344 my $req = HTTP::Request->new($method => $url => $headers => $data);
345 my $res = $ua->request($req);
347 if ($res->is_success) {
349 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
350 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
351 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
352 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
358 sub _jsonopensrfrequest_send {
363 my $blocking = shift;
366 my @p = @{ JSON->JSON2perl($params) };
368 my $ctx = $self->context;
370 # just so perl has access to it...
371 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
373 my $ses = OpenSRF::AppSession->create($service);
374 my $req = $ses->request($method,@p);
378 my $res = $req->content;
380 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', $res);
381 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
382 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
383 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
386 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
387 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
388 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
389 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
396 sub _parse_xml_string {
405 $doc = XML::LibXML->new->parse_string( $string );
409 warn "Could not parse document: $e\n";
413 _JS_DOM($self->context, $key, $doc);
421 if ($node->nodeType == 9) {
422 $node = $node->documentElement;
424 my $n = $node->nodeName;
425 my $ns = $node->namespaceURI;
426 $ns =~ s/'/\'/gso if ($ns);
427 $ns = "'$ns'" if ($ns);
428 $ns = 'null' unless ($ns);
431 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
432 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
434 $key = $key.'.documentElement';
437 for my $a ($node->attributes) {
438 my $n = $a->nodeName;
442 #warn("$key.setAttribute('$n','$v');");
443 $ctx->eval("$key.setAttribute('$n','$v');");
448 for my $c ($node->childNodes) {
449 if ($c->nodeType == 1) {
450 my $n = $c->nodeName;
451 my $ns = $node->namespaceURI;
454 $ns =~ s/'/\'/gso if ($ns);
455 $ns = "'$ns'" if ($ns);
456 $ns = 'null' unless ($ns);
458 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
459 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
460 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
462 } elsif ($c->nodeType == 3) {
465 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
466 #warn("path is $key.item($k);");
467 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
469 } elsif ($c->nodeType == 4) {
472 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
473 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
475 } elsif ($c->nodeType == 8) {
478 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
479 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
482 warn "ACK! I don't know how to handle node type ".$c->nodeType;