I try to run a nodeJS script with j2v8 in my Java project and it runs normally but i can't get the Array or any other JScript Objects although this functionality is offered through j2v8. Additionally the script uses a npm module called Blocktrail which generates the Array. The call for the Object is in the function testExportAnalyzer(). Here it throws that the Object does not contain "test". Please, can anyone explain how i can use the variables or the needed Array in my Java Code or what I do wrong?
public ScriptLoader(String adr) {
address = adr;
addressInformation = null;
NODE_SCRIPT = ""
+"var test = \"123456\";\n"
+"var blocktrail = require('/blocktrail-sdk');\n"
+"var addressInformation = null;\n"
+"var client = blocktrail.BlocktrailSDK({apiKey : \"xxxxxx\", apiSecret : \"xxxxxx\"});\n"
+"client.address(\""+address+"\", function(err, address) {\n"
+" if (err) {\n"
+" console.log('address ERR', err);\n"
+" return;\n"
+" }\n"
+" addressInformation = address;"
+"console.log('address:', address['address'], 'balance:', address['balance'] / blocktrail.COIN, 'sent and received in BTC:', address['sent'] / blocktrail.COIN, address['received'] / blocktrail.COIN, 'number of transactions:', address['total_transactions_out'], address['total_transactions_in']);\n"
+"});\n"
+"\n"
+"client.addressTransactions(\""+address+"\", {limit: 100}, function(err, address_txs) {\n"
+" console.log('address_transactions', address_txs['data'].length, address_txs['data'][0]);\n"
+"});";
}
public void executeAnalyzerScript() throws IOException {
final NodeJS nodeJS = NodeJS.createNodeJS();
JavaCallback callback = new JavaCallback() {
public Object invoke(V8Object receiver, V8Array parameters) {
return "Hello, JavaWorld!";
}
};
nodeJS.getRuntime().registerJavaMethod(callback, "someJavaMethod");
File nodeScript = createTemporaryScriptFile(NODE_SCRIPT, "addressScript");
nodeJS.exec(nodeScript);
while(nodeJS.isRunning()) {
nodeJS.handleMessage();
}
nodeJS.release();
}
public void testExportAnalyzer() throws IOException {
NodeJS nodeJS = null;
File testScript = createTemporaryScriptFile(NODE_SCRIPT, "Test");
nodeJS = NodeJS.createNodeJS();
V8Object exports = nodeJS.require(testScript);
while(nodeJS.isRunning()) {
nodeJS.handleMessage();
}
System.out.println(exports.contains("test"));
exports.release();
}
private static File createTemporaryScriptFile(final String script, final String name) throws IOException {
File tempFile = File.createTempFile(name, ".js.tmp");
PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
try {
writer.print(script);
} finally {
writer.close();
}
return tempFile;
}
public void setAddress(String input) {
address = input;
}
I had some success by writing variables like this in the Javascript code:
global.myvar = "myval";