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>; }
17 $class = ref($class) || $class;
18 $params{paths} ||= [];
19 $params{reset_count} ||= 0;
21 my $self = bless { file => $params{file},
22 libs => $params{libs},
23 reset_count => $params{reset_count},
25 _path => {%_paths} } => $class;
27 $self->add_path($_) for @{$params{paths}};
32 my( $self, $context ) = @_;
33 $self->{ctx} = $context if $context;
39 $self->context( new JavaScript::SpiderMonkey );
40 $self->context->init();
44 # eating our own dog food with insert
45 $self->insert(log_stdout => sub { print "@_\n"; } );
46 $self->insert(log_stderr => 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(@_); return 1;});
57 # OpenSRF support functions
59 _OILS_FUNC_jsonopensrfrequest_send =>
60 sub { $self->_jsonopensrfrequest_send(@_); }
63 _OILS_FUNC_jsonopensrfrequest_connect =>
64 sub { $self->_jsonopensrfrequest_connect(@_); }
67 _OILS_FUNC_jsonopensrfrequest_disconnect =>
68 sub { $self->_jsonopensrfrequest_disconnect(@_); }
71 _OILS_FUNC_jsonopensrfrequest_finish =>
72 sub { $self->_jsonopensrfrequest_finish(@_); }
75 # XML support functions
77 _OILS_FUNC_xmlhttprequest_send =>
78 sub { $self->_xmlhttprequest_send(@_); }
81 _OILS_FUNC_xml_parse_string =>
82 sub { $self->_parse_xml_string(@_); }
85 for my $e ( @{$self->{_env}} ) {
86 $self->insert( @$e{ qw/key value readonly/ } => 1 );
89 for my $e ( @{$self->{_methods}} ) {
90 $self->insert_method( @$e{ qw/key name meth/ } => 1 );
93 $self->load_lib($_) for @{$self->{libs}};
100 $logger->debug("Refreshing JavaScript Context...");
101 $self->context->destroy;
102 $logger->debug("Context destroyed");
103 $self->{_loaded} = {};
104 $logger->debug("Loaded scripts removed");
106 $logger->debug("New Context initialized");
111 my( $self, $filename ) = @_;
112 $self->{file} = $filename;
115 sub runs { shift()->{_runs} }
121 $self->{reset_count} = $count if ($count);
122 return $self->{reset_count};
132 $file = $self->{file};
135 $self->refresh_context
136 if ($self->reset_count && $self->runs > $self->reset_count);
138 $self->{_runs}++ if ($_real);
140 $file = $self->_find_file($file);
141 $logger->debug("full script file path: $file");
143 if( ! open(F, $file) ) {
144 $logger->error("Error opening script file: $file");
148 my $js = $self->context;
153 $self->insert('environment.result' => {});
156 #print ( "full script is [$content]" );
159 if( !$js || !$content || !$js->eval($content) ) {
160 $logger->error("$file Eval failed: $@");
163 $logger->debug("eval of $file took ". sprintf('%0.3f', time - $s) . " seconds");
166 $self->insert('__' => {'OILS_RESULT' => ''});
167 $js->eval($__json_js."__.OILS_RESULT = js2JSON(environment.result);");
168 $res = $self->retrieve('__.OILS_RESULT');
173 $logger->debug( "script result is [$res]" );
174 return JSON->JSON2perl( $res );
178 my( $self, $path ) = @_;
180 if ($self->{_path}{$path}) {
181 $self->{_path}{$path} = 0;
183 return $self->{_path}{$path};
185 if ($_paths{$path}) {
188 return $_paths{$path};
193 my( $self, $path ) = @_;
195 if (!$self->{_path}{$path}) {
196 $self->{_path}{$path} = 1;
199 if (!$_paths{$path}) {
209 for my $p ( keys %{ $self->{_path} } ) {
210 next unless ($self->{_path}{$p});
211 my $full = join('/',$p,$file);
212 return $full if (-e $full);
217 my( $self, $file ) = @_;
219 push @{ $self->{libs} }, $file
220 if (! grep {$_ eq $file} @{ $self->{libs} });
222 if (!$self->{_loaded}{$file}) {
224 $self->{_loaded}{$file} = 1;
226 return $self->{_loaded}{$file};
236 my( $self, $key ) = @_;
237 return $self->context->property_get($key);
241 my( $self, $obj_key, $meth_name, $sub, $stop) = @_;
243 push @{$self->{_methods}}, { key => $obj_key => name => $meth_name, meth => $sub } unless ($stop);
245 my $obj = $self->context->object_by_path( $obj_key );
246 $self->context->function_set( $meth_name, $sub, $obj ) if $obj;
251 my( $self, $key, $val, $RO, $stop ) = @_;
252 return unless defined($key);
254 push @{$self->{_env}}, { key => $key => value => $val, readonly => $RO } unless ($stop);
256 if (ref($val) =~ /^Fieldmapper/o) {
257 $self->insert_fm($key, $val, $RO);
258 } elsif (ref($val) and $val =~ /ARRAY/o) {
259 $self->insert_array($key, $val, $RO);
260 } elsif (ref($val) and $val =~ /HASH/o) {
261 $self->insert_hash($key, $val, $RO);
262 } elsif (ref($val) and $val =~ /CODE/o) {
263 $self->context->function_set( $key, $val );
264 } elsif (!ref($val)) {
265 if( defined($val) ) {
266 $self->context->property_by_path(
270 sub { my( $k, $v ) = @_; $val = $v; } :
275 $self->context->property_by_path($key, "");
287 my( $self, $key, $fm, $RO ) = @_;
288 my $ctx = $self->context;
289 return undef unless ($ctx and $key and $fm);
290 my $o = $ctx->object_by_path($key);
292 for my $f ( $fm->properties ) {
295 $self->insert("$key.$f", $val);
297 $ctx->property_by_path(
301 my $k = _js_prop_name(shift());
307 my $k = _js_prop_name(shift());
320 my( $self, $key, $hash, $RO ) = @_;
321 my $ctx = $self->context;
322 return undef unless ($ctx and $key and $hash);
323 $ctx->object_by_path($key);
325 for my $k ( keys %$hash ) {
328 $self->insert("$key.$k", $v);
330 $ctx->property_by_path(
332 sub { $hash->{_js_prop_name(shift())} },
335 my( $hashkey, $val ) = @_;
336 $hash->{_js_prop_name($hashkey)} = $val;
348 my( $self, $key, $array ) = @_;
349 my $ctx = $self->context;
350 return undef unless ($ctx and $key and $array);
352 my $a = $ctx->array_by_path($key);
355 for my $v ( @$array ) {
357 my $tmp_index = $__array_id++;
358 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$tmp_index);
359 $self->insert('__tmp_arr_el'.$tmp_index, $v);
360 $ctx->array_set_element_as_object( $a, $ind, $elobj );
362 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
368 sub _xmlhttprequest_send {
373 my $blocking = shift;
374 my $headerlist = shift;
377 my $ctx = $self->context;
379 # just so perl has access to it...
380 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
382 my $headers = new HTTP::Headers;
383 my @lines = split(/\n/so, $headerlist);
384 for my $line (@lines) {
385 if ($line =~ /^(.+?)|(.+)$/o) {
386 $headers->header($1 => $2);
390 my $ua = LWP::UserAgent->new;
391 $ua->agent("OpenILS/0.1");
393 my $req = HTTP::Request->new($method => $url => $headers => $data);
394 my $res = $ua->request($req);
396 if ($res->is_success) {
398 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
399 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
400 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
401 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
407 our %_jsonopensrfrequest_cache = ();
409 sub _jsonopensrfrequest_connect {
414 my $ctx = $self->context;
415 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
417 my $ses = $_jsonopensrfrequest_cache{$id} ||
418 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
421 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 1);
423 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 0);
427 sub _jsonopensrfrequest_disconnect {
431 my $ctx = $self->context;
432 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
434 my $ses = $_jsonopensrfrequest_cache{$id};
440 sub _jsonopensrfrequest_finish {
444 my $ctx = $self->context;
445 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
447 my $ses = $_jsonopensrfrequest_cache{$id};
451 delete $_jsonopensrfrequest_cache{$id};
454 sub _jsonopensrfrequest_send {
459 my $blocking = shift;
462 my @p = @{ JSON->JSON2perl($params) };
464 my $ctx = $self->context;
466 # just so perl has access to it...
467 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
469 my $ses = $_jsonopensrfrequest_cache{$id} ||
470 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
471 my $req = $ses->request($method,@p);
475 my $res = $req->recv->content;
477 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', JSON->perl2JSON($res));
478 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
479 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
480 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
483 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
484 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
485 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
486 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
493 sub _parse_xml_string {
502 $doc = XML::LibXML->new->parse_string( $string );
506 warn "Could not parse document: $e\n";
510 _JS_DOM($self->context, $key, $doc);
518 if ($node->nodeType == 9) {
519 $node = $node->documentElement;
521 my $n = $node->nodeName;
522 my $ns = $node->namespaceURI;
523 $ns =~ s/'/\'/gso if ($ns);
524 $ns = "'$ns'" if ($ns);
525 $ns = 'null' unless ($ns);
528 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
529 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
531 $key = $key.'.documentElement';
534 for my $a ($node->attributes) {
535 my $n = $a->nodeName;
539 #warn("$key.setAttribute('$n','$v');");
540 $ctx->eval("$key.setAttribute('$n','$v');");
545 for my $c ($node->childNodes) {
546 if ($c->nodeType == 1) {
547 my $n = $c->nodeName;
548 my $ns = $node->namespaceURI;
551 $ns =~ s/'/\'/gso if ($ns);
552 $ns = "'$ns'" if ($ns);
553 $ns = 'null' unless ($ns);
555 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
556 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
557 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
559 } elsif ($c->nodeType == 3) {
562 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
563 #warn("path is $key.item($k);");
564 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
566 } elsif ($c->nodeType == 4) {
569 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
570 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
572 } elsif ($c->nodeType == 8) {
575 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
576 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
579 warn "ACK! I don't know how to handle node type ".$c->nodeType;
595 // in case we run on an implimentation that doesn't have "undefined";
598 function Cast (obj, class_constructor) {
600 if (eval(class_constructor + '["_isfieldmapper"]')) {
601 obj = eval("new " + class_constructor + "(obj)");
610 function JSON2js (json) {
612 json = String(json).replace( /\/\*--\s*S\w*?\s*?\s+\w+\s*--\*\//g, 'Cast(');
613 json = String(json).replace( /\/\*--\s*E\w*?\s*?\s+(\w+)\s*--\*\//g, ', "$1")');
618 eval( 'obj = ' + json );
620 debug("Error building JSON object with string " + E + "\nString:\n" + json );
628 function object2Array(obj) {
629 if( obj == null ) return null;
631 var arr = new Array();
632 for( var i = 0; i < obj.length; i++ ) {
639 function js2JSON(arg) {
640 return _js2JSON(arg);
643 function _js2JSON(arg) {
646 switch (typeof arg) {
651 if (arg._isfieldmapper) { /* magi-c-ast for fieldmapper objects */
653 if( arg.a.constructor != Array ) {
654 var arr = new Array();
655 for( var i = 0; i < arg.a.length; i++ ) {
656 if( arg.a[i] == null ) {
657 arr[i] = null; continue;
660 if( typeof arg.a[i] != 'object' ) {
663 } else if( typeof arg.a[i] == 'object'
664 && arg.a[i]._isfieldmapper) {
669 arr[i] = object2Array(arg.a[i]);
675 return "/*--S " + arg.classname + " --*/" + js2JSON(arg.a) + "/*--E " + arg.classname + " --*/";
679 if (arg.constructor == Array) {
681 for (i = 0; i < arg.length; ++i) {
692 return '[' + o + ']';
694 } else if (typeof arg.toString != 'undefined') {
702 o += js2JSON(i) + ':' + v;
718 if( isNaN(arg) ) throw "JSON.js encountered NaN in js2JSON()";
727 return '"' + String(arg).replace(/(["\\])/g, '\\$1') + '"';