Example usage for javax.script ScriptEngine get

List of usage examples for javax.script ScriptEngine get

Introduction

In this page you can find the example usage for javax.script ScriptEngine get.

Prototype

public Object get(String key);

Source Link

Document

Retrieves a value set in the state of this engine.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    String script = "var year = 2015";

    engine.eval(script);//from w w w  . j  a va 2s  .  c  o  m
    Object year = engine.get("year");
    System.out.println("year's class:" + year.getClass().getName());
    System.out.println("year's value:" + year);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("javascript");

    engine.eval(new InputStreamReader(Main.class.getResourceAsStream("scripting.js")));

    List<String> list1 = (List<String>) engine.get("list1");
    if (list1 != null) {
        for (String s : (List<String>) list1) {
            System.out.println(s);
        }/*from   www  . j  a  va 2  s .  co  m*/
    }
    Invocable engineInv = (Invocable) engine;
    Object obj = engine.get("listObject");
    Object list2 = engineInv.invokeMethod(obj, "getList2");
    if (list2 != null) {
        for (String s : (List<String>) list2) {
            System.out.println(s);
        }
    }
}

From source file:Main.java

public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {//from  w w w .  j ava2 s.co  m
        engine.put("name", "abcde");
        engine.eval("var output = '';for (i = 0; i <= name.length; i++) {"
                + "  output = name.charAt(i)+'-' + output" + "}");
        String name = (String) engine.get("output");
        System.out.println(name);
    } catch (ScriptException e) {
        System.err.println(e);
    }
}

From source file:MonthlyPayment.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension("js");
    String calcMonthlyPaymentScript = "intrate = intrate/1200.0;"
            + "payment = principal*intrate*(Math.pow (1+intrate, months)/"
            + "                            (Math.pow (1+intrate,months)-1));";

    engine.put("principal", 20000.0);
    System.out.println("Principal = " + engine.get("principal"));
    engine.put("intrate", 6.0);
    System.out.println("Interest Rate = " + engine.get("intrate") + "%");
    engine.put("months", 360);
    System.out.println("Months = " + engine.get("months"));
    engine.eval(calcMonthlyPaymentScript);
    System.out.printf("Monthly Payment = %.2f\n", engine.get("payment"));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    if (!(engine instanceof Invocable)) {
        System.out.println("Invoking methods is not supported.");
        return;//from  www . java 2 s  .  co m
    }
    Invocable inv = (Invocable) engine;
    String scriptPath = "c:/Java_Dev/calculator.js";

    engine.eval("load('" + scriptPath + "')");

    Object calculator = engine.get("calculator");

    int x = 3;
    int y = 4;
    Object addResult = inv.invokeMethod(calculator, "add", x, y);
    Object subResult = inv.invokeMethod(calculator, "subtract", x, y);
    Object mulResult = inv.invokeMethod(calculator, "multiply", x, y);
    Object divResult = inv.invokeMethod(calculator, "divide", x, y);

    System.out.println(addResult);
    System.out.println(subResult);
    System.out.println(mulResult);
    System.out.println(divResult);
}

From source file:velo.scripting.ScriptingManager.java

public static void main(String[] args) throws FactoryException {
    //ScriptingManager sm = new ScriptingManager();
    //ScriptEngine se = sm.getScriptEngine("groovy");
    ScriptEngine se = ScriptingManager.getScriptEngine("groovy");

    OperationContext oc = new OperationContext();
    se.put("name", "moshe");
    se.put("cntx", oc);
    //String a = "<?xml version=\"1.0\"?><j:jelly trim=\"false\" xmlns:j=\"jelly:core\" xmlns:x=\"jelly:xml\" xmlns:html=\"jelly:html\"><html><head><title>${name}'s Page</title></head></html></j:jelly>";
    //String a = "def a = new Date(); println(a.getClass().getName()); def myArr = new Date[1]; myArr[0] = a; println(myArr.getClass().getName()); cntx.addVar('myArr',myArr);";
    String a = "def a = new Date(); a.getClass().getName(); def myArr = new Date[1]; myArr[0] = a; myArr.getClass().getName(); cntx.addVar('myArr',myArr);";

    //Sadly it seems that invoking via se.eval and script.eval almost return the same times, thought it should be much more effecient :/
    try {/*from   www . j  a v  a  2s  .c  o  m*/
        //groovy
        //se.eval("println(name);");
        StopWatch sw = new StopWatch();
        sw.start();

        for (int i = 0; i < 100000; i++) {
            se.eval(a);
        }
        sw.stop();
        System.out.println("time in seconds: '" + sw.getTime() / 1000 + "'");
        sw.reset();

        sw.start();
        CompiledScript script = ((Compilable) se).compile(a);
        for (int i = 0; i < 100000; i++) {
            script.eval();
        }
        sw.stop();
        System.out.println("time in seconds: '" + sw.getTime() / 1000 + "'");

        OperationContext getOc = (OperationContext) se.get("cntx");
        Date[] arrOfDate = (Date[]) getOc.get("myArr");
        //System.out.println(arrOfDate);

    } catch (ScriptException e) {
        System.out.println("ERROR: " + e);
    }
}

From source file:Main.java

public static Object getValue(String filepath, String key) {
    try {// w w w .j  ava 2  s  . co m
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine jsEngine = sem.getEngineByName("js");
        jsEngine.eval(new FileReader(filepath));
        return jsEngine.get(key);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:org.rhq.bindings.ScriptEngineFactory.java

/**
 * Goes through the methods of the object found in the <code>scriptEngine</code>'s ENGINE_SCOPE
 * and for each of them generates a top-level function that is called the same name and accepts the same
 * parameters./*w w w  .  jav a 2s  .  com*/
 * 
 * @param scriptEngine the script engine to generate the top-level functions in
 * @param bindingName the name of the object in the script engine to generate the functions from
 * 
 * @see ScriptEngineInitializer#generateIndirectionMethod(String, Method)
 * @see NoTopLevelIndirection
 */
public static void bindIndirectionMethods(ScriptEngine scriptEngine, String bindingName) {
    Object object = scriptEngine.get(bindingName);
    if (object == null) {
        LOG.debug("The script engine doesn't contain a binding called '" + bindingName
                + "'. No indirection functions will be generated.");
        return;
    }

    ScriptEngineInitializer initializer = getInitializer(scriptEngine.getFactory().getLanguageName());
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(), Object.class);
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();

        Map<String, Set<Method>> overloadsPerMethodName = new HashMap<String, Set<Method>>();
        for (MethodDescriptor methodDescriptor : methodDescriptors) {
            Method method = methodDescriptor.getMethod();
            if (shouldIndirect(method)) {
                Set<Method> overloads = overloadsPerMethodName.get(method.getName());
                if (overloads == null) {
                    overloads = new HashSet<Method>();
                    overloadsPerMethodName.put(method.getName(), overloads);
                }
                overloads.add(method);
            }
        }

        for (Set<Method> overloads : overloadsPerMethodName.values()) {
            Set<String> methodDefs = initializer.generateIndirectionMethods(bindingName, overloads);
            for (String methodDef : methodDefs) {
                try {
                    scriptEngine.eval(methodDef);
                } catch (ScriptException e) {
                    LOG.warn("Unable to define global function declared as:\n" + methodDef, e);
                }
            }
        }
    } catch (IntrospectionException e) {
        LOG.debug("Could not inspect class " + object.getClass().getName()
                + ". No indirection methods for variable '" + bindingName + "' will be generated.", e);
    }
}

From source file:org.siphon.common.js.JsEngineUtil.java

public static Object eval(ScriptEngine jsEngine, String srcFile, boolean onlyOnce, boolean preservePathInStack)
        throws Exception {
    ScriptObjectMirror importedFiles = (ScriptObjectMirror) jsEngine.get("IMPORTED_FILES");
    if (importedFiles.containsKey(srcFile)) {
        if (onlyOnce)
            return null;
    } else {//  ww  w  .  j  av  a  2 s.c om
        importedFiles.put(srcFile, true);
    }
    ScriptObjectMirror stk = (ScriptObjectMirror) jsEngine.get("IMPORTS_PATH_STACK");
    // NativeArray.pushObject(stk.to(NativeArray.class), srcFile);
    //stk.callMember("push", srcFile);

    try {
        String code = FileUtils.readFileToString(new File(srcFile), "utf-8");
        return eval(jsEngine, srcFile, code);
    } catch (ScriptException | FileNotFoundException e) {
        throw e;
    } finally {
        if (!preservePathInStack)
            NativeArray.pop(stk.to(NativeArray.class));
    }
}

From source file:org.siphon.common.js.JsEngineUtil.java

public static Object eval(ScriptEngine jsEngine, String srcFile, String aliasPath, String script,
        boolean onlyOnce, boolean preservePathInStack) throws NoSuchMethodException, ScriptException {
    ScriptObjectMirror importedFiles = (ScriptObjectMirror) jsEngine.get("IMPORTED_FILES");
    if (importedFiles.containsKey(srcFile)) {
        if (onlyOnce)
            return null;
    } else {/*from w w  w  .ja  va 2  s.c  o m*/
        importedFiles.put(srcFile, true);
    }
    ScriptObjectMirror stk = (ScriptObjectMirror) jsEngine.get("IMPORTS_PATH_STACK");
    //NativeArray.pushObject((Object)(stk.to(NativeArray.class)), (Object)srcFile);
    stk.callMember("push", srcFile);

    try {
        return eval(jsEngine, aliasPath, script);
    } catch (ScriptException e) {
        throw e;
    } finally {
        if (!preservePathInStack)
            NativeArray.pop(stk.to(NativeArray.class));
    }
}