javax.script.Compilable Java Examples

The following examples show how to use javax.script.Compilable. 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: ScriptRecordReader.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #2
Source File: ExpressionCachingTest.java    From camunda-engine-dmn with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: KotlinScriptEngineTest.java    From dynkt with GNU Affero General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: OQLEngineImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = Scripting.newBuilder().allowAllAccess(true).build();
        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.INFO, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
 
Example #5
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: OQLEngineImpl.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
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.INFO, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
 
Example #7
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: ExpressionLanguageScriptEngineImpl.java    From oval with Eclipse Public License 2.0 6 votes vote down vote up
protected ExpressionLanguageScriptEngineImpl(final ScriptEngine engine) {
   this.engine = engine;
   if (engine instanceof Compilable) {
      compilable = (Compilable) engine;
      compiledCache = new ObjectCache<String, CompiledScript>() {
         @Override
         protected CompiledScript load(final String expression) {
            try {
               return compilable.compile(expression);
            } catch (final ScriptException ex) {
               throw new ExpressionEvaluationException("Parsing " + engine.get(ScriptEngine.NAME) + " expression failed: " + expression, ex);
            }
         }
      };
   } else {
      compilable = null;
      compiledCache = null;
   }
}
 
Example #10
Source File: ScriptExecutor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
            }
        } );
    }
}
 
Example #11
Source File: ScriptExecutor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
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;
            }
        } );
    }
}
 
Example #12
Source File: ScopeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: JavaScriptParser.java    From AutoLoadCache with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #15
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 6 votes vote down vote up
@Test
public void test_bsh_script_engine_compile_return_this() throws Throwable {
    class CompiledMethod {
        Object bshThis;
        Method invokeMethod;
        CompiledMethod() throws Throwable {
            Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
            assertNotNull( engine );
            CompiledScript script = engine.compile("square(x) { return x*x; } return this;");
            bshThis = script.eval();
            invokeMethod = bshThis.getClass().getMethod("invokeMethod", new Class[] {String.class, Object[].class});
        }
        int square(int x) throws Throwable {
            return (int) invokeMethod.invoke(bshThis, new Object[] {"square", new Object[] {x}});
        }
    }
    CompiledMethod cm = new CompiledMethod();
    assertEquals(16, cm.square(4));
    assertEquals(25, cm.square(5));
}
 
Example #16
Source File: ScriptRouter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example #17
Source File: ScriptEngineTests.java    From luaj with MIT License 5 votes vote down vote up
public void testCompiledScript() throws ScriptException {
          CompiledScript cs = ((Compilable)e).compile("z = math.sqrt(x); return z");
          
          b.put("x", 144);
          assertEquals(12, cs.eval(b));
          assertEquals(12, b.get("z"));

          b.put("x", 25);
          assertEquals(5, cs.eval(c));
          assertEquals(5, b.get("z"));
}
 
Example #18
Source File: ExpressionEvaluationHandler.java    From camunda-engine-dmn with Apache License 2.0 5 votes vote down vote up
protected Object evaluateScriptExpression(String expressionLanguage, VariableContext variableContext, String expressionText, CachedCompiledScriptSupport cachedCompiledScriptSupport) {
  ScriptEngine scriptEngine = getScriptEngineForName(expressionLanguage);
  // wrap script engine bindings + variable context and pass enhanced
  // bindings to the script engine.
  Bindings bindings = VariableContextScriptBindings.wrap(scriptEngine.createBindings(), variableContext);
  bindings.put("variableContext", variableContext);

  try {
    if (scriptEngine instanceof Compilable) {

      CompiledScript compiledScript = cachedCompiledScriptSupport.getCachedCompiledScript();
      if (compiledScript == null) {
        synchronized (cachedCompiledScriptSupport) {
          compiledScript = cachedCompiledScriptSupport.getCachedCompiledScript();

          if(compiledScript == null) {
            Compilable compilableScriptEngine = (Compilable) scriptEngine;
            compiledScript = compilableScriptEngine.compile(expressionText);

            cachedCompiledScriptSupport.cacheCompiledScript(compiledScript);
          }
        }
      }

      return compiledScript.eval(bindings);
    }
    else {
      return scriptEngine.eval(expressionText, bindings);
    }
  }
  catch (ScriptException e) {
    throw LOG.unableToEvaluateExpression(expressionText, scriptEngine.getFactory().getLanguageName(), e);
  }
}
 
Example #19
Source File: ScriptEngineSample.java    From luaj with MIT License 5 votes vote down vote up
public static void testBindings(ScriptEngine e, Bindings b) throws ScriptException {
    CompiledScript cs = ((Compilable)e).compile(
    		"print( 'somejavaint', type(somejavaint), somejavaint )\n" +
    		"print( 'somejavadouble', type(somejavadouble), somejavadouble )\n" +
    		"print( 'somejavastring', type(somejavastring), somejavastring )\n" +
    		"print( 'somejavaobject', type(somejavaobject), somejavaobject )\n" +
    		"print( 'somejavaarray', type(somejavaarray), somejavaarray, somejavaarray[1] )\n" +
    		"someluaint = 444\n" +
    		"someluadouble = 555.666\n" +
    		"someluastring = 'def'\n" +
    		"someluauserdata = somejavaobject\n" +
    		"someluatable = { 999, 111 }\n" +
    		"someluafunction = function(x) print( 'hello, world', x ) return 678 end\n" +
    		"" );
    b.put("somejavaint", 111);
    b.put("somejavadouble", 222.333);
    b.put("somejavastring", "abc");
    b.put("somejavaobject", new SomeUserClass());
    b.put("somejavaarray", new int[] { 777, 888 } );
    System.out.println( "eval: "+cs.eval(b) );
    Object someluaint = b.get("someluaint");
    Object someluadouble = b.get("someluaint");
    Object someluastring = b.get("someluastring");
    Object someluauserdata = b.get("someluauserdata");
    Object someluatable = b.get("someluatable");
    Object someluafunction = b.get("someluafunction");
    System.out.println( "someluaint: "+someluaint.getClass()+" "+someluaint );
    System.out.println( "someluadouble: "+someluadouble.getClass()+" "+someluadouble );
    System.out.println( "someluastring: "+someluastring.getClass()+" "+someluastring );
    System.out.println( "someluauserdata: "+someluauserdata.getClass()+" "+someluauserdata );
    System.out.println( "someluatable: "+someluatable.getClass()+" "+someluatable );
    System.out.println( "someluafunction: "+someluafunction.getClass()+" "+someluafunction );
    System.out.println( "someluafunction(345): "+((LuaValue) someluafunction).call(LuaValue.valueOf(345)) );
}
 
Example #20
Source File: ScriptEngineSample.java    From luaj with MIT License 5 votes vote down vote up
public static void testUserClasses(ScriptEngine e) throws ScriptException {
    CompiledScript cs = ((Compilable)e).compile(
    		"test = test or luajava.newInstance(\"java.lang.String\", \"test\")\n" +
    		"print( 'test', type(test), test, tostring(test) )\n" +
    		"return tostring(test)");
    Bindings b = e.createBindings();
    Object resultstring = cs.eval(b);
    b.put("test", new SomeUserClass());
    Object resultuserclass = cs.eval(b);
    System.out.println( "eval(string): "+resultstring.getClass()+" "+resultstring );
    System.out.println( "eval(userclass): "+resultuserclass.getClass()+" "+resultuserclass );        
}
 
Example #21
Source File: ScriptEngineTests.java    From luaj with MIT License 5 votes vote down vote up
public void testReturnMultipleValues() throws ScriptException {
       CompiledScript cs = ((Compilable)e).compile("return 'foo', 'bar'\n");
       Object o = cs.eval();
       assertEquals(Object[].class, o.getClass());
       Object[] array = (Object[]) o;
       assertEquals(2, array.length);
       assertEquals("foo", array[0]);
       assertEquals("bar", array[1]);
}
 
Example #22
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 5 votes vote down vote up
@Test
public void test_bsh_script_engine_compile() throws Throwable {
    Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
    assertNotNull( engine );
    CompiledScript script = engine.compile(new StringReader("return 42;"));
    assertEquals(42, script.eval());
}
 
Example #23
Source File: ScriptRouter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example #24
Source File: InteractiveConsole.java    From jupyter-kernel-jsr223 with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param codeString source code which is evaluted by the ScriptEngine
 * @return result of the evaluation
 *
 */
@Override
public Object eval(String codeString) {
    CompiledScript compiledScript;
    ex = null;
    try {
        compiledScript = ((Compilable) engine).compile(codeString);
        return compiledScript.eval();
    } catch (ScriptException e) {
        ex = e;
        setErrorMessage();
    }
    return null;
}
 
Example #25
Source File: ScriptEngineTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #26
Source File: ScriptRouter.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example #27
Source File: SpinxFunction.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	Bindings bindings = scriptEngine.createBindings();
	for (int i = 0; i < args.length; i++) {
		Argument argument = arguments.get(i);
		Value arg = args[i];
		Object jsArg;
		if (arg instanceof Literal) {
			Literal argLiteral = (Literal) arg;
			if (XMLSchema.INTEGER.equals(argLiteral.getDatatype())) {
				jsArg = argLiteral.intValue();
			} else if (XMLSchema.DECIMAL.equals(argLiteral.getDatatype())) {
				jsArg = argLiteral.doubleValue();
			} else {
				jsArg = argLiteral.getLabel();
			}
		} else {
			jsArg = arg.stringValue();
		}
		bindings.put(argument.getPredicate().getLocalName(), jsArg);
	}

	Object result;
	try {
		if (compiledScript == null && scriptEngine instanceof Compilable) {
			compiledScript = ((Compilable) scriptEngine).compile(script);
		}
		if (compiledScript != null) {
			result = compiledScript.eval(bindings);
		} else {
			result = scriptEngine.eval(script, bindings);
		}
	} catch (ScriptException e) {
		throw new ValueExprEvaluationException(e);
	}

	ValueFactory vf = ValueFactoryImpl.getInstance();
	return (returnType != null) ? vf.createLiteral(result.toString(), returnType) : vf.createURI(result.toString());
}
 
Example #28
Source File: ScriptEngineTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #29
Source File: ScriptEngineTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #30
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
        String fileExtension = getFileExtension(filePath); // SCIPIO: slight refactor
        if ("bsh".equalsIgnoreCase(fileExtension)) { // SCIPIO: 2018-09-19: Warn here, there's nowhere else we can do it...
            Debug.logWarning("Deprecated Beanshell script file invoked (" + filePath + "); "
                    + "this is a compatibility mode only (runs as Groovy); please convert to Groovy script", module);
            fileExtension = "groovy";
        }
        ScriptEngine engine = manager.getEngineByExtension(fileExtension);
        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(), UtilIO
                .getUtf8()));
            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;
}