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 $self->load_lib($_) for @{$self->{libs}};
92 $self->context->destroy;
93 $self->{_loaded} = {};
98 my( $self, $filename ) = @_;
99 $self->{file} = $filename;
102 sub runs { shift()->{_runs} }
108 $self->{reset_count} = $count if ($count);
109 return $self->{reset_count};
119 $file = $self->{file};
122 my $js = $self->context;
126 $self->refresh_context
127 if ($self->reset_count && $self->runs > $self->reset_count);
131 $file = $self->_find_file($file);
132 $logger->debug("full script file path: $file");
134 if( ! open(F, $file) ) {
135 $logger->error("Error opening script file: $file");
142 $self->insert('environment.result' => {});
145 #print ( "full script is [$content]" );
148 if( !$js || !$content || !$js->eval($content) ) {
149 $logger->error("$file Eval failed: $@");
152 $logger->debug("eval of $file took ". sprintf('%0.3f', time - $s) . " seconds");
155 $self->insert('__' => {'OILS_RESULT' => ''});
156 $js->eval($__json_js."__.OILS_RESULT = js2JSON(environment.result);");
157 $res = $self->retrieve('__.OILS_RESULT');
162 $logger->debug( "script result is [$res]" );
163 return JSON->JSON2perl( $res );
167 my( $self, $path ) = @_;
169 if ($self->{_path}{$path}) {
170 $self->{_path}{$path} = 0;
172 return $self->{_path}{$path};
174 if ($_paths{$path}) {
177 return $_paths{$path};
182 my( $self, $path ) = @_;
184 if (!$self->{_path}{$path}) {
185 $self->{_path}{$path} = 1;
188 if (!$_paths{$path}) {
198 for my $p ( keys %{ $self->{_path} } ) {
199 next unless ($self->{_path}{$p});
200 my $full = join('/',$p,$file);
201 return $full if (-e $full);
206 my( $self, $file ) = @_;
208 push @{ $self->{libs} }, $file
209 if (! grep {$_ eq $file} @{ $self->{libs} });
211 if (!$self->{_loaded}{$file} && $self->run( $file )) {
212 $self->{_loaded}{$file} = 1;
214 return $self->{_loaded}{$file};
224 my( $self, $key ) = @_;
225 return $self->context->property_get($key);
229 my( $self, $obj_key, $meth_name, $sub ) = @_;
230 my $obj = $self->context->object_by_path( $obj_key );
231 $self->context->function_set( $meth_name, $sub, $obj ) if $obj;
236 my( $self, $key, $val, $RO ) = @_;
237 return unless defined($key);
239 if (ref($val) =~ /^Fieldmapper/o) {
240 $self->insert_fm($key, $val, $RO);
241 } elsif (ref($val) and $val =~ /ARRAY/o) {
242 $self->insert_array($key, $val, $RO);
243 } elsif (ref($val) and $val =~ /HASH/o) {
244 $self->insert_hash($key, $val, $RO);
245 } elsif (ref($val) and $val =~ /CODE/o) {
246 $self->context->function_set( $key, $val );
247 } elsif (!ref($val)) {
248 if( defined($val) ) {
249 $self->context->property_by_path(
253 sub { my( $k, $v ) = @_; $val = $v; } :
258 $self->context->property_by_path($key, "");
270 my( $self, $key, $fm, $RO ) = @_;
271 my $ctx = $self->context;
272 return undef unless ($ctx and $key and $fm);
273 my $o = $ctx->object_by_path($key);
275 for my $f ( $fm->properties ) {
278 $self->insert("$key.$f", $val);
280 $ctx->property_by_path(
284 my $k = _js_prop_name(shift());
290 my $k = _js_prop_name(shift());
303 my( $self, $key, $hash, $RO ) = @_;
304 my $ctx = $self->context;
305 return undef unless ($ctx and $key and $hash);
306 $ctx->object_by_path($key);
308 for my $k ( keys %$hash ) {
311 $self->insert("$key.$k", $v);
313 $ctx->property_by_path(
315 sub { $hash->{_js_prop_name(shift())} },
318 my( $hashkey, $val ) = @_;
319 $hash->{_js_prop_name($hashkey)} = $val;
331 my( $self, $key, $array ) = @_;
332 my $ctx = $self->context;
333 return undef unless ($ctx and $key and $array);
335 my $a = $ctx->array_by_path($key);
338 for my $v ( @$array ) {
340 my $tmp_index = $__array_id++;
341 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$tmp_index);
342 $self->insert('__tmp_arr_el'.$tmp_index, $v);
343 $ctx->array_set_element_as_object( $a, $ind, $elobj );
345 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
351 sub _xmlhttprequest_send {
356 my $blocking = shift;
357 my $headerlist = shift;
360 my $ctx = $self->context;
362 # just so perl has access to it...
363 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
365 my $headers = new HTTP::Headers;
366 my @lines = split(/\n/so, $headerlist);
367 for my $line (@lines) {
368 if ($line =~ /^(.+?)|(.+)$/o) {
369 $headers->header($1 => $2);
373 my $ua = LWP::UserAgent->new;
374 $ua->agent("OpenILS/0.1");
376 my $req = HTTP::Request->new($method => $url => $headers => $data);
377 my $res = $ua->request($req);
379 if ($res->is_success) {
381 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
382 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
383 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
384 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
390 our %_jsonopensrfrequest_cache = ();
392 sub _jsonopensrfrequest_connect {
397 my $ctx = $self->context;
398 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
400 my $ses = $_jsonopensrfrequest_cache{$id} ||
401 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
404 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 1);
406 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 0);
410 sub _jsonopensrfrequest_disconnect {
414 my $ctx = $self->context;
415 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
417 my $ses = $_jsonopensrfrequest_cache{$id};
423 sub _jsonopensrfrequest_finish {
427 my $ctx = $self->context;
428 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
430 my $ses = $_jsonopensrfrequest_cache{$id};
434 delete $_jsonopensrfrequest_cache{$id};
437 sub _jsonopensrfrequest_send {
442 my $blocking = shift;
445 my @p = @{ JSON->JSON2perl($params) };
447 my $ctx = $self->context;
449 # just so perl has access to it...
450 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
452 my $ses = $_jsonopensrfrequest_cache{$id} ||
453 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
454 my $req = $ses->request($method,@p);
458 my $res = $req->recv->content;
460 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', JSON->perl2JSON($res));
461 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
462 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
463 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
466 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
467 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
468 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
469 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
476 sub _parse_xml_string {
485 $doc = XML::LibXML->new->parse_string( $string );
489 warn "Could not parse document: $e\n";
493 _JS_DOM($self->context, $key, $doc);
501 if ($node->nodeType == 9) {
502 $node = $node->documentElement;
504 my $n = $node->nodeName;
505 my $ns = $node->namespaceURI;
506 $ns =~ s/'/\'/gso if ($ns);
507 $ns = "'$ns'" if ($ns);
508 $ns = 'null' unless ($ns);
511 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
512 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
514 $key = $key.'.documentElement';
517 for my $a ($node->attributes) {
518 my $n = $a->nodeName;
522 #warn("$key.setAttribute('$n','$v');");
523 $ctx->eval("$key.setAttribute('$n','$v');");
528 for my $c ($node->childNodes) {
529 if ($c->nodeType == 1) {
530 my $n = $c->nodeName;
531 my $ns = $node->namespaceURI;
534 $ns =~ s/'/\'/gso if ($ns);
535 $ns = "'$ns'" if ($ns);
536 $ns = 'null' unless ($ns);
538 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
539 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
540 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
542 } elsif ($c->nodeType == 3) {
545 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
546 #warn("path is $key.item($k);");
547 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
549 } elsif ($c->nodeType == 4) {
552 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
553 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
555 } elsif ($c->nodeType == 8) {
558 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
559 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
562 warn "ACK! I don't know how to handle node type ".$c->nodeType;
578 // in case we run on an implimentation that doesn't have "undefined";
581 function Cast (obj, class_constructor) {
583 if (eval(class_constructor + '["_isfieldmapper"]')) {
584 obj = eval("new " + class_constructor + "(obj)");
593 function JSON2js (json) {
595 json = String(json).replace( /\/\*--\s*S\w*?\s*?\s+\w+\s*--\*\//g, 'Cast(');
596 json = String(json).replace( /\/\*--\s*E\w*?\s*?\s+(\w+)\s*--\*\//g, ', "$1")');
601 eval( 'obj = ' + json );
603 debug("Error building JSON object with string " + E + "\nString:\n" + json );
611 function object2Array(obj) {
612 if( obj == null ) return null;
614 var arr = new Array();
615 for( var i = 0; i < obj.length; i++ ) {
622 function js2JSON(arg) {
623 return _js2JSON(arg);
626 function _js2JSON(arg) {
629 switch (typeof arg) {
634 if (arg._isfieldmapper) { /* magi-c-ast for fieldmapper objects */
636 if( arg.a.constructor != Array ) {
637 var arr = new Array();
638 for( var i = 0; i < arg.a.length; i++ ) {
639 if( arg.a[i] == null ) {
640 arr[i] = null; continue;
643 if( typeof arg.a[i] != 'object' ) {
646 } else if( typeof arg.a[i] == 'object'
647 && arg.a[i]._isfieldmapper) {
652 arr[i] = object2Array(arg.a[i]);
658 return "/*--S " + arg.classname + " --*/" + js2JSON(arg.a) + "/*--E " + arg.classname + " --*/";
662 if (arg.constructor == Array) {
664 for (i = 0; i < arg.length; ++i) {
675 return '[' + o + ']';
677 } else if (typeof arg.toString != 'undefined') {
685 o += js2JSON(i) + ':' + v;
701 if( isNaN(arg) ) throw "JSON.js encountered NaN in js2JSON()";
710 return '"' + String(arg).replace(/(["\\])/g, '\\$1') + '"';