Skip to content

Instantly share code, notes, and snippets.

@rbackhouse
Created March 20, 2011 22:29
Show Gist options
  • Save rbackhouse/878741 to your computer and use it in GitHub Desktop.
Save rbackhouse/878741 to your computer and use it in GitHub Desktop.
Example demonstrating using the V8 Java Bridge to run javascript with a callback into java
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.dojotoolkit.json.JSONParser;
import org.dojotoolkit.json.JSONSerializer;
import org.dojotoolkit.rt.v8.V8Exception;
import org.dojotoolkit.rt.v8.V8JavaBridge;
import org.dojotoolkit.server.util.resource.ResourceLoader;
public class V8JavaBridgeExample extends V8JavaBridge {
private ResourceLoader resourceLoader = null;
public V8JavaBridgeExample(ResourceLoader resourceLoader) {
super(true);
this.resourceLoader = resourceLoader;
}
public String readResource(String path, boolean useCache) throws IOException {
return resourceLoader.readResource(path, useCache);
}
public void runTestScript() {
StringBuffer sb = new StringBuffer();
sb.append("var v = test(JSON.stringify({input: \"Hello\"})); print(v);");
try {
runScript(sb.toString(), new String[]{"test"});
} catch (V8Exception e) {
e.printStackTrace();
}
}
public String test(String json) {
try {
Map<String, Object> input = (Map<String, Object>)JSONParser.parse(new StringReader(json));
System.out.println("json input value = "+input.get("input"));
Map<String, Object> returnValue = new HashMap<String, Object>();
returnValue.put("returnValue", "Hello Back");
StringWriter sw = new StringWriter();
JSONSerializer.serialize(sw, returnValue);
return sw.toString();
} catch (IOException e) {
e.printStackTrace();
return "{}";
}
}
}
@makc
Copy link

makc commented Jul 17, 2013

this does not seem to go with https://github.com/zazl/serverutils well. I cant even do super(true);

edit: so it seems I need to take out super and useCache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment