1+ REM
2+ REM Running JavaScript using Javax API in OJVM
3+ REM
4+ REM -- -----------------------------------------------------------
5+ REM Copyright (c) 2017 , Oracle and / or its affiliates. All rights
6+ REM reserved.
7+ REM
8+ REM Author Kuassi Mensah
9+ REM
10+ REM Turn steps i, ii and iii in ReadeMe- JavaScript- OJVM .txt into a Java
11+ REM wrapper class in OJVM.
12+ REM
13+ REM This description is based on select .js
14+ REM For your own JavaScript function, the signature may differ depending
15+ REM on your input parameters and return values .
16+ REM
17+ REM The following script generates the Java wrapper class;
18+ REM you may paste this direcly in a SQL session
19+ REM or put it in a script file and invoke it.
20+ REM
21+ create or replace and compile java resource named " InvokeScript" as
22+ import javax .script .* ;
23+ import java .net .* ;
24+ import java .io .* ;
25+ public class InvokeScript {
26+ public static String eval(String inputId) throws Exception {
27+ String output = new String();
28+ try {
29+ // create a script engine manager
30+ ScriptEngineManager factory = new ScriptEngineManager();
31+ // create a JavaScript engine
32+ ScriptEngine engine = factory .getEngineByName (" javascript" );
33+ // read the script as a java resource
34+ engine .eval (new InputStreamReader
35+ (InvokeScript .class .getResourceAsStream(" select.js" )));
36+ /*
37+ * Alternative approach
38+ * engine.eval(Thread.currentThread().getContextClassLoader().getResource("select.js"));
39+ */
40+ Invocable invocable = (Invocable) engine;
41+ Object selectResult =
42+ invocable .invokeFunction (" selectQuery" , inputId);
43+ output = selectResult .toString ();
44+ } catch(Exception e) {
45+ output = e .getMessage ();
46+ }
47+ return output;
48+ }
49+ }
50+ /
51+
52+
53+ REM Create a SQL wrapper for the eval function
54+ REM Create function
55+ REM
56+ CREATE OR REPLACE FUNCTION invokeScriptEval (inputId varchar2 ) return varchar2 as language java
57+ name ' InvokeScript.eval(java.lang.String) return java.lang.String' ;
58+ /
59+
60+ REM
61+ REM Allow calling InvokeScriptEval() from SQL or PL/ SQL
62+ REM
63+ CREATE OR REPLACE PROCEDURE sqldemo(id IN varchar2 )
64+ IS
65+ output varchar2 (10000 );
66+ BEGIN
67+ SELECT invokeScriptEval(id) INTO output from dual;
68+ dbms_output .put_line (output);
69+ END;
70+ /
71+ SHOW ERRORS;
0 commit comments