1 package OpenILS::Utils::SpiderMonkey;
2 use strict; use warnings;
3 use OpenSRF::Utils::Logger qw(:logger);
4 use OpenILS::Utils::ScriptRunner;
5 use base 'OpenILS::Utils::ScriptRunner';
6 use JavaScript::SpiderMonkey;
9 my ( $class, %params ) = @_;
10 $class = ref($class) || $class;
11 my $self = { file => $params{file}, libs => $params{libs} };
12 return bless( $self, $class );
16 my( $self, $context ) = @_;
17 $self->{ctx} = $context if $context;
23 my $js = JavaScript::SpiderMonkey->new();
25 $js->function_set("perl_print", sub { print "@_\n"; } );
26 $js->function_set("log_error", sub { $logger->error(@_); return 1;} );
27 $js->function_set("log_warn", sub { $logger->warn(@_); return 1;} );
28 $js->function_set("log_info", sub { $logger->info(@_); return 1;} );
29 $js->function_set("log_debug", sub { $logger->debug(@_); return 1;} );
30 $js->function_set("log_internal", sub { $logger->internal(@_); return 1;} );
31 $js->function_set("debug", sub { $logger->debug(@_); return 1;} );
32 $js->function_set("alert", sub { $logger->warn(@_); return 1;} );
34 $self->load_lib($_) for @{$self->{libs}};
39 my( $self, $filename ) = @_;
40 $self->{file} = $filename;
45 my $file = shift() || $self->{file};
46 my $js = $self->context;
48 if( ! open(F, $file) ) {
49 $logger->error("Error opening script file: $file");
53 if( ! $js->eval(join("\n", <F>)) ) {
54 $logger->error("$file Eval failed: $@");
63 my( $self, $file ) = @_;
74 my( $self, $key, $val ) = @_;
76 if (ref($val) =~ /^Fieldmapper/o) {
77 $self->insert_fm($key, $val);
78 } elsif (ref($val) and $val =~ /ARRAY/o) {
79 $self->insert_array($key, $val);
80 } elsif (ref($val) and $val =~ /HASH/o) {
81 $self->insert_hash($key, $val);
82 } elsif (!ref($val)) {
83 $self->context->property_by_path(
86 sub { my( $k, $v ) = @_; $val = $v; }
97 my( $self, $key, $fm ) = @_;
98 my $ctx = $self->context;
99 return undef unless ($ctx and $key and $fm);
100 my $o = $ctx->object_by_path($key);
102 for my $f ( $fm->properties ) {
105 $self->insert("$key.$f", $val);
107 $ctx->property_by_path(
111 my $k = _js_prop_name(shift());
116 my $k = _js_prop_name(shift());
127 my( $self, $key, $hash ) = @_;
128 my $ctx = $self->context;
129 return undef unless ($ctx and $key and $hash);
130 $ctx->object_by_path($key);
132 for my $k ( keys %$hash ) {
135 $self->insert("$key.$k", $v);
137 $ctx->property_by_path(
139 sub { $hash->{_js_prop_name(shift())} },
141 my( $key, $val ) = @_;
142 $hash->{_js_prop_name($key)} = $val; }
150 my( $self, $key, $array ) = @_;
151 my $ctx = $self->context;
152 return undef unless ($ctx and $key and $array);
154 my $a = $ctx->array_by_path($key);
157 for my $v ( @$array ) {
159 my $elobj = $ctx->object_by_path('__tmp_arr_el');
160 $self->insert('__tmp_arr_el', $v);
161 $ctx->array_set_element_as_object( $a, $ind, $elobj );
163 $ctx->array_set_element( $a, $ind, $v );