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 $logger->debug("Refreshing JavaScript Context...");
93 $self->context->destroy;
94 $logger->debug("Context destroyed");
95 $self->{_loaded} = {};
96 $logger->debug("Loaded scripts removed");
98 $logger->debug("New Context initialized");
103 my( $self, $filename ) = @_;
104 $self->{file} = $filename;
107 sub runs { shift()->{_runs} }
113 $self->{reset_count} = $count if ($count);
114 return $self->{reset_count};
124 $file = $self->{file};
127 my $js = $self->context;
131 $self->refresh_context
132 if ($self->reset_count && $self->runs > $self->reset_count);
134 $self->{_runs}++ if ($_real);
136 $file = $self->_find_file($file);
137 $logger->debug("full script file path: $file");
139 if( ! open(F, $file) ) {
140 $logger->error("Error opening script file: $file");
147 $self->insert('environment.result' => {});
150 #print ( "full script is [$content]" );
153 if( !$js || !$content || !$js->eval($content) ) {
154 $logger->error("$file Eval failed: $@");
157 $logger->debug("eval of $file took ". sprintf('%0.3f', time - $s) . " seconds");
160 $self->insert('__' => {'OILS_RESULT' => ''});
161 $js->eval($__json_js."__.OILS_RESULT = js2JSON(environment.result);");
162 $res = $self->retrieve('__.OILS_RESULT');
167 $logger->debug( "script result is [$res]" );
168 return JSON->JSON2perl( $res );
172 my( $self, $path ) = @_;
174 if ($self->{_path}{$path}) {
175 $self->{_path}{$path} = 0;
177 return $self->{_path}{$path};
179 if ($_paths{$path}) {
182 return $_paths{$path};
187 my( $self, $path ) = @_;
189 if (!$self->{_path}{$path}) {
190 $self->{_path}{$path} = 1;
193 if (!$_paths{$path}) {
203 for my $p ( keys %{ $self->{_path} } ) {
204 next unless ($self->{_path}{$p});
205 my $full = join('/',$p,$file);
206 return $full if (-e $full);
211 my( $self, $file ) = @_;
213 push @{ $self->{libs} }, $file
214 if (! grep {$_ eq $file} @{ $self->{libs} });
216 if (!$self->{_loaded}{$file}) {
218 $self->{_loaded}{$file} = 1;
220 return $self->{_loaded}{$file};
230 my( $self, $key ) = @_;
231 return $self->context->property_get($key);
235 my( $self, $obj_key, $meth_name, $sub ) = @_;
236 my $obj = $self->context->object_by_path( $obj_key );
237 $self->context->function_set( $meth_name, $sub, $obj ) if $obj;
242 my( $self, $key, $val, $RO ) = @_;
243 return unless defined($key);
245 if (ref($val) =~ /^Fieldmapper/o) {
246 $self->insert_fm($key, $val, $RO);
247 } elsif (ref($val) and $val =~ /ARRAY/o) {
248 $self->insert_array($key, $val, $RO);
249 } elsif (ref($val) and $val =~ /HASH/o) {
250 $self->insert_hash($key, $val, $RO);
251 } elsif (ref($val) and $val =~ /CODE/o) {
252 $self->context->function_set( $key, $val );
253 } elsif (!ref($val)) {
254 if( defined($val) ) {
255 $self->context->property_by_path(
259 sub { my( $k, $v ) = @_; $val = $v; } :
264 $self->context->property_by_path($key, "");
276 my( $self, $key, $fm, $RO ) = @_;
277 my $ctx = $self->context;
278 return undef unless ($ctx and $key and $fm);
279 my $o = $ctx->object_by_path($key);
281 for my $f ( $fm->properties ) {
284 $self->insert("$key.$f", $val);
286 $ctx->property_by_path(
290 my $k = _js_prop_name(shift());
296 my $k = _js_prop_name(shift());
309 my( $self, $key, $hash, $RO ) = @_;
310 my $ctx = $self->context;
311 return undef unless ($ctx and $key and $hash);
312 $ctx->object_by_path($key);
314 for my $k ( keys %$hash ) {
317 $self->insert("$key.$k", $v);
319 $ctx->property_by_path(
321 sub { $hash->{_js_prop_name(shift())} },
324 my( $hashkey, $val ) = @_;
325 $hash->{_js_prop_name($hashkey)} = $val;
337 my( $self, $key, $array ) = @_;
338 my $ctx = $self->context;
339 return undef unless ($ctx and $key and $array);
341 my $a = $ctx->array_by_path($key);
344 for my $v ( @$array ) {
346 my $tmp_index = $__array_id++;
347 my $elobj = $ctx->object_by_path('__tmp_arr_el'.$tmp_index);
348 $self->insert('__tmp_arr_el'.$tmp_index, $v);
349 $ctx->array_set_element_as_object( $a, $ind, $elobj );
351 $ctx->array_set_element( $a, $ind, $v ) if defined($v);
357 sub _xmlhttprequest_send {
362 my $blocking = shift;
363 my $headerlist = shift;
366 my $ctx = $self->context;
368 # just so perl has access to it...
369 $ctx->object_by_path('__xmlhttpreq_hash.id'.$id);
371 my $headers = new HTTP::Headers;
372 my @lines = split(/\n/so, $headerlist);
373 for my $line (@lines) {
374 if ($line =~ /^(.+?)|(.+)$/o) {
375 $headers->header($1 => $2);
379 my $ua = LWP::UserAgent->new;
380 $ua->agent("OpenILS/0.1");
382 my $req = HTTP::Request->new($method => $url => $headers => $data);
383 my $res = $ua->request($req);
385 if ($res->is_success) {
387 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.responseText', $res->content);
388 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.readyState', 4);
389 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.statusText', $res->status_line);
390 $ctx->property_by_path('__xmlhttpreq_hash.id'.$id.'.status', $res->code);
396 our %_jsonopensrfrequest_cache = ();
398 sub _jsonopensrfrequest_connect {
403 my $ctx = $self->context;
404 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
406 my $ses = $_jsonopensrfrequest_cache{$id} ||
407 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
410 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 1);
412 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.connected', 0);
416 sub _jsonopensrfrequest_disconnect {
420 my $ctx = $self->context;
421 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
423 my $ses = $_jsonopensrfrequest_cache{$id};
429 sub _jsonopensrfrequest_finish {
433 my $ctx = $self->context;
434 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
436 my $ses = $_jsonopensrfrequest_cache{$id};
440 delete $_jsonopensrfrequest_cache{$id};
443 sub _jsonopensrfrequest_send {
448 my $blocking = shift;
451 my @p = @{ JSON->JSON2perl($params) };
453 my $ctx = $self->context;
455 # just so perl has access to it...
456 $ctx->object_by_path('__jsonopensrfreq_hash.id'.$id);
458 my $ses = $_jsonopensrfrequest_cache{$id} ||
459 do { $_jsonopensrfrequest_cache{$id} = OpenSRF::AppSession->create($service) };
460 my $req = $ses->request($method,@p);
464 my $res = $req->recv->content;
466 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', JSON->perl2JSON($res));
467 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
468 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', 'OK');
469 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', '200');
472 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.responseText', '');
473 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.readyState', 4);
474 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.statusText', $req->failed->status );
475 $ctx->property_by_path('__jsonopensrfreq_hash.id'.$id.'.status', $req->failed->statusCode );
482 sub _parse_xml_string {
491 $doc = XML::LibXML->new->parse_string( $string );
495 warn "Could not parse document: $e\n";
499 _JS_DOM($self->context, $key, $doc);
507 if ($node->nodeType == 9) {
508 $node = $node->documentElement;
510 my $n = $node->nodeName;
511 my $ns = $node->namespaceURI;
512 $ns =~ s/'/\'/gso if ($ns);
513 $ns = "'$ns'" if ($ns);
514 $ns = 'null' unless ($ns);
517 #warn("$key = DOMImplementation().createDocument($ns,'$n');");
518 $ctx->eval("$key = new DOMImplementation().createDocument($ns,'$n');");
520 $key = $key.'.documentElement';
523 for my $a ($node->attributes) {
524 my $n = $a->nodeName;
528 #warn("$key.setAttribute('$n','$v');");
529 $ctx->eval("$key.setAttribute('$n','$v');");
534 for my $c ($node->childNodes) {
535 if ($c->nodeType == 1) {
536 my $n = $c->nodeName;
537 my $ns = $node->namespaceURI;
540 $ns =~ s/'/\'/gso if ($ns);
541 $ns = "'$ns'" if ($ns);
542 $ns = 'null' unless ($ns);
544 #warn("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
545 $ctx->eval("$key.appendChild($key.ownerDocument.createElementNS($ns,'$n'));");
546 _JS_DOM($ctx, "$key.childNodes.item($k)",$c);
548 } elsif ($c->nodeType == 3) {
551 #warn("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
552 #warn("path is $key.item($k);");
553 $ctx->eval("$key.appendChild($key.ownerDocument.createTextNode('$n'));");
555 } elsif ($c->nodeType == 4) {
558 #warn("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
559 $ctx->eval("$key.appendChild($key.ownerDocument.createCDATASection('$n'));");
561 } elsif ($c->nodeType == 8) {
564 #warn("$key.appendChild($key.ownerDocument.createComment('$n'));");
565 $ctx->eval("$key.appendChild($key.ownerDocument.createComment('$n'));");
568 warn "ACK! I don't know how to handle node type ".$c->nodeType;
584 // in case we run on an implimentation that doesn't have "undefined";
587 function Cast (obj, class_constructor) {
589 if (eval(class_constructor + '["_isfieldmapper"]')) {
590 obj = eval("new " + class_constructor + "(obj)");
599 function JSON2js (json) {
601 json = String(json).replace( /\/\*--\s*S\w*?\s*?\s+\w+\s*--\*\//g, 'Cast(');
602 json = String(json).replace( /\/\*--\s*E\w*?\s*?\s+(\w+)\s*--\*\//g, ', "$1")');
607 eval( 'obj = ' + json );
609 debug("Error building JSON object with string " + E + "\nString:\n" + json );
617 function object2Array(obj) {
618 if( obj == null ) return null;
620 var arr = new Array();
621 for( var i = 0; i < obj.length; i++ ) {
628 function js2JSON(arg) {
629 return _js2JSON(arg);
632 function _js2JSON(arg) {
635 switch (typeof arg) {
640 if (arg._isfieldmapper) { /* magi-c-ast for fieldmapper objects */
642 if( arg.a.constructor != Array ) {
643 var arr = new Array();
644 for( var i = 0; i < arg.a.length; i++ ) {
645 if( arg.a[i] == null ) {
646 arr[i] = null; continue;
649 if( typeof arg.a[i] != 'object' ) {
652 } else if( typeof arg.a[i] == 'object'
653 && arg.a[i]._isfieldmapper) {
658 arr[i] = object2Array(arg.a[i]);
664 return "/*--S " + arg.classname + " --*/" + js2JSON(arg.a) + "/*--E " + arg.classname + " --*/";
668 if (arg.constructor == Array) {
670 for (i = 0; i < arg.length; ++i) {
681 return '[' + o + ']';
683 } else if (typeof arg.toString != 'undefined') {
691 o += js2JSON(i) + ':' + v;
707 if( isNaN(arg) ) throw "JSON.js encountered NaN in js2JSON()";
716 return '"' + String(arg).replace(/(["\\])/g, '\\$1') + '"';