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 @_; } );
47 $self->insert(log_activity => sub { $logger->activity(@_); return 1;} );
48 $self->insert(log_error => sub { $logger->error(@_); return 1;} );
49 $self->insert(log_warn => sub { $logger->warn(@_); return 1;} );
50 $self->insert(log_info => sub { $logger->info(@_); return 1;} );
51 $self->insert(log_debug => sub { $logger->debug(@_); return 1;} );
52 $self->insert(log_internal => sub { $logger->internal(@_); return 1;} );
53 $self->insert(debug => sub { $logger->debug(@_); return 1;} );
54 $self->insert(alert => sub { $logger->warn(@_); 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;
105 $self->refresh_context
106 if ($self->reset_count && $self->runs > $self->reset_count);
110 $file = $self->_find_file($file);
112 if( ! open(F, $file) ) {
113 $logger->error("Error opening script file: $file");
120 if( !$js || !$content || !$js->eval($content) ) {
121 $logger->error("$file Eval failed: $@");
124 $logger->debug("eval of $file took ". sprintf('%0.3f', time - $s) . " seconds");
132 my( $self, $path ) = @_;
134 if ($self->{_path}{$path}) {
135 $self->{_path}{$path} = 0;
137 return $self->{_path}{$path};
139 if ($_paths{$path}) {
142 return $_paths{$path};
147 my( $self, $path ) = @_;
149 if (!$self->{_path}{$path}) {
150 $self->{_path}{$path} = 1;
153 if (!$_paths{$path}) {
163 for my $p ( keys %{ $self->{_path} } ) {
164 next unless ($self->{_path}{$p});
165 my $full = join('/',$p,$file);
166 return $full if (-e $full);
171 my( $self, $file ) = @_;
173 push @{ $self->{libs} }, $file
174 if (! grep {$_ eq $file} @{ $self->{libs} });
176 if (!$self->{_loaded}{$file} && $self->run( $file )) {
177 $self->{_loaded}{$file} = 1;
179 return $self->{_loaded}{$file};
189 my( $self, $key ) = @_;
190 return $self->context->property_get($key);
194 my( $self, $obj_key, $meth_name, $sub ) = @_;
195 my $obj = $self->context->object_by_path( $obj_key );
196 $self->context->function_set( $meth_name, $sub, $obj ) if $obj;
201 my( $self, $key, $val, $RO ) = @_;
202 return unless defined($key);
204 if (ref($val) =~ /^Fieldmapper/o) {
205 $self->insert_fm($key, $val, $RO);
206 } elsif (ref($val) and $val =~ /ARRAY/o) {
207 $self->insert_array($key, $val, $RO);
208 } elsif (ref($val) and $val =~ /HASH/o) {
209 $self->insert_hash($key, $val, $RO);
210 } elsif (ref($val) and $val =~ /CODE/o) {
211 $self->context->function_set( $key, $val );
212 } elsif (!ref($val)) {
213 if( defined($val) ) {
214 $self->context->property_by_path(
218 sub { my( $k, $v ) = @_; $val = $v; } :
223 $self->context->property_by_path($key, "");
235 my( $self, $key, $fm, $RO ) = @_;
236 my $ctx = $self->context;
237 return undef unless ($ctx and $key and $fm);
238 my $o = $ctx->object_by_path($key);
240 for my $f ( $fm->properties ) {
243 $self->insert("$key.$f", $val);
245 $ctx->property_by_path(
249 my $k = _js_prop_name(shift());
255 my $k = _js_prop_name(shift());
268 my( $self, $key, $hash, $RO ) = @_;
269 my $ctx = $self->context;
270 return undef unless ($ctx and $key and $hash);
271 $ctx->object_by_path($key);
273 for my $k ( keys %$hash ) {
276 $self->insert("$key.$k", $v);
278 $ctx->property_by_path(
280 sub { $hash->{_js_prop_name(shift())} },
283 my( $hashkey, $val ) = @_;
284 $hash->{_js_prop_name($hashkey)} = $val;
296 my( $self, $key, $array ) = @_;
297 my $ctx = $self->context;
298 return undef unless ($ctx and $key and $array);
300 my $a = $ctx->array_by_path($key);
303 for my $v ( @$array ) {
305 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$__array_id);
306 $self->insert('__tmp_arr_el'.$__array_id, $v);
307 $ctx->array_set_element_as_object( $a, $ind, $elobj );
310 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
316 sub _xmlhttprequest_send {
321 my $blocking = shift;
322 my $headerlist = shift;
325 my $ctx = $self->context;
327 # just so perl has access to it...
328 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
330 my $headers = new HTTP::Headers;
331 my @lines = split(/\n/so, $headerlist);
332 for my $line (@lines) {
333 if ($line =~ /^(.+?)|(.+)$/o) {
334 $headers->header($1 => $2);
338 my $ua = LWP::UserAgent->new;
339 $ua->agent("OpenILS/0.1");
341 my $req = HTTP::Request->new($method => $url => $headers => $data);
342 my $res = $ua->request($req);
344 if ($res->is_success) {
346 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
347 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
348 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
349 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
355 sub _jsonopensrfrequest_send {
360 my $blocking = shift;
363 my @p = @{ JSON->JSON2perl($params) };
365 my $ctx = $self->context;
367 # just so perl has access to it...
368 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
370 my $ses = OpenSRF::AppSession->create($service);
371 my $req = $ses->request($method,@p);
375 my $res = $req->content;
377 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', $res);
378 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
379 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
380 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
383 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
384 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
385 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
386 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
393 sub _parse_xml_string {
402 $doc = XML::LibXML->new->parse_string( $string );
406 warn "Could not parse document: $e\n";
410 _JS_DOM($self->context, $key, $doc);
418 if ($node->nodeType == 9) {
419 $node = $node->documentElement;
421 my $n = $node->nodeName;
422 my $ns = $node->namespaceURI;
423 $ns =~ s/'/\'/gso if ($ns);
424 $ns = "'$ns'" if ($ns);
425 $ns = 'null' unless ($ns);
428 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
429 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
431 $key = $key.'.documentElement';
434 for my $a ($node->attributes) {
435 my $n = $a->nodeName;
439 #warn("$key.setAttribute('$n','$v');");
440 $ctx->eval("$key.setAttribute('$n','$v');");
445 for my $c ($node->childNodes) {
446 if ($c->nodeType == 1) {
447 my $n = $c->nodeName;
448 my $ns = $node->namespaceURI;
451 $ns =~ s/'/\'/gso if ($ns);
452 $ns = "'$ns'" if ($ns);
453 $ns = 'null' unless ($ns);
455 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
456 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
457 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
459 } elsif ($c->nodeType == 3) {
462 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
463 #warn("path is $key.item($k);");
464 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
466 } elsif ($c->nodeType == 4) {
469 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
470 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
472 } elsif ($c->nodeType == 8) {
475 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
476 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
479 warn "ACK! I don't know how to handle node type ".$c->nodeType;