Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mingchen/9716857ab2a20dc034e6 to your computer and use it in GitHub Desktop.
Save mingchen/9716857ab2a20dc034e6 to your computer and use it in GitHub Desktop.
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 "{}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment