It has been nearly a decade since I started playing with JavaScript on the PeopleSoft application server. Back then I had to deploy a couple of JAR files to the app server. At that time, maintaining and deploying unmanaged files seemed more headache than benefit. Today Java provides full scripting support through the ScriptEngineManager and embedded Mozilla Rhino JavaScript script engine. Why would I want to script PeopleCode? Here are a few of my favorite reasons:
- Low-level socket communication
- Avoid reflection: JavaScript executes all methods regardless of variable type whereas PeopleCode only recognizes the returned type, not the real type
- Process simple JSON structures that can't be modeled with the Documents module
Here is the PeopleCode required to invoke JavaScript
Local JavaObject &manager = CreateJavaObject("javax.script.ScriptEngineManager");
Local JavaObject &engine = &manager.getEngineByName("JavaScript");
REM ** Evaluate a simple JavaScript;
&engine.eval("var result = Math.random();");
REM ** Access the value of the JavaScript variable named result;
Local string &result_text = &engine.get("result").toString();
Here is some JavaScript that converts the variable &json_string
into a JSON Array and then iterates over each entry, inserting values into a table. Notice that I'm invoking the PeopleCode SQLExec function from JavaScript.
var result = (function() { var SQLExec = Packages.PeopleSoft.PeopleCode.Func.SQLExec; var json = JSON.parse(json_string); var count = 0; json.forEach(function(item, idx) { SQLExec("INSERT INTO ... SYSTIMESTAMP", [idx, item]); count++; }); return count + " rows inserted"; }());
Where did that &json_string
variable come from? Here:
&engine.put("json_string", "[""item1"", ""item2"", ""item3""]");