Skip to content

Instantly share code, notes, and snippets.

@tiennv90
Last active December 22, 2015 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiennv90/6498882 to your computer and use it in GitHub Desktop.
Save tiennv90/6498882 to your computer and use it in GitHub Desktop.
package com.nextuser.template;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.json.JsonParser;
public class JavaScript {
/**
*
*/
private Context context = Context.enter();
private Scriptable scope;
public JavaScript(String resource) throws Exception {
this.scope = context.initStandardObjects();
JsonParser parser = new JsonParser(this.context, this.scope);
Object empty = parser.parseValue("{}");
putJSObject("elements", empty)
.putJSObject("data", empty)
.putJSObject("tpl", "");
Window window = new Window();
//create Window object
putJSObject("window", window)
.putJSObject("window.Beard", window.getBeard());
this.processSource(context, resource);
addScript("Beard = window.Beard;");
}
public void addScript(String script) {
context.evaluateString(this.scope, script, "<stdin>", 1, null);
}
public JavaScript putJSObject(String paramName, Object value) {
scope.put(paramName, scope, value);
return this;
}
public Object execute(String script, boolean isJson) {
context.evaluateString(scope, String.format("result = %s", script),
"<stdin>", 1, null);
if (isJson) {
return (NativeObject) scope.get("result", scope);
}
return scope.get("result", scope);
}
public Context getContext() {
return context;
}
public Scriptable getScope() {
return scope;
}
private void processSource(Context context, String input) throws IOException {
if (input != null && !input.isEmpty()) {
BufferedReader in = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(input.getBytes())));
String sourceName = "<stdin>";
int lineno = 1;
boolean hitEOF = false;
do {
int startline = lineno;
String source = "";
// Collect lines of source to compile.
while (true) {
String newline;
newline = in.readLine();
if (newline == null) {
hitEOF = true;
break;
}
source = source + newline + "\n";
lineno++;
// Continue collecting as long as more lines
// are needed to complete the current
// statement. stringIsCompilableUnit is also
// true if the source statement will result in
// any error other than one that might be
// resolved by appending more source.
if (context.stringIsCompilableUnit(source)) {
break;
}
}
context.evaluateString(scope, source, sourceName, startline,
null);
} while (!hitEOF);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment