Java Code Examples for javax.script.ScriptEngine#get()

The following examples show how to use javax.script.ScriptEngine#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InvokeScriptMethod.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
Example 2
Source File: RunnableImplObject.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

    // evaluate script
    engine.eval(script);

    // get script object on which we want to implement the interface with
    final Object obj = engine.get("obj");

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script methods of object 'obj'
    final Runnable r = inv.getInterface(obj, Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 3
Source File: RunnableImplObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

    // evaluate script
    engine.eval(script);

    // get script object on which we want to implement the interface with
    final Object obj = engine.get("obj");

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script methods of object 'obj'
    final Runnable r = inv.getInterface(obj, Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 4
Source File: InvokeScriptMethod.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
Example 5
Source File: RunnableImplObject.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

    // evaluate script
    engine.eval(script);

    // get script object on which we want to implement the interface with
    final Object obj = engine.get("obj");

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script methods of object 'obj'
    final Runnable r = inv.getInterface(obj, Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 6
Source File: InvokeScriptMethod.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
Example 7
Source File: Test8.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("\nTest8\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e  = Helper.getJsEngine(m);
    if (e == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    e.eval(new FileReader(
        new File(System.getProperty("test.src", "."), "Test8.js")));
    Invocable inv = (Invocable)e;
    inv.invokeFunction("main", "Mustang");
    // use method of a specific script object
    Object scriptObj = e.get("scriptObj");
    inv.invokeMethod(scriptObj, "main", "Mustang");
}
 
Example 8
Source File: JavaScriptConfigEvaluator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public String evaluateJavaScript(Reader fileReader)
{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    try
    {
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("json2.js")));
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test-utils.js")));
        engine.eval(fileReader);
        engine.eval("jsonString = JSON.stringify(" + TEST_CONFIG_VARIABLE_NAME + ")");
    }
    catch (ScriptException e)
    {
        throw new DistributedTestException("Exception while evaluating test config", e);
    }
    String result = (String) engine.get("jsonString");

    return result;
}
 
Example 9
Source File: RunnableImplObject.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

    // evaluate script
    engine.eval(script);

    // get script object on which we want to implement the interface with
    final Object obj = engine.get("obj");

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script methods of object 'obj'
    final Runnable r = inv.getInterface(obj, Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example 10
Source File: Test7.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("\nTest7\n");
    File file =
        new File(System.getProperty("test.src", "."), "Test7.js");
    Reader r = new FileReader(file);
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine eng = Helper.getJsEngine(m);
    if (eng == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    eng.put("filename", file.getAbsolutePath());
    eng.eval(r);
    String str = (String)eng.get("firstLine");
    // do not change first line in Test7.js -- we check it here!
    if (!str.equals("//this is the first line of Test7.js")) {
        throw new RuntimeException("unexpected first line");
    }
}
 
Example 11
Source File: InvocableTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeMethodTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var Example = function() { this.hello = function() { return 'Hello World!'; };}; myExample = new Example();");
        final Object obj = e.get("myExample");
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 12
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeMethodTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var Example = function() { this.hello = function() { return 'Hello World!'; };}; myExample = new Example();");
        final Object obj = e.get("myExample");
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 13
Source File: ToolScript.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
     * 渲染模板
     *
     * @param templateContent
     * @param paramMap
     *
     * @return
     */
    public static String render(String templateContent, Map<String, Object> paramMap) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        // 建立javascript脚本引擎
        ScriptEngine engine = manager.getEngineByName("javascript");
        // 将变量和变量值传给javascript脚本
        for (String key : paramMap.keySet()) {
            engine.put(key, paramMap.get(key));
        }

        // 开始执行脚本
        engine.eval(templateContent);

        // 编译执行,执行单个函数
//			if (engine instanceof Compilable){
//				Compilable compEngine = (Compilable)engine;
//				compEngine.compile(templateContent);
//			}

        // 执行多个函数
//			if (engine instanceof Invocable){
//				engine.eval(templateContent);
//				Invocable invokeEngine = (Invocable)engine;
//				Object o = invokeEngine.invokeFunction("funcName", "funcParam1", "funcParam2");
//			}

        // 异步调用
//			Invocable invokeEngine = (Invocable)engine;
//			Runnable runner = invokeEngine.getInterface(Runnable.class);
//			Thread t = new Thread(runner);
//			t.start();
//			t.join();

//		} catch (NoSuchMethodException e) {
//			log.error("执行脚本异常");
//		}

        // 取js变量值
        return (String) engine.get("output");
    }
 
Example 14
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeMethodTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var Example = function() { this.hello = function() { return 'Hello World!'; };}; myExample = new Example();");
        final Object obj = e.get("myExample");
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 15
Source File: InvocableTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeMethodTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var Example = function() { this.hello = function() { return 'Hello World!'; };}; myExample = new Example();");
        final Object obj = e.get("myExample");
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 16
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static String prettify(ScriptEngine engine, String src) {
  try {
    Object w = engine.get("window");
    return (String) ((Invocable) engine).invokeMethod(w, "prettyPrintOne", src);
  } catch (ScriptException | NoSuchMethodException ex) {
    ex.printStackTrace();
    return "";
  }
}
 
Example 17
Source File: ParkInetServer.java    From Fourinone with Apache License 2.0 4 votes vote down vote up
String getResponse(String treeId, int treenum, String eid){
	String result = "";
	try{
		String fttps = ConfigContext.getRequest(ConfigContext.getProp("RSPFTTPJS"));
		//System.out.println(fttps);
		ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
		
		String[] fttproot=null,fttprootcode=null;
		FileProperty[] fttpchild = null;
		if(treenum==0){
			fttproot = FttpAdapter.fttpRoots();
			//for(int i=0;i<fttproot.length;i++)System.out.println("fttproot:"+fttproot[i]);
			fttprootcode = FttpAdapter.fttpRootsPathEncode(fttproot);
		}else if(treenum>0){
			//System.out.println("getResponse treeId................"+treeId);
			FttpAdapter fa = new FttpAdapter(treeId);//ObjectBytes.getViewUtf8UrlString(treeId)getViewUrlStringdecodeReplace"fttp://localhost"
			//rootlist = fa.listRoots();
			fttpchild = fa.getChildProperty();
			/*System.out.println("getResponse fttpchild................"+fttpchild);
			if(fttpchild!=null)
				System.out.println("getResponse fttpchild length................"+fttpchild.length);*/
		}
		
		engine.put("$treenum", treenum);
		engine.put("$fttproot", fttproot);
		engine.put("$fttprootcode", fttprootcode);
		engine.put("$fttpchild", fttpchild);
		//if(engine instanceof Invocable){
		
		if(engine instanceof Compilable){
			Compilable ce = (Compilable)engine;
			ce.compile(fttps).eval();
		}
		//System.out.println(o);
		result = (String)engine.get("result");
		//result = new String(result.getBytes("iso-8859-1"),"utf-8");
		//System.out.println("result:"+result);
	}catch(Exception e){
		//System.out.println(e);
		 LogUtil.info("[getResponse]", "[HandlerAuth]", e);
	}
	return "<script>parent."+eid+".innerHTML=\""+result+"\";</script>";
}
 
Example 18
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void jsobjectTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("var obj = { '1': 'world', func: function() { return this.bar; }, bar: 'hello' }");
        final ScriptObjectMirror obj = (ScriptObjectMirror) e.get("obj");

        // try basic get on existing properties
        if (!obj.getMember("bar").equals("hello")) {
            fail("obj.bar != 'hello'");
        }

        if (!obj.getSlot(1).equals("world")) {
            fail("obj[1] != 'world'");
        }

        if (!obj.callMember("func", new Object[0]).equals("hello")) {
            fail("obj.func() != 'hello'");
        }

        // try setting properties
        obj.setMember("bar", "new-bar");
        obj.setSlot(1, "new-element-1");
        if (!obj.getMember("bar").equals("new-bar")) {
            fail("obj.bar != 'new-bar'");
        }

        if (!obj.getSlot(1).equals("new-element-1")) {
            fail("obj[1] != 'new-element-1'");
        }

        // try adding properties
        obj.setMember("prop", "prop-value");
        obj.setSlot(12, "element-12");
        if (!obj.getMember("prop").equals("prop-value")) {
            fail("obj.prop != 'prop-value'");
        }

        if (!obj.getSlot(12).equals("element-12")) {
            fail("obj[12] != 'element-12'");
        }

        // delete properties
        obj.removeMember("prop");
        if ("prop-value".equals(obj.getMember("prop"))) {
            fail("obj.prop is not deleted!");
        }

        // Simple eval tests
        assertEquals(obj.eval("typeof Object"), "function");
        assertEquals(obj.eval("'nashorn'.substring(3)"), "horn");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 19
Source File: EngineCompiler.java    From vertx-lang-typescript with Apache License 2.0 4 votes vote down vote up
@Override
public String compile(String filename, SourceFactory sourceFactory) throws IOException {
  ScriptEngine e = getEngine();
  ScriptObjectMirror o = (ScriptObjectMirror)e.get("compileTypescript");
  return (String)o.call(null, filename, sourceFactory);
}
 
Example 20
Source File: Script.java    From HoloAPI with GNU General Public License v3.0 4 votes vote down vote up
protected void compile(ScriptEngine engine) throws ScriptException {
    if (engine.get(this.name) == null) {
        engine.eval("var " + this.name + " = function(hologram, player) {\n" + this.code + "\n}");
    }
}