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 while ( my $e = shift @{$self->{_env}} ) {
86 $self->insert( @$e{ qw/key value readonly/ } => 1 );
89 while ( my $e = shift @{$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(
268 ( !$RO ? (sub { $val }, sub { my( $k, $v ) = @_; $val = $v; }) : () )
271 $self->context->property_by_path($key, "");
283 my( $self, $key, $fm, $RO ) = @_;
284 my $ctx = $self->context;
285 return undef unless ($ctx and $key and $fm);
286 my $o = $ctx->object_by_path($key);
288 for my $f ( $fm->properties ) {
291 $self->insert("$key.$f", $val);
293 $ctx->property_by_path(
298 my $k = _js_prop_name(shift());
302 my $k = _js_prop_name(shift());
315 my( $self, $key, $hash, $RO ) = @_;
316 my $ctx = $self->context;
317 return undef unless ($ctx and $key and $hash);
318 $ctx->object_by_path($key);
320 for my $k ( keys %$hash ) {
323 $self->insert("$key.$k", $v);
325 $ctx->property_by_path(
328 (sub { $hash->{_js_prop_name(shift())} },
330 my( $hashkey, $val ) = @_;
331 $hash->{_js_prop_name($hashkey)} = $val;
343 my( $self, $key, $array ) = @_;
344 my $ctx = $self->context;
345 return undef unless ($ctx and $key and $array);
347 my $a = $ctx->array_by_path($key);
350 for my $v ( @$array ) {
352 my $tmp_index = $__array_id++;
353 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$tmp_index);
354 $self->insert('__tmp_arr_el'.$tmp_index, $v);
355 $ctx->array_set_element_as_object( $a, $ind, $elobj );
357 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
363 sub _xmlhttprequest_send {
368 my $blocking = shift;
369 my $headerlist = shift;
372 my $ctx = $self->context;
374 # just so perl has access to it...
375 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
377 my $headers = new HTTP::Headers;
378 my @lines = split(/\n/so, $headerlist);
379 for my $line (@lines) {
380 if ($line =~ /^(.+?)|(.+)$/o) {
381 $headers->header($1 => $2);
385 my $ua = LWP::UserAgent->new;
386 $ua->agent("OpenILS/0.1");
388 my $req = HTTP::Request->new($method => $url => $headers => $data);
389 my $res = $ua->request($req);
391 if ($res->is_success) {
393 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
394 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
395 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
396 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
402 our %_jsonopensrfrequest_cache = ();
404 sub _jsonopensrfrequest_connect {
409 my $ctx = $self->context;
410 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
412 my $ses = $_jsonopensrfrequest_cache{$id} ||
413 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
416 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 1);
418 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 0);
422 sub _jsonopensrfrequest_disconnect {
426 my $ctx = $self->context;
427 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
429 my $ses = $_jsonopensrfrequest_cache{$id};
435 sub _jsonopensrfrequest_finish {
439 my $ctx = $self->context;
440 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
442 my $ses = $_jsonopensrfrequest_cache{$id};
446 delete $_jsonopensrfrequest_cache{$id};
449 sub _jsonopensrfrequest_send {
454 my $blocking = shift;
457 my @p = @{ JSON->JSON2perl($params) };
459 my $ctx = $self->context;
461 # just so perl has access to it...
462 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
464 my $ses = $_jsonopensrfrequest_cache{$id} ||
465 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
466 my $req = $ses->request($method,@p);
470 my $res = $req->recv->content;
472 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', JSON->perl2JSON($res));
473 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
474 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
475 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
478 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
479 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
480 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
481 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
488 sub _parse_xml_string {
497 $doc = XML::LibXML->new->parse_string( $string );
501 warn "Could not parse document: $e\n";
505 _JS_DOM($self->context, $key, $doc);
513 if ($node->nodeType == 9) {
514 $node = $node->documentElement;
516 my $n = $node->nodeName;
517 my $ns = $node->namespaceURI;
518 $ns =~ s/'/\'/gso if ($ns);
519 $ns = "'$ns'" if ($ns);
520 $ns = 'null' unless ($ns);
523 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
524 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
526 $key = $key.'.documentElement';
529 for my $a ($node->attributes) {
530 my $n = $a->nodeName;
534 #warn("$key.setAttribute('$n','$v');");
535 $ctx->eval("$key.setAttribute('$n','$v');");
540 for my $c ($node->childNodes) {
541 if ($c->nodeType == 1) {
542 my $n = $c->nodeName;
543 my $ns = $node->namespaceURI;
546 $ns =~ s/'/\'/gso if ($ns);
547 $ns = "'$ns'" if ($ns);
548 $ns = 'null' unless ($ns);
550 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
551 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
552 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
554 } elsif ($c->nodeType == 3) {
557 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
558 #warn("path is $key.item($k);");
559 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
561 } elsif ($c->nodeType == 4) {
564 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
565 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
567 } elsif ($c->nodeType == 8) {
570 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
571 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
574 warn "ACK! I don't know how to handle node type ".$c->nodeType;
590 // in case we run on an implimentation that doesn't have "undefined";
593 function Cast (obj, class_constructor) {
595 if (eval(class_constructor + '["_isfieldmapper"]')) {
596 obj = eval("new " + class_constructor + "(obj)");
605 function JSON2js (json) {
607 json = String(json).replace( /\/\*--\s*S\w*?\s*?\s+\w+\s*--\*\//g, 'Cast(');
608 json = String(json).replace( /\/\*--\s*E\w*?\s*?\s+(\w+)\s*--\*\//g, ', "$1")');
613 eval( 'obj = ' + json );
615 debug("Error building JSON object with string " + E + "\nString:\n" + json );
623 function object2Array(obj) {
624 if( obj == null ) return null;
626 var arr = new Array();
627 for( var i = 0; i < obj.length; i++ ) {
634 function js2JSON(arg) {
635 return _js2JSON(arg);
638 function _js2JSON(arg) {
641 switch (typeof arg) {
646 if (arg._isfieldmapper) { /* magi-c-ast for fieldmapper objects */
648 if( arg.a.constructor != Array ) {
649 var arr = new Array();
650 for( var i = 0; i < arg.a.length; i++ ) {
651 if( arg.a[i] == null ) {
652 arr[i] = null; continue;
655 if( typeof arg.a[i] != 'object' ) {
658 } else if( typeof arg.a[i] == 'object'
659 && arg.a[i]._isfieldmapper) {
664 arr[i] = object2Array(arg.a[i]);
670 return "/*--S " + arg.classname + " --*/" + js2JSON(arg.a) + "/*--E " + arg.classname + " --*/";
674 if (arg.constructor == Array) {
676 for (i = 0; i < arg.length; ++i) {
687 return '[' + o + ']';
689 } else if (typeof arg.toString != 'undefined') {
697 o += js2JSON(i) + ':' + v;
713 if( isNaN(arg) ) throw "JSON.js encountered NaN in js2JSON()";
722 return '"' + String(arg).replace(/(["\\])/g, '\\$1') + '"';