java类javax.script.Compilable的实例源码

ScopeTest.java 文件源码 项目:openjdk-jdk10 阅读 25 收藏 0 点赞 0 评论 0
@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);
}
OQLEngineImpl.java 文件源码 项目:incubator-netbeans 阅读 18 收藏 0 点赞 0 评论 0
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);
    }
}
ScriptExecutor.java 文件源码 项目:neoscada 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 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;
            }
        } );
    }
}
ScriptExecutor.java 文件源码 项目:neoscada 阅读 23 收藏 0 点赞 0 评论 0
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;
            }
        } );
    }
}
NashornKnowledgeBaseInterpreter.java 文件源码 项目:sponge 阅读 16 收藏 0 点赞 0 评论 0
@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;
}
ScriptKotlinKnowledgeBaseInterpreter.java 文件源码 项目:sponge 阅读 16 收藏 0 点赞 0 评论 0
@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;
}
ScriptEngineTest.java 文件源码 项目:csvsum 阅读 20 收藏 0 点赞 0 评论 0
@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);
}
FormulaScript.java 文件源码 项目:4mila-1.0 阅读 23 收藏 0 点赞 0 评论 0
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();
  }
ScriptRecordReader.java 文件源码 项目:LiteGraph 阅读 28 收藏 0 点赞 0 评论 0
@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);
    }
}
ScopeTest.java 文件源码 项目:lookaside_java-1.8.0-openjdk 阅读 19 收藏 0 点赞 0 评论 0
@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);
}
ScopeTest.java 文件源码 项目:jdk8u_nashorn 阅读 18 收藏 0 点赞 0 评论 0
@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);
}
Jsr223Scriptlet.java 文件源码 项目:scripturian 阅读 17 收藏 0 点赞 0 评论 0
@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 );
            }
        }
    }
}
EBusConfigurationProvider.java 文件源码 项目:openhab-hdl 阅读 16 收藏 0 点赞 0 评论 0
/**
 * 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;

        }
    }
}
ExpressionCachingTest.java 文件源码 项目:camunda-engine-dmn 阅读 17 收藏 0 点赞 0 评论 0
@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);
}
AttributeEvalParser.java 文件源码 项目:contexttoolkit 阅读 19 收藏 0 点赞 0 评论 0
/**
 * @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);
}
KotlinScriptEngineTest.java 文件源码 项目:dynkt 阅读 20 收藏 0 点赞 0 评论 0
@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());
}
JavaScriptParser.java 文件源码 项目:AutoLoadCache 阅读 28 收藏 0 点赞 0 评论 0
@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);
    }
}
ScriptRecordReader.java 文件源码 项目:tinkerpop 阅读 21 收藏 0 点赞 0 评论 0
@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());
    }
}
NashornTests.java 文件源码 项目:elasticsearch-lang-javascript-nashorn 阅读 18 收藏 0 点赞 0 评论 0
@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));
}
NashornTests.java 文件源码 项目:elasticsearch-lang-javascript-nashorn 阅读 15 收藏 0 点赞 0 评论 0
@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));
}
V8EngineTest.java 文件源码 项目:gameserver 阅读 17 收藏 0 点赞 0 评论 0
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));
}
ScriptRunner.java 文件源码 项目:fixprotocol-test-suite 阅读 25 收藏 0 点赞 0 评论 0
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");
}
EBusConfigurationProvider.java 文件源码 项目:openhab1-addons 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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;

        }
    }
}
ScriptManager.java 文件源码 项目:logging-log4j2 阅读 24 收藏 0 点赞 0 评论 0
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;
}
GraphvizWriter.java 文件源码 项目:windup 阅读 17 收藏 0 点赞 0 评论 0
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());
}
L2ScriptEngineManager.java 文件源码 项目:L2jBrasil 阅读 23 收藏 0 点赞 0 评论 0
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);
}
CompiledScriptCache.java 文件源码 项目:L2jBrasil 阅读 19 收藏 0 点赞 0 评论 0
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;
    }
}
ScriptRouter.java 文件源码 项目:EatDubbo 阅读 22 收藏 0 点赞 0 评论 0
@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;
    }
}
ScriptPage.java 文件源码 项目:neoscada 阅读 15 收藏 0 点赞 0 评论 0
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 );
}
ScriptRouter.java 文件源码 项目:dubbo2 阅读 17 收藏 0 点赞 0 评论 0
@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;
    }
}


问题


面经


文章

微信
公众号

扫码关注公众号