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/;
10 use vars qw/%_paths $__json_js/;
12 { local $/ = undef; $__json_js = <DATA>; }
16 $logger->info("script_runner destroying self: $self");
21 $runner->context->destroy;
22 delete($$runner{$_}) for (keys %$runner);
28 $class = ref($class) || $class;
29 $params{paths} ||= [];
30 $params{reset_count} ||= 0;
32 my $self = bless { file => $params{file},
33 libs => $params{libs},
34 reset_count => $params{reset_count},
36 _path => {%_paths} } => $class;
38 $self->add_path($_) for @{$params{paths}};
43 my( $self, $context ) = @_;
44 $self->{ctx} = $context if $context;
50 $self->context( new JavaScript::SpiderMonkey );
51 $self->context->init();
55 # eating our own dog food with insert
56 $self->insert(log_stdout => sub { print "@_\n"; } );
57 $self->insert(log_stderr => sub { warn "@_\n"; } );
58 $self->insert(log_activity => sub { $logger->activity("script_runner: @_"); return 1;} );
59 $self->insert(log_error => sub { $logger->error("script_runner: @_"); return 1;} );
60 $self->insert(log_warn => sub { $logger->warn("script_runner: @_"); return 1;} );
61 $self->insert(log_info => sub { $logger->info("script_runner: @_"); return 1;} );
62 $self->insert(log_debug => sub { $logger->debug("script_runner: @_"); return 1;} );
63 $self->insert(log_internal => sub { $logger->internal("script_runner: @_"); return 1;} );
64 $self->insert(debug => sub { $logger->debug("script_runner: @_"); return 1;} );
65 $self->insert(alert => sub { $logger->warn("script_runner: @_"); return 1;} );
66 $self->insert(load_lib => sub { $self->load_lib(@_); return 1;});
68 # OpenSRF support functions
70 _OILS_FUNC_jsonopensrfrequest_send =>
71 sub { $self->_jsonopensrfrequest_send(@_); }
74 _OILS_FUNC_jsonopensrfrequest_connect =>
75 sub { $self->_jsonopensrfrequest_connect(@_); }
78 _OILS_FUNC_jsonopensrfrequest_disconnect =>
79 sub { $self->_jsonopensrfrequest_disconnect(@_); }
82 _OILS_FUNC_jsonopensrfrequest_finish =>
83 sub { $self->_jsonopensrfrequest_finish(@_); }
86 # XML support functions
88 _OILS_FUNC_xmlhttprequest_send =>
89 sub { $self->_xmlhttprequest_send(@_); }
92 _OILS_FUNC_xml_parse_string =>
93 sub { $self->_parse_xml_string(@_); }
96 while ( my $e = shift @{$self->{_env}} ) {
97 $self->insert( @$e{ qw/key value readonly/ } => 1 );
100 while ( my $e = shift @{$self->{_methods}} ) {
101 $self->insert_method( @$e{ qw/key name meth/ } => 1 );
104 $self->load_lib($_) for @{$self->{libs}};
109 sub refresh_context {
111 $logger->debug("Refreshing JavaScript Context...");
112 $self->context->destroy;
113 $logger->debug("Context destroyed");
114 $self->{_loaded} = {};
115 $logger->debug("Loaded scripts removed");
117 $logger->debug("New Context initialized");
122 my( $self, $filename ) = @_;
123 $self->{file} = $filename;
126 sub runs { shift()->{_runs} }
132 $self->{reset_count} = $count if ($count);
133 return $self->{reset_count};
143 $file = $self->{file};
146 $self->refresh_context
147 if ($self->reset_count && $self->runs > $self->reset_count);
149 $self->{_runs}++ if ($_real);
151 $file = $self->_find_file($file);
152 $logger->debug("full script file path: $file");
154 if( ! open(F, $file) ) {
155 $logger->error("Error opening script file: $file");
159 my $js = $self->context;
164 $self->insert('environment.result' => {});
167 #print ( "full script is [$content]" );
170 if( !$js || !$content || !$js->eval($content) ) {
171 $logger->error("$file Eval failed: $@");
174 $logger->debug("eval of $file took ". sprintf('%0.3f', time - $s) . " seconds");
177 $self->insert('__' => {'OILS_RESULT' => ''});
178 $js->eval($__json_js."__.OILS_RESULT = js2JSON(environment.result);");
179 $res = $self->retrieve('__.OILS_RESULT');
184 $logger->debug( "script result is [$res]" );
185 return JSON->JSON2perl( $res );
189 my( $self, $path ) = @_;
191 if ($self->{_path}{$path}) {
192 $self->{_path}{$path} = 0;
194 return $self->{_path}{$path};
196 if ($_paths{$path}) {
199 return $_paths{$path};
204 my( $self, $path ) = @_;
206 if (!$self->{_path}{$path}) {
207 $self->{_path}{$path} = 1;
210 if (!$_paths{$path}) {
220 for my $p ( keys %{ $self->{_path} } ) {
221 next unless ($self->{_path}{$p});
222 my $full = join('/',$p,$file);
223 return $full if (-e $full);
228 my( $self, $file ) = @_;
230 push @{ $self->{libs} }, $file
231 if (! grep {$_ eq $file} @{ $self->{libs} });
233 if (!$self->{_loaded}{$file}) {
235 $self->{_loaded}{$file} = 1;
237 return $self->{_loaded}{$file};
247 my( $self, $key ) = @_;
248 return $self->context->property_get($key);
252 my( $self, $obj_key, $meth_name, $sub, $stop) = @_;
254 push @{$self->{_methods}}, { key => $obj_key => name => $meth_name, meth => $sub } unless ($stop);
256 my $obj = $self->context->object_by_path( $obj_key );
257 $self->context->function_set( $meth_name, $sub, $obj ) if $obj;
262 my( $self, $key, $val, $RO, $stop ) = @_;
263 return unless defined($key);
265 push @{$self->{_env}}, { key => $key => value => $val, readonly => $RO } unless ($stop);
267 if (ref($val) =~ /^Fieldmapper/o) {
268 $self->insert_fm($key, $val, $RO);
269 } elsif (ref($val) and $val =~ /ARRAY/o) {
270 $self->insert_array($key, $val, $RO);
271 } elsif (ref($val) and $val =~ /HASH/o) {
272 $self->insert_hash($key, $val, $RO);
273 } elsif (ref($val) and $val =~ /CODE/o) {
274 $self->context->function_set( $key, $val );
275 } elsif (!ref($val)) {
276 if( defined($val) ) {
277 $self->context->property_by_path(
279 ( !$RO ? (sub { $val }, sub { my( $k, $v ) = @_; $val = $v; }) : () )
282 $self->context->property_by_path($key, "");
294 my( $self, $key, $fm, $RO ) = @_;
295 my $ctx = $self->context;
296 return undef unless ($ctx and $key and $fm);
297 my $o = $ctx->object_by_path($key);
299 for my $f ( $fm->properties ) {
302 $self->insert("$key.$f", $val);
304 $ctx->property_by_path(
309 my $k = _js_prop_name(shift());
313 my $k = _js_prop_name(shift());
326 my( $self, $key, $hash, $RO ) = @_;
327 my $ctx = $self->context;
328 return undef unless ($ctx and $key and $hash);
329 $ctx->object_by_path($key);
331 for my $k ( keys %$hash ) {
334 $self->insert("$key.$k", $v);
336 $ctx->property_by_path(
339 (sub { $hash->{_js_prop_name(shift())} },
341 my( $hashkey, $val ) = @_;
342 $hash->{_js_prop_name($hashkey)} = $val;
354 my( $self, $key, $array ) = @_;
355 my $ctx = $self->context;
356 return undef unless ($ctx and $key and $array);
358 my $a = $ctx->array_by_path($key);
361 for my $v ( @$array ) {
363 my $tmp_index = $__array_id++;
364 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$tmp_index);
365 $self->insert('__tmp_arr_el'.$tmp_index, $v);
366 $ctx->array_set_element_as_object( $a, $ind, $elobj );
368 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
374 sub _xmlhttprequest_send {
379 my $blocking = shift;
380 my $headerlist = shift;
383 my $ctx = $self->context;
385 # just so perl has access to it...
386 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
388 my $headers = new HTTP::Headers;
389 my @lines = split(/\n/so, $headerlist);
390 for my $line (@lines) {
391 if ($line =~ /^(.+?)|(.+)$/o) {
392 $headers->header($1 => $2);
396 my $ua = LWP::UserAgent->new;
397 $ua->agent("OpenILS/0.1");
399 my $req = HTTP::Request->new($method => $url => $headers => $data);
400 my $res = $ua->request($req);
402 if ($res->is_success) {
404 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
405 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
406 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
407 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
413 our %_jsonopensrfrequest_cache = ();
415 sub _jsonopensrfrequest_connect {
420 my $ctx = $self->context;
421 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
423 my $ses = $_jsonopensrfrequest_cache{$id} ||
424 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
427 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 1);
429 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 0);
433 sub _jsonopensrfrequest_disconnect {
437 my $ctx = $self->context;
438 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
440 my $ses = $_jsonopensrfrequest_cache{$id};
446 sub _jsonopensrfrequest_finish {
450 my $ctx = $self->context;
451 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
453 my $ses = $_jsonopensrfrequest_cache{$id};
457 delete $_jsonopensrfrequest_cache{$id};
460 sub _jsonopensrfrequest_send {
465 my $blocking = shift;
468 my @p = @{ JSON->JSON2perl($params) };
470 my $ctx = $self->context;
472 # just so perl has access to it...
473 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
475 my $ses = $_jsonopensrfrequest_cache{$id} ||
476 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
477 my $req = $ses->request($method,@p);
481 my $res = $req->recv->content;
483 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', JSON->perl2JSON($res));
484 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
485 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
486 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
489 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
490 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
491 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
492 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
499 sub _parse_xml_string {
508 $doc = XML::LibXML->new->parse_string( $string );
512 warn "Could not parse document: $e\n";
516 _JS_DOM($self->context, $key, $doc);
524 if ($node->nodeType == 9) {
525 $node = $node->documentElement;
527 my $n = $node->nodeName;
528 my $ns = $node->namespaceURI;
529 $ns =~ s/'/\'/gso if ($ns);
530 $ns = "'$ns'" if ($ns);
531 $ns = 'null' unless ($ns);
534 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
535 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
537 $key = $key.'.documentElement';
540 for my $a ($node->attributes) {
541 my $n = $a->nodeName;
545 #warn("$key.setAttribute('$n','$v');");
546 $ctx->eval("$key.setAttribute('$n','$v');");
551 for my $c ($node->childNodes) {
552 if ($c->nodeType == 1) {
553 my $n = $c->nodeName;
554 my $ns = $node->namespaceURI;
557 $ns =~ s/'/\'/gso if ($ns);
558 $ns = "'$ns'" if ($ns);
559 $ns = 'null' unless ($ns);
561 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
562 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
563 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
565 } elsif ($c->nodeType == 3) {
568 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
569 #warn("path is $key.item($k);");
570 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
572 } elsif ($c->nodeType == 4) {
575 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
576 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
578 } elsif ($c->nodeType == 8) {
581 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
582 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
585 warn "ACK! I don't know how to handle node type ".$c->nodeType;
601 // in case we run on an implimentation that doesn't have "undefined";
604 function Cast (obj, class_constructor) {
606 if (eval(class_constructor + '["_isfieldmapper"]')) {
607 obj = eval("new " + class_constructor + "(obj)");
616 function JSON2js (json) {
618 json = String(json).replace( /\/\*--\s*S\w*?\s*?\s+\w+\s*--\*\//g, 'Cast(');
619 json = String(json).replace( /\/\*--\s*E\w*?\s*?\s+(\w+)\s*--\*\//g, ', "$1")');
624 eval( 'obj = ' + json );
626 debug("Error building JSON object with string " + E + "\nString:\n" + json );
634 function object2Array(obj) {
635 if( obj == null ) return null;
637 var arr = new Array();
638 for( var i = 0; i < obj.length; i++ ) {
645 function js2JSON(arg) {
646 return _js2JSON(arg);
649 function _js2JSON(arg) {
652 switch (typeof arg) {
657 if (arg._isfieldmapper) { /* magi-c-ast for fieldmapper objects */
659 if( arg.a.constructor != Array ) {
660 var arr = new Array();
661 for( var i = 0; i < arg.a.length; i++ ) {
662 if( arg.a[i] == null ) {
663 arr[i] = null; continue;
666 if( typeof arg.a[i] != 'object' ) {
669 } else if( typeof arg.a[i] == 'object'
670 && arg.a[i]._isfieldmapper) {
675 arr[i] = object2Array(arg.a[i]);
681 return "/*--S " + arg.classname + " --*/" + js2JSON(arg.a) + "/*--E " + arg.classname + " --*/";
685 if (arg.constructor == Array) {
687 for (i = 0; i < arg.length; ++i) {
698 return '[' + o + ']';
700 } else if (typeof arg.toString != 'undefined') {
708 o += js2JSON(i) + ':' + v;
724 if( isNaN(arg) ) throw "JSON.js encountered NaN in js2JSON()";
733 return '"' + String(arg).replace(/(["\\])/g, '\\$1') + '"';