All Downloads are FREE. Search and download functionalities are using the official Maven repository.

li.rudin.mavenjs.core.JavascriptContext Maven / Gradle / Ivy

package li.rudin.mavenjs.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import li.rudin.mavenjs.core.js.Error;
import li.rudin.mavenjs.core.util.JsRuntimeSupport;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class JavascriptContext
{
	private final Context cx;
	private final ScriptableObject sharedScope;
	
	public JavascriptContext() throws Exception
	{
		cx = Context.enter();

		sharedScope = cx.initStandardObjects(new JsRuntimeSupport(), true);
		
		sharedScope.defineFunctionProperties(new String[]{"print", "load"}, sharedScope.getClass(), ScriptableObject.DONTENUM);
		
		Scriptable argsObj = cx.newArray(sharedScope, new Object[] {});
		sharedScope.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM);
		
		ScriptableObject.defineClass(sharedScope, Error.class);
	}
	
	
	public Object eval(String js)
	{
		return cx.evaluateString(sharedScope, js, this.toString(), 1, null);
	}
	
	public Object eval(InputStream input) throws IOException
	{
		InputStreamReader reader = new InputStreamReader(input);
		return cx.evaluateReader(sharedScope, reader, this.toString(), 1, null);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy