Java 类javax.script.CompiledScript 实例源码

项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:incubator-netbeans    文件:OQLEngineImpl.java   
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript"); // NOI18N
        InputStream strm = getInitStream();
        CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
        cs.eval();
        Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
        engine.put("heap", heap); // NOI18N
        engine.put("cancelled", cancelled); // NOI18N
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
项目:neoscada    文件:SetExternalNameWizard.java   
public void setExternalName ( final CompiledScript script ) throws Exception
{
    final CompoundManager manager = new CompoundManager ();

    for ( final ExternalValue v : SelectionHelper.iterable ( this.selection, ExternalValue.class ) )
    {
        final EditingDomain domain = AdapterFactoryEditingDomain.getEditingDomainFor ( v );
        if ( domain == null )
        {
            continue;
        }
        final String name = evalName ( script, v );
        manager.append ( domain, SetCommand.create ( domain, v, ComponentPackage.Literals.EXTERNAL_VALUE__SOURCE_NAME, name ) );
    }

    manager.executeAll ();
}
项目:neoscada    文件:SetExternalNameWizard.java   
public static String evalName ( final CompiledScript script, final ExternalValue v ) throws Exception
{
    final SimpleScriptContext ctx = new SimpleScriptContext ();

    ctx.setAttribute ( "item", v, ScriptContext.ENGINE_SCOPE ); //$NON-NLS-1$

    final Object result = Scripts.executeWithClassLoader ( Activator.class.getClassLoader (), new Callable<Object> () {

        @Override
        public Object call () throws Exception
        {
            return script.eval ( ctx );
        }
    } );

    if ( result == null )
    {
        return null;
    }

    return result.toString ();
}
项目:mynlp    文件:Java8Tester.java   
public static void main(String args[]) throws Exception {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
    String name = "Mahesh";

    System.out.println(nashorn.getClass());

    Integer result = null;
    try {
        nashorn.eval("print('" + name + "')");
        result = (Integer) nashorn.eval("10 + 2");
    } catch (ScriptException e) {
        System.out.println("Error executing script: " + e.getMessage());
    }

    jdk.nashorn.api.scripting.NashornScriptEngine x = (jdk.nashorn.api.scripting.NashornScriptEngine)
            nashorn;

    CompiledScript v = x.compile("1+2");

    System.out.println(v.eval());


}
项目:VirtualChest    文件:VirtualChestItem.java   
public static VirtualChestItem deserialize(VirtualChestPlugin plugin, DataView data) throws InvalidDataException
{
    DataView serializedStack = data.getView(ITEM).orElseThrow(() -> new InvalidDataException("Expected Item"));

    String requirementString = data.getString(REQUIREMENTS).orElse("");
    Tuple<String, CompiledScript> requirements = plugin.getScriptManager().prepare(requirementString);

    List<DataView> primaryList = getViewListOrSingletonList(PRIMARY_ACTION, data);
    VirtualChestActionDispatcher primaryAction = new VirtualChestActionDispatcher(primaryList);

    List<DataView> secondaryList = getViewListOrSingletonList(SECONDARY_ACTION, data);
    VirtualChestActionDispatcher secondaryAction = new VirtualChestActionDispatcher(secondaryList);

    List<DataView> primaryShiftList = getViewListOrSingletonList(PRIMARY_SHIFT_ACTION, data);
    List<DataView> primaryShiftListFinal = primaryShiftList.isEmpty() ? primaryList : primaryShiftList;
    VirtualChestActionDispatcher primaryShiftAction = new VirtualChestActionDispatcher(primaryShiftListFinal);

    List<DataView> secondaryShiftList = getViewListOrSingletonList(SECONDARY_SHIFT_ACTION, data);
    List<DataView> secondaryShiftListFinal = secondaryShiftList.isEmpty() ? secondaryList : secondaryShiftList;
    VirtualChestActionDispatcher secondaryShiftAction = new VirtualChestActionDispatcher(secondaryShiftListFinal);

    List<String> ignoredPermissions = data.getStringList(IGNORED_PERMISSIONS).orElse(ImmutableList.of());

    return new VirtualChestItem(plugin, serializedStack, requirements,
            primaryAction, secondaryAction, primaryShiftAction, secondaryShiftAction, ignoredPermissions);
}
项目:VirtualChest    文件:VirtualChestItem.java   
private VirtualChestItem(
        VirtualChestPlugin plugin,
        DataView serializedStack,
        Tuple<String, CompiledScript> requirements,
        VirtualChestActionDispatcher primaryAction,
        VirtualChestActionDispatcher secondaryAction,
        VirtualChestActionDispatcher primaryShiftAction,
        VirtualChestActionDispatcher secondaryShiftAction,
        List<String> ignoredPermissions)
{
    this.plugin = plugin;
    this.serializer = new VirtualChestItemStackSerializer(plugin);

    this.serializedStack = serializedStack;
    this.requirements = requirements;
    this.primaryAction = primaryAction;
    this.secondaryAction = secondaryAction;
    this.primaryShiftAction = primaryShiftAction;
    this.secondaryShiftAction = secondaryShiftAction;
    this.ignoredPermissions = ignoredPermissions;
}
项目:scipio-erp    文件:ScriptUtil.java   
/**
 * Executes a compiled script and returns the result.
 * 
 * @param script Compiled script.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @return The script result.
 * @throws IllegalArgumentException
 */
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
    Assert.notNull("script", script, "scriptContext", scriptContext);
    Object result = script.eval(scriptContext);
    if (UtilValidate.isNotEmpty(functionName)) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoking function/method " + functionName, module);
        }
        ScriptEngine engine = script.getEngine();
        try {
            Invocable invocableEngine = (Invocable) engine;
            result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
        } catch (ClassCastException e) {
            throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
        }
    }
    return result;
}
项目:csvsum    文件:ScriptEngineTest.java   
@Test
public final void test() throws Exception {
    String csvMapperScript = "mapFunction = function(inputHeaders, inputField, inputValue, outputField, line) return inputValue end";
    String simpleScript = "return inputValue";
    CompiledScript compiledScript = (CompiledScript) ((Compilable) scriptEngine).compile(simpleScript);
    Bindings bindings = scriptEngine.createBindings();
    // inputHeaders, inputField, inputValue, outputField, line
    bindings.put("inputHeaders", "");
    bindings.put("inputField", "");
    bindings.put("inputValue", "testreturnvalue");
    bindings.put("outputField", "");
    bindings.put("line", "");
    String result = (String) compiledScript.eval(bindings);
    System.out.println(result);
    assertEquals("testreturnvalue", result);
}
项目:Rapture    文件:BaseRaptureScript.java   
@SuppressWarnings("unchecked")
@Override
public List<Object> runMap(CallingContext context, RaptureScript script, RaptureDataContext data, Map<String, Object> parameters) {
    try {
        ScriptEngine engine = engineRef.get();
        CompiledScript cScript = getMapScript(engine, script);
        addStandardContext(context, engine);
        engine.put(PARAMS, parameters);
        engine.put(DATA, JacksonUtil.getHashFromObject(data));
        Kernel.getKernel().getStat().registerRunScript();

        return (List<Object>) cScript.eval();
    } catch (ScriptException e) {
        Kernel.writeAuditEntry(EXCEPTION, 2, e.getMessage());
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error running script " + script.getName(), e);

    }
}
项目:Rapture    文件:BaseRaptureScript.java   
@Override
public String runOperation(CallingContext context, RaptureScript script, String ctx, Map<String, Object> params) {
    // Get the script from the implementation bit, set up the helpers into
    // the context and execute...
    try {
        ScriptEngine engine = engineRef.get();
        CompiledScript cScript = getOperationScript(engine, script);
        addStandardContext(context, engine);
        engine.put(PARAMS, params);
        engine.put(CTX, ctx);
        Kernel.getKernel().getStat().registerRunScript();
        return JacksonUtil.jsonFromObject(cScript.eval());
    } catch (ScriptException e) {
        Kernel.writeAuditEntry(EXCEPTION, 2, e.getMessage());
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error running script " + script.getName(), e);
    }
}
项目:Rapture    文件:BaseRaptureScript.java   
@Override
public String runProgram(CallingContext context, IActivityInfo activity, RaptureScript script, Map<String, Object> extraParams) {
    try {
        ScriptEngine engine = engineRef.get();
        CompiledScript cScript = getProgramScript(engine, script);
        addStandardContext(context, engine);
        for (Map.Entry<String, ?> entry : extraParams.entrySet()) {
            engine.put(entry.getKey(), entry.getValue());
        }
        if (Kernel.getKernel().getStat() != null) {
            Kernel.getKernel().getStat().registerRunScript();
        }
        return JacksonUtil.jsonFromObject(cScript.eval());
    } catch (ScriptException e) {
        Kernel.writeAuditEntry(EXCEPTION, 2, e.getMessage());
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error running script " + script.getName(), e);
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:jdk8u_nashorn    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:step    文件:Activator.java   
public static Boolean evaluateActivationExpression(Bindings bindings, Expression activationExpression) {
    Boolean expressionResult; 
    if(activationExpression!=null) {
        CompiledScript script = activationExpression.compiledScript;
        if(script!=null) {
            try {
                Object evaluationResult = script.eval(bindings);
                if(evaluationResult instanceof Boolean) {
                    expressionResult = (Boolean) evaluationResult;
                } else {
                    expressionResult = false;
                }
            } catch (ScriptException e) {
                expressionResult = false;
            }
        } else {
            expressionResult = true;
        }
    } else {
        expressionResult = true;
    }
    return expressionResult;
}
项目:oval    文件:ExpressionLanguageScriptEngineImpl.java   
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
    LOG.debug("Evaluating JavaScript expression: {1}", expression);
    try {
        final Bindings scope = engine.createBindings();
        for (final Entry<String, ?> entry : values.entrySet()) {
            scope.put(entry.getKey(), entry.getValue());
        }

        if (compilable != null) {
            CompiledScript compiled = compiledCache.get(expression);
            if (compiled == null) {
                compiled = compilable.compile(expression);
                compiledCache.put(expression, compiled);
            }
            return compiled.eval(scope);
        }
        return engine.eval(expression, scope);
    } catch (final ScriptException ex) {
        throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex);
    }
}
项目:openhab-hdl    文件:EBusTelegramParser.java   
/**
 * Evaluates the compiled script of a entry.
 * @param entry The configuration entry to evaluate
 * @param scopeValues All known values for script scope
 * @return The computed value
 * @throws ScriptException
 */
private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> scopeValues) throws ScriptException {

    Object value = null;

    // executes compiled script
    if(entry.getValue().containsKey("cscript")) {
        CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript");

        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(scopeValues);
        value = cscript.eval(bindings);
    }

    // try to convert the returned value to BigDecimal
    value = ObjectUtils.defaultIfNull(
            NumberUtils.toBigDecimal(value), value);

    // round to two digits, maybe not optimal for any result
    if(value instanceof BigDecimal) {
        ((BigDecimal)value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    return value;
}
项目:camunda-engine-dmn    文件:ExpressionCachingTest.java   
@Test
public void testCompiledScriptCaching() throws ScriptException {

  // given
  DmnExpressionImpl expression = createExpression("1 > 2", "groovy");

  // when
  expressionEvaluationHandler.evaluateExpression("groovy", expression, emptyVariableContext());

  // then
  InOrder inOrder = inOrder(expression, scriptEngineSpy);
  inOrder.verify(expression, atLeastOnce()).getCachedCompiledScript();
  inOrder.verify(compilableSpy, times(1)).compile(anyString());
  inOrder.verify(expression, times(1)).cacheCompiledScript(any(CompiledScript.class));

  // when (2)
  expressionEvaluationHandler.evaluateExpression("groovy", expression, emptyVariableContext());

  // then (2)
  inOrder.verify(expression, atLeastOnce()).getCachedCompiledScript();
  inOrder.verify(compilableSpy, times(0)).compile(anyString());
}
项目:teiid    文件:ObjectExecution.java   
@Override
public List<Object> next() throws TranslatorException,
        DataNotAvailableException {
    // create and return one row at a time for your resultset.
    if (resultsIt.hasNext()) {
        List<Object> r = new ArrayList<Object>(projects.size());
        Object o = resultsIt.next();
        sc.setAttribute(OBJECT_NAME, o, ScriptContext.ENGINE_SCOPE);
        for (CompiledScript cs : this.projects) {
            if (cs == null) {
                r.add(o);
                continue;
            }
            try {
                r.add(cs.eval(sc));
            } catch (ScriptException e) {
                throw new TranslatorException(e);
            }
        }
        return r;
    }
    return null;
}
项目:dynkt    文件:KotlinScriptEngineTest.java   
@Test
public void testCompileFromFile2() throws FileNotFoundException, ScriptException {
    InputStreamReader code = getStream("nameread.kt");
    CompiledScript result = ((Compilable) engine).compile(code);
    assertNotNull(result);
    // First time
    Bindings bnd1 = engine.createBindings();
    StringWriter ret1;
    bnd1.put("out", new PrintWriter(ret1 = new StringWriter()));
    assertNotNull(result.eval(bnd1));
    assertEquals("Provide a name", ret1.toString().trim());
    // Second time
    Bindings bnd2 = engine.createBindings();
    bnd2.put(ScriptEngine.ARGV, new String[] { "Amadeus" });
    StringWriter ret2;
    bnd2.put("out", new PrintWriter(ret2 = new StringWriter()));
    assertNotNull(result.eval(bnd2));
    assertEquals("Hello, Amadeus!", ret2.toString().trim());
}
项目:AutoLoadCache    文件:JavaScriptParser.java   
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal, Class<T> valueType) throws Exception {
    Bindings bindings=new SimpleBindings();
    bindings.put(TARGET, target);
    bindings.put(ARGS, arguments);
    if(hasRetVal) {
        bindings.put(RET_VAL, retVal);
    }
    CompiledScript script=expCache.get(exp);
    if(null != script) {
        return (T)script.eval(bindings);
    }
    if(engine instanceof Compilable) {
        Compilable compEngine=(Compilable)engine;
        script=compEngine.compile(funcs + exp);
        expCache.put(exp, script);
        return (T)script.eval(bindings);
    } else {
        return (T)engine.eval(funcs + exp, bindings);
    }
}
项目:jsen-js    文件:JavaScriptEngine.java   
@Override
public CompiledScript compile(Reader script) throws ScriptException {
    CompiledScript compiledScript = null;

    Context cx = enterContext();

    try {
        String filename = getFilenameFromReader(script);
        Script rhinoScript = cx.compileReader(script, filename, 1, null);
        compiledScript = new CompiledJavaScript(this, rhinoScript);
    } catch (Exception e) {
        throwWrappedScriptException(e);
    } finally {
        exitContext();
    }

    return compiledScript;
}
项目:elpi    文件:ScriptUtil.java   
/**
 * Executes a compiled script and returns the result.
 * 
 * @param script Compiled script.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @return The script result.
 * @throws IllegalArgumentException
 */
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
    Assert.notNull("script", script, "scriptContext", scriptContext);
    Object result = script.eval(scriptContext);
    if (UtilValidate.isNotEmpty(functionName)) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoking function/method " + functionName, module);
        }
        ScriptEngine engine = script.getEngine();
        try {
            Invocable invocableEngine = (Invocable) engine;
            result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
        } catch (ClassCastException e) {
            throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
        }
    }
    return result;
}
项目:ef-orm    文件:RhinoScriptEngine.java   
@SuppressWarnings("deprecation")
public CompiledScript compile(java.io.Reader script) throws ScriptException {
       CompiledScript ret = null;
       Context cx = enterContext();

       try {
           String fileName = (String) get(ScriptEngine.FILENAME);
           if (fileName == null) {
               fileName = "<Unknown Source>";
           }

           Scriptable scope = getRuntimeScope(context);
           Script scr = cx.compileReader(scope, script, fileName, 1, null);
           ret = new RhinoCompiledScript(this, scr);
       } catch (Exception e) {
           throw new ScriptException(e);
       } finally {
        Context.exit();
       }
       return ret;
   }
项目:elasticsearch-lang-javascript-nashorn    文件:NashornTests.java   
@Test
public void intArrayLengthTest() throws ScriptException {
    Map<String, Object> vars = new HashMap<String, Object>();
    Integer[] l = new Integer[] { 1,2,3 };
    vars.put("l", l);
    String script = "l.length";
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    ScriptContext context = engine.getContext();
    Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.putAll(vars);
    Compilable compilable = (Compilable)engine;
    CompiledScript compiledScript = compilable.compile(script);
    Object o = compiledScript.eval();
    assertThat(((Number) o).intValue(), equalTo(3));
}
项目:elasticsearch-lang-javascript-nashorn    文件:NashornTests.java   
@Test
public void objectArrayTest() throws ScriptException {
    Map<String, Object> vars = new HashMap<String, Object>();
    final Map<String, Object> obj2 = new HashMap<String,Object>() {{
        put("prop2", "value2");
    }};
    final Map<String, Object> obj1 = new HashMap<String,Object>() {{
        put("prop1", "value1");
        put("obj2", obj2);
    }};
    vars.put("l", new Object[] { "1", "2", "3", obj1 });
    String script = "l.length";
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.putAll(vars);
    Compilable compilable = (Compilable)engine;
    CompiledScript compiledScript = compilable.compile(script);
    Object o = compiledScript.eval(bindings);
    assertThat(((Number) o).intValue(), equalTo(4));
}
项目:o3erp    文件:ScriptUtil.java   
/**
 * Executes a compiled script and returns the result.
 * 
 * @param script Compiled script.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @return The script result.
 * @throws IllegalArgumentException
 */
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
    Assert.notNull("script", script, "scriptContext", scriptContext);
    Object result = script.eval(scriptContext);
    if (UtilValidate.isNotEmpty(functionName)) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoking function/method " + functionName, module);
        }
        ScriptEngine engine = script.getEngine();
        try {
            Invocable invocableEngine = (Invocable) engine;
            result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
        } catch (ClassCastException e) {
            throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
        }
    }
    return result;
}
项目:gameserver    文件:V8EngineTest.java   
public void testInvoke() throws Exception {
    eng = new ScriptEngineManager().getEngineByName("jav8");
    Compilable compiler = (Compilable) this.eng;
    CompiledScript script = compiler.compile(calcFunction);

    int max = 100000;
    Bindings binding = this.eng.getBindings(ScriptContext.GLOBAL_SCOPE);
    binding.put("num", 3);
    Object r = script.eval(binding);
    System.out.println(r);
    long startM = System.currentTimeMillis();
    for ( int i=0; i<max; i++ ) {
        script.eval(binding);
    }
    long endM = System.currentTimeMillis();
    System.out.println(" V8 engine loop " + max + ":" + (endM-startM));
}
项目:OLD-OpenJDK8    文件:NashornScriptEngine.java   
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
    final ScriptFunction func = compileImpl(source, context);
    return new CompiledScript() {
        @Override
        public Object eval(final ScriptContext ctxt) throws ScriptException {
            final ScriptObject globalObject = getNashornGlobalFrom(ctxt);
            // Are we running the script in the correct global?
            if (func.getScope() == globalObject) {
                return evalImpl(func, ctxt, globalObject);
            }
            // ScriptContext with a different global. Compile again!
            // Note that we may still hit per-global compilation cache.
            return evalImpl(compileImpl(source, ctxt), ctxt, globalObject);
        }
        @Override
        public ScriptEngine getEngine() {
            return NashornScriptEngine.this;
        }
    };
}
项目:fixprotocol-test-suite    文件:ScriptRunner.java   
public static void main(String[] args) throws Exception {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    engine.eval(new FileReader("src/main/javascript/Example.js"));

    Compilable compilingEngine = (Compilable) engine;
    CompiledScript script = compilingEngine.compile(new FileReader(
            "src/main/javascript/Function.js"));

    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("date", new Date());
    bindings.put("out", System.out);
    for (Map.Entry me : bindings.entrySet()) {
        System.out.printf("%s: %s\n", me.getKey(),
                String.valueOf(me.getValue()));
    }
    script.eval(bindings);

    Invocable invocable = (Invocable) script.getEngine();
    invocable.invokeFunction("sayhello", "Jose");
}
项目:nashorn-backport    文件:NashornScriptEngine.java   
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
    final ScriptFunction func = compileImpl(source, context);
    return new CompiledScript() {
        @Override
        public Object eval(final ScriptContext ctxt) throws ScriptException {
            final ScriptObject global = getNashornGlobalFrom(ctxt);
            // Are we running the script in the correct global?
            if (func.getScope() == global) {
                return evalImpl(func, ctxt, global);
            } else {
                // ScriptContext with a different global. Compile again!
                // Note that we may still hit per-global compilation cache.
                return evalImpl(compileImpl(source, ctxt), ctxt, global);
            }
        }
        @Override
        public ScriptEngine getEngine() {
            return NashornScriptEngine.this;
        }
    };
}
项目:OC-LuaJ    文件:LuaScriptEngine.java   
@Override
public CompiledScript compile(Reader script) throws ScriptException {
    try {
        InputStream is = new Utf8Encoder(script);
        try {
            final Globals g = context.globals;
            final LuaFunction f = g.load(script, "script").checkfunction();
            return new LuajCompiledScript(f, g);
        } catch (LuaError lee) {
            throw new ScriptException(lee.getMessage());
        } finally {
            is.close();
        }
    } catch (Exception e) {
        throw new ScriptException("eval threw " + e.toString());
    }
}
项目:nashorn    文件:NashornScriptEngine.java   
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
    final ScriptFunction func = compileImpl(source, context);
    return new CompiledScript() {
        @Override
        public Object eval(final ScriptContext ctxt) throws ScriptException {
            final ScriptObject global = getNashornGlobalFrom(ctxt);
            // Are we running the script in the correct global?
            if (func.getScope() == global) {
                return evalImpl(func, ctxt, global);
            } else {
                // ScriptContext with a different global. Compile again!
                // Note that we may still hit per-global compilation cache.
                return evalImpl(compileImpl(source, ctxt), ctxt, global);
            }
        }
        @Override
        public ScriptEngine getEngine() {
            return NashornScriptEngine.this;
        }
    };
}
项目:ScriptBox    文件:WindowJavaScriptEngine.java   
@Override
public CompiledScript compile(Reader script) throws ScriptException {
    CompiledScript compiledScript = null;

    Context cx = enterContext();

    try {
        String filename = getFilenameFromReader(script);
        Script rhinoScript = cx.compileReader(script, filename, 1, null);
        compiledScript = new CompiledJavaScript(this, rhinoScript);
    } catch (Exception e) {
        throwWrappedScriptException(e);
    } finally {
        exitContext();
    }

    return compiledScript;
}
项目:openhab1-addons    文件:EBusTelegramParser.java   
/**
 * Evaluates the compiled script of a entry.
 * 
 * @param entry The configuration entry to evaluate
 * @param scopeValues All known values for script scope
 * @return The computed value
 * @throws ScriptException
 */
private Object evaluateScript(Entry<String, TelegramValue> entry, Map<String, Object> scopeValues)
        throws ScriptException {

    Object value = null;

    // executes compiled script
    if (entry.getValue().getCsript() != null) {
        CompiledScript cscript = entry.getValue().getCsript();

        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(scopeValues);
        value = cscript.eval(bindings);
    }

    // try to convert the returned value to BigDecimal
    value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value);

    // round to two digits, maybe not optimal for any result
    if (value instanceof BigDecimal) {
        ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    return value;
}
项目:jvarkit    文件:XmlFilterVariantFactory.java   
private JSPredigate compileJSPredigate(final String jsExpr) {
final javax.script.ScriptEngineManager manager = new javax.script.ScriptEngineManager();
final javax.script.ScriptEngine engine = manager.getEngineByName("js");
if(engine==null)
    {
    throw new JvarkitException.JavaScriptEngineNotFound();
    }
final javax.script.Compilable compilingEngine = (javax.script.Compilable)engine;
try {
    CompiledScript compiled = compilingEngine.compile(jsExpr);
    return new JSPredigate(compiled);
    }
catch(final Exception err)
    {
    throw new RuntimeException(err);
    }
}
项目:logging-log4j2    文件:ScriptManager.java   
public MainScriptRunner(final ScriptEngine scriptEngine, final AbstractScript script) {
    this.script = script;
    this.scriptEngine = scriptEngine;
    CompiledScript compiled = null;
    if (scriptEngine instanceof Compilable) {
        logger.debug("Script {} is compilable", script.getName());
        compiled = AccessController.doPrivileged(new PrivilegedAction<CompiledScript>() {
            @Override
            public CompiledScript run() {
                try {
                    return ((Compilable) scriptEngine).compile(script.getScriptText());
                } catch (final Throwable ex) {
                    /*
                     * ScriptException is what really should be caught here. However, beanshell's ScriptEngine
                     * implements Compilable but then throws Error when the compile method is called!
                     */
                    logger.warn("Error compiling script", ex);
                    return null;
                }
            }
        });
    }
    compiledScript = compiled;
}
项目:L2jBrasil    文件:L2ScriptEngineManager.java   
public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
{
    if (engine instanceof Compilable && ATTEMPT_COMPILATION)
    {
        Compilable eng = (Compilable) engine;
        CompiledScript cs = eng.compile(script);
        return context != null ? cs.eval(context) : cs.eval();
    } else
        return context != null ? engine.eval(script, context) : engine.eval(script);
}
项目:L2jBrasil    文件:CompiledScriptCache.java   
public CompiledScript loadCompiledScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException
{
    int len = L2ScriptEngineManager.SCRIPT_FOLDER.getPath().length() + 1;
    String relativeName = file.getPath().substring(len);
    CompiledScriptHolder csh = _compiledScriptCache.get(relativeName);
    if (csh != null && csh.matches(file))
    {
        if (Config.DEBUG)
            LOG.fine("Reusing cached compiled script: " + file);
        return csh.getCompiledScript();
    }
    else
    {
        if (Config.DEBUG)
            LOG.info("Compiling script: " + file);
        Compilable eng = (Compilable) engine;
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        // TODO lock file
        CompiledScript cs = eng.compile(reader);
        if (cs instanceof Serializable)
            synchronized (_compiledScriptCache)
            {
                _compiledScriptCache.put(relativeName, new CompiledScriptHolder(cs, file));
                _modified = true;
            }
        return cs;
    }
}
项目:L2jBrasil    文件:CompiledScriptHolder.java   
/**
 * @param compiledScript
 * @param lastModified
 * @param size
 */
public CompiledScriptHolder(CompiledScript compiledScript, long lastModified, long size)
{
    _compiledScript = compiledScript;
    _lastModified = lastModified;
    _size = size;
}