I've had success initializing my JS scope, injecting various Java
objects using code like the following:
String globalName = "SomeGlobal";
Object jsObject = Context.javaToJS(anObject, this.jsScope);
ScriptableObject.putProperty(jsScope, globalName, jsObject);
Now I'd like to (in Java code) construct a JS array that contains JS
objects. Each of the JS objects in the array is formed from a
java.util.Map where the keys become property names and the values
become property values. The values are to be native Java objects
(presumably wrapped). The keys are strings.
[{key1:value1, key2:value2, key3:value3},
{key1:value1, key2:value2, key3:value3},
{key1:value1, key2:value2, key3:value3},
...]
I have the following utility method that builds the JS object
public static Scriptable inputDataToJSArray(Workbook wb, Scriptable
scope,
Context context) {
Iterator<Map<String, Object>> rowIterator = WorkbookDataUtil
.createInputDataRowInterator(wb);
// Create a JS array for the return value
Scriptable returnJSArray = context.newArray(scope, 1);
// For every row create a new JS object and insert it
int rowIndex = 0;
while(rowIterator.hasNext()) {
Scriptable rowJSObject = context.newObject(scope);
Map<String,Object> rowMap = rowIterator.next();
for (Map.Entry<String, Object> columnEntry :
rowMap.entrySet()) {
String columnName = columnEntry.getKey();
Object cellValue = columnEntry.getValue();
scope.put(columnName, rowJSObject,
Context.javaToJS(cellValue,
rowJSObject));
}
scope.put(rowIndex, returnJSArray, rowJSObject);
rowIndex++;
}
return returnJSArray;
}
And I add the result to my scope using:
protected void addToScopeJS(String globalName, Object jsObject,
org.apache.commons.chain.Context chainContext) {
logger.trace("addToScope - added {} to scope as global name {}",
jsObject.toString(), globalName);
ScriptableObject.putProperty(jsScope, globalName, jsObject);
chainContext.put(globalName, jsObject);
}
Note: globalName = "InputData"
But in my scripts, when I attempt to access the properties of each row
I get undefined (see row["First_Name"] & row["Last_Name"]):
function main1() {
Logger.trace("Begin UploadHelloService.js");
var aSheet = OutputWorkbook.createSheet("SayHello Results", 0);
var rowIndex = 1;
addLabelCell("Response",aSheet,0,0);
var row;
var column;
var response;
for(row in InputData) {
response = sayHello(row["First_Name"],row["Last_Name"]);
addLabelCell(response,aSheet,rowIndex,0);
}
Logger.trace("End UploadHelloService.js");
}
I've done detailed inspection of the JS array and contained JS objects
in the debugger and they appear to be well formed. I've tried
variants where I don't call javaToJS and turning off primitive
wrapping to no avail.
Any hints greatly appreciated,
Ron
_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino