Java 类javax.script.Compilable 实例源码

项目: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    文件:ScriptExecutor.java   
/**
 * Construct a new script executors
 *
 * @param engine
 *            the script engine to use, must not be <code>null</code>
 * @param command
 *            the command to execute, may be <code>null</code>
 * @param classLoader
 *            the class loader to use when executing, may be
 *            <code>null</code>
 * @throws ScriptException
 */
public ScriptExecutor ( final ScriptEngine engine, final String command, final ClassLoader classLoader, final String sourceName ) throws Exception
{
    this.engine = engine;
    this.command = command;
    this.commandUrl = null;
    this.classLoader = classLoader;
    this.sourceName = sourceName;

    if ( command != null && engine instanceof Compilable && !Boolean.getBoolean ( PROP_NAME_DISABLE_COMPILE ) )
    {
        if ( sourceName != null )
        {
            engine.put ( ScriptEngine.FILENAME, sourceName );
        }

        Scripts.executeWithClassLoader ( classLoader, new Callable<Void> () {
            @Override
            public Void call () throws Exception
            {
                ScriptExecutor.this.compiledScript = ( (Compilable)engine ).compile ( command );
                return null;
            }
        } );
    }
}
项目:neoscada    文件:ScriptExecutor.java   
public ScriptExecutor ( final ScriptEngine engine, final URL commandUrl, final ClassLoader classLoader ) throws Exception
{
    this.engine = engine;
    this.command = null;
    this.commandUrl = commandUrl;
    this.classLoader = classLoader;
    this.sourceName = commandUrl.toString ();

    if ( commandUrl != null && engine instanceof Compilable && !Boolean.getBoolean ( PROP_NAME_DISABLE_COMPILE ) )
    {
        Scripts.executeWithClassLoader ( classLoader, new Callable<Void> () {

            @Override
            public Void call () throws Exception
            {
                ScriptExecutor.this.compiledScript = ( (Compilable)engine ).compile ( new InputStreamReader ( commandUrl.openStream () ) );
                return null;
            }
        } );
    }
}
项目:sponge    文件:NashornKnowledgeBaseInterpreter.java   
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    // ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine result = factory.getScriptEngine("-scripting");

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    PROCESSOR_CLASSES.forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, NashornPlugin.class, Plugin.class.getSimpleName());

    getStandardImportClasses().forEach(cls -> addImport(result, cls));

    result.put(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    eval(result, "load(\"classpath:" + INITIAL_SCRIPT + "\");");

    return result;
}
项目:sponge    文件:ScriptKotlinKnowledgeBaseInterpreter.java   
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    KotlinConstants.PROCESSOR_CLASSES
            .forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, KPlugin.class, Plugin.class.getSimpleName());

    // TODO The line below performs very slow in Kotlin
    eval(result, getStandardImportClasses().stream().map(cls -> "import " + cls.getName()).collect(Collectors.joining("\n")));

    setVariable(result, KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    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);
}
项目:4mila-1.0    文件:FormulaScript.java   
private void init() throws ProcessingException {

    // check formula
    if (StringUtility.isNullOrEmpty(StringUtility.trim(script))) {
      throw new VetoException(Texts.get("FormulaEmptyMessage"));
    }

    // Script
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // Compile Formula
    Compilable compilingEngine = (Compilable) engine;
    try {
      compiledScript = compilingEngine.compile(script);
    }
    catch (ScriptException e) {
      handleScriptException(e, script);
    }

    bindings = engine.createBindings();
  }
项目:LiteGraph    文件:ScriptRecordReader.java   
@Override
public void initialize(final InputSplit genericSplit, final TaskAttemptContext context) throws IOException {
    this.lineRecordReader.initialize(genericSplit, context);
    final Configuration configuration = context.getConfiguration();
    if (configuration.get(Constants.GREMLIN_HADOOP_GRAPH_FILTER, null) != null)
        this.graphFilter = VertexProgramHelper.deserialize(ConfUtil.makeApacheConfiguration(configuration), Constants.GREMLIN_HADOOP_GRAPH_FILTER);
    this.engine = new GremlinGroovyScriptEngine((CompilerCustomizerProvider) new DefaultImportCustomizerProvider());
    //this.engine = ScriptEngineCache.get(configuration.get(SCRIPT_ENGINE, ScriptEngineCache.DEFAULT_SCRIPT_ENGINE));
    final FileSystem fs = FileSystem.get(configuration);
    try (final InputStream stream = fs.open(new Path(configuration.get(SCRIPT_FILE)));
         final InputStreamReader reader = new InputStreamReader(stream)) {
        this.parse = String.join("\n", IOUtils.toString(reader), READ_CALL);
        script = ((Compilable) engine).compile(this.parse);
    } catch (ScriptException e) {
        throw new IOException(e.getMessage(), 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);
}
项目:scripturian    文件:Jsr223Scriptlet.java   
@Override
public void prepare() throws PreparationException
{
    if( adapter.isCompilable() )
    {
        ScriptEngine scriptEngine = adapter.getStaticScriptEngine();
        if( scriptEngine instanceof Compilable )
        {
            try
            {
                compiledScript = ( (Compilable) scriptEngine ).compile( sourceCode );
            }
            catch( ScriptException x )
            {
                String scriptEngineName = (String) adapter.getAttributes().get( Jsr223LanguageAdapter.JSR223_SCRIPT_ENGINE_NAME );
                throw new PreparationException( executable.getDocumentName(), startLineNumber, startColumnNumber, "Compilation error in " + scriptEngineName, x );
            }
        }
    }
}
项目:openhab-hdl    文件:EBusConfigurationProvider.java   
/**
 * Constructor
 */
public EBusConfigurationProvider() {
    final ScriptEngineManager mgr = new ScriptEngineManager();

    // load script engine if available
    if(mgr != null) {
        final ScriptEngine engine = mgr.getEngineByName("JavaScript");

        if(engine == null) {
            logger.warn("Unable to load \"JavaScript\" engine! Skip every eBus value calculated by JavaScript.");

        } else if (engine instanceof Compilable) {
            compEngine = (Compilable) engine;

        }
    }
}
项目:camunda-engine-dmn    文件:ExpressionCachingTest.java   
@Before
public void setup() {
  ScriptEngineManager scriptEngineManager = spy(new ScriptEngineManager());
  when(scriptEngineManager.getEngineByName(anyString())).then(new Answer<ScriptEngine>() {
    public ScriptEngine answer(InvocationOnMock invocation) throws Throwable {
      scriptEngineSpy = spy((ScriptEngine) invocation.callRealMethod());
      compilableSpy = (Compilable) scriptEngineSpy;
      return scriptEngineSpy;
    }
  });

  DefaultDmnEngineConfiguration configuration = new DefaultDmnEngineConfiguration();

  configuration.setScriptEngineResolver(new DefaultScriptEngineResolver(scriptEngineManager));
  configuration.init();


  elProviderSpy = spy(configuration.getElProvider());
  configuration.setElProvider(elProviderSpy);

  expressionEvaluationHandler = new ExpressionEvaluationHandler(configuration);
}
项目:contexttoolkit    文件:AttributeEvalParser.java   
/**
 * @see #instance(Attribute, String, Map)
 * @param attribute
 * @param scriptText
 * @param constVars
 */
private AttributeEvalParser(
        Attribute<T> attribute, 
        String scriptText, 
        Map<String, Comparable<?>> constVars) {
    this.attribute = attribute;
    this.type = (Class<T>) attribute.getType();
    this.scriptText = scriptText;

    manager = new ScriptEngineManager();
    engine = manager.getEngineByName("js"); // javascript

    // compile to make script run faster on each execution
    try {
        script = ((Compilable) engine).compile(scriptText);
    } catch (ScriptException e) {
        e.printStackTrace();
    }

    // bindings for vars
    bindings = engine.createBindings();

    // add vars from constants
    bindings.putAll(constVars);
}
项目: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);
    }
}
项目:tinkerpop    文件:ScriptRecordReader.java   
@Override
public void initialize(final InputSplit genericSplit, final TaskAttemptContext context) throws IOException {
    this.lineRecordReader.initialize(genericSplit, context);
    final Configuration configuration = context.getConfiguration();
    if (configuration.get(Constants.GREMLIN_HADOOP_GRAPH_FILTER, null) != null)
        this.graphFilter = VertexProgramHelper.deserialize(ConfUtil.makeApacheConfiguration(configuration), Constants.GREMLIN_HADOOP_GRAPH_FILTER);
    this.engine = manager.getEngineByName(configuration.get(SCRIPT_ENGINE, "gremlin-groovy"));
    final FileSystem fs = FileSystem.get(configuration);
    try (final InputStream stream = fs.open(new Path(configuration.get(SCRIPT_FILE)));
         final InputStreamReader reader = new InputStreamReader(stream)) {
        final String parse = String.join("\n", IOUtils.toString(reader), READ_CALL);
        script = ((Compilable) engine).compile(parse);
    } catch (ScriptException e) {
        throw new IOException(e.getMessage());
    }
}
项目: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));
}
项目: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));
}
项目: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");
}
项目:openhab1-addons    文件:EBusConfigurationProvider.java   
/**
 * Constructor
 */
public EBusConfigurationProvider() {
    final ScriptEngineManager mgr = new ScriptEngineManager();

    // load script engine if available
    if (mgr != null) {
        final ScriptEngine engine = mgr.getEngineByName("JavaScript");

        if (engine == null) {
            logger.warn("Unable to load \"JavaScript\" engine! Skip every eBus value calculated by JavaScript.");

        } else if (engine instanceof Compilable) {
            compEngine = (Compilable) engine;

        }
    }
}
项目: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;
}
项目:windup    文件:GraphvizWriter.java   
public GraphvizWriter(Graph graph) throws ScriptException, IOException
{
    super(graph);
    if (true)
    {
        throw new RuntimeException(
                    "Not yet implemented; this is unstable.  The javascript requires Int32Array, which isn't currently provided by Rhino.");
    }

    // precompile the javascript.
    StringBuilder builder = new StringBuilder();
    builder.append(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("vizjs/viz.js")));

    builder = new StringBuilder();
    builder.append("function Viz() { console.log('Hello World'); }");

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    String script = builder.toString();
    Compilable compilingEngine = (Compilable) engine;
    vizJsCompiled = compilingEngine.compile(builder.toString());
}
项目: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;
    }
}
项目:EatDubbo    文件:ScriptRouter.java   
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
项目:neoscada    文件:ScriptPage.java   
private CompiledScript makeScript ( final Object value ) throws Exception
{
    if ( value == null )
    {
        return null;
    }

    if ( this.engine == null )
    {
        this.engine = (Compilable)Scripts.createEngine ( "JavaScript", Activator.class.getClassLoader () ); //$NON-NLS-1$
    }

    return this.engine.compile ( (String)value );
}
项目:dubbo2    文件:ScriptRouter.java   
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
项目:github-test    文件:ScriptRouter.java   
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>) inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
项目:dubbox-hystrix    文件:ScriptRouter.java   
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
项目:openjdk-jdk10    文件:Test6.java   
public static void main(String[] args) throws Exception {
    System.out.println("\nTest6\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine engine = Helper.getJsEngine(m);
    if (engine == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }

    try (Reader reader = new FileReader(
        new File(System.getProperty("test.src", "."), "Test6.js"))) {
        engine.eval(reader);
    }
    Object res = engine.get("res");

    CompiledScript scr = null;
    try (Reader reader = new FileReader(
        new File(System.getProperty("test.src", "."), "Test6.js"))) {
        scr = ((Compilable)engine).compile(reader);
    }

    if (scr == null) {
        throw new RuntimeException("compilation failed!");
    }

    scr.eval();
    Object res1 = engine.get("res");
    if (! res.equals(res1)) {
        throw new RuntimeException("values not equal");
    }
}
项目:openjdk-jdk10    文件:ScriptEngineTest.java   
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
项目:dubbocloud    文件:ScriptRouter.java   
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
项目:iotplatform    文件:NashornJsEvaluator.java   
private static CompiledScript compileScript(String script) {
  ScriptEngine engine = factory.getScriptEngine(new String[] { "--no-java" });
  Compilable compEngine = (Compilable) engine;
  try {
    return compEngine.compile(script);
  } catch (ScriptException e) {
    log.warn("Failed to compile filter script: {}", e.getMessage(), e);
    throw new IllegalArgumentException("Can't compile script: " + e.getMessage());
  }
}
项目:openjdk9    文件:ScriptEngineTest.java   
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}
项目:scipio-erp    文件:ScriptUtil.java   
/**
 * Returns a compiled script.
 * 
 * @param filePath Script path and file name.
 * @return The compiled script, or <code>null</code> if the script engine does not support compilation.
 * @throws IllegalArgumentException
 * @throws ScriptException
 * @throws IOException
 */
public static CompiledScript compileScriptFile(String filePath) throws ScriptException, IOException {
    Assert.notNull("filePath", filePath);
    CompiledScript script = parsedScripts.get(filePath);
    if (script == null) {
        ScriptEngineManager manager = getScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension(getFileExtension(filePath));
        if (engine == null) {
            throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
        }
        engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
        try {
            Compilable compilableEngine = (Compilable) engine;
            URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(scriptUrl.openStream()));
            script = compilableEngine.compile(reader);
            if (Debug.verboseOn()) {
                Debug.logVerbose("Compiled script " + filePath + " using engine " + engine.getClass().getName(), module);
            }
        } catch (ClassCastException e) {
            if (Debug.verboseOn()) {
                Debug.logVerbose("Script engine " + engine.getClass().getName() + " does not implement Compilable", module);
            }
        }
        if (script != null) {
            parsedScripts.putIfAbsent(filePath, script);
        }
    }
    return script;
}
项目:scipio-erp    文件:ScriptUtil.java   
/**
 * Returns a compiled script.
 * 
 * @param language
 * @param script
 * @return The compiled script, or <code>null</code> if the script engine does not support compilation.
 * @throws IllegalArgumentException
 * @throws ScriptException
 */
public static CompiledScript compileScriptString(String language, String script) throws ScriptException {
    Assert.notNull("language", language, "script", script);
    String cacheKey = language.concat("://").concat(script);
    CompiledScript compiledScript = parsedScripts.get(cacheKey);
    if (compiledScript == null) {
        ScriptEngineManager manager = getScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(language);
        if (engine == null) {
            throw new IllegalArgumentException("The script type is not supported for language: " + language);
        }
        engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
        try {
            Compilable compilableEngine = (Compilable) engine;
            compiledScript = compilableEngine.compile(script);
            if (Debug.verboseOn()) {
                Debug.logVerbose("Compiled script [" + script + "] using engine " + engine.getClass().getName(), module);
            }
        } catch (ClassCastException e) {
            if (Debug.verboseOn()) {
                Debug.logVerbose("Script engine " + engine.getClass().getName() + " does not implement Compilable", module);
            }
        }
        if (compiledScript != null) {
            parsedScripts.putIfAbsent(cacheKey, compiledScript);
        }
    }
    return compiledScript;
}
项目:jCode    文件:EJSParser.java   
public EJSParser() {

        try {
            engine = new ScriptEngineManager().getEngineByName("nashorn");
            engine.eval("var window = this;"
                    + "var console = {\n"
                    + "  debug: print,\n"
                    + "  warn: print,\n"
                    + "  log: print\n"
                    + "};"
                    + "function contains(obj, a) {\n"
                    + "    for (var i = 0; i < a.length; i++) {\n"
                    + "        if (a[i] === obj) {\n"
                    + "            return true;\n"
                    + "        }\n"
                    + "    }\n"
                    + "    return false;\n"
                    + "}");

            //[].includes support
            engine.eval("Array.prototype.includes||Object.defineProperty(Array.prototype,\"includes\",{value:function(r,e){function t(r,e){return r===e||\"number\"==typeof r&&\"number\"==typeof e&&isNaN(r)&&isNaN(e)}if(null==this)throw new TypeError('\"this\" is null or not defined');var n=Object(this),i=n.length>>>0;if(0===i)return!1;for(var o=0|e,u=Math.max(o>=0?o:i-Math.abs(o),0);i>u;){if(t(n[u],r))return!0;u++}return!1}});");
            engine.eval("Array.prototype.forEach||(Array.prototype.forEach=function(r){var t,n;if(null==this)throw new TypeError(\"this is null or not defined\");var o=Object(this),e=o.length>>>0;if(\"function\"!=typeof r)throw new TypeError(r+\" is not a function\");for(arguments.length>1&&(t=arguments[1]),n=0;e>n;){var i;n in o&&(i=o[n],r.call(t,i,n,o)),n++}});");

            Compilable compilingEngine = (Compilable) engine;
            cscript = compilingEngine.compile(new BufferedReader(new InputStreamReader(EJSParser.class.getClassLoader().getResourceAsStream("org/netbeans/jcode/parser/ejs/resources/ejs.js"), "UTF-8")));
            bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
            cscript.eval(bindings);
        } catch (ScriptException | UnsupportedEncodingException ex) {
            Exceptions.printStackTrace(ex);
        }
    }