Search in sources :

Example 71 with ScriptContext

use of javax.script.ScriptContext in project tomee by apache.

the class OpenEJBScripter method evaluate.

public Object evaluate(final String language, final String script, final ScriptContext context) throws ScriptException {
    if (!ENGINE_FACTORIES.containsKey(language)) {
        throw new IllegalArgumentException("can't find factory for language " + language + ". You probably need to add the jar to openejb libs.");
    }
    ScriptContext executionContext = context;
    if (executionContext == null) {
        executionContext = new SimpleScriptContext();
    }
    // we bind local variables (per execution) every time we execute a script
    bindLocal(executionContext);
    final ScriptEngine engine = engine(language);
    return engine.eval(script, executionContext);
}
Also used : SimpleScriptContext(javax.script.SimpleScriptContext) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) ScriptEngine(javax.script.ScriptEngine)

Example 72 with ScriptContext

use of javax.script.ScriptContext in project webmagic by code4craft.

the class ScriptProcessor method process.

@Override
public void process(Page page) {
    ScriptEngine engine = enginePool.getEngine();
    try {
        ScriptContext context = engine.getContext();
        context.setAttribute("page", page, ScriptContext.ENGINE_SCOPE);
        context.setAttribute("config", site, ScriptContext.ENGINE_SCOPE);
        try {
            switch(language) {
                case JavaScript:
                    engine.eval(defines + "\n" + script, context);
                    // }
                    break;
                case JRuby:
                    RubyHash oRuby = (RubyHash) engine.eval(defines + "\n" + script, context);
                    Iterator itruby = oRuby.entrySet().iterator();
                    while (itruby.hasNext()) {
                        Map.Entry pairs = (Map.Entry) itruby.next();
                        page.getResultItems().put(pairs.getKey().toString(), pairs.getValue());
                    }
                    break;
                case Jython:
                    engine.eval(defines + "\n" + script, context);
                    PyDictionary oJython = (PyDictionary) engine.get("result");
                    Iterator it = oJython.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry pairs = (Map.Entry) it.next();
                        page.getResultItems().put(pairs.getKey().toString(), pairs.getValue());
                    }
                    break;
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    } finally {
        enginePool.release(engine);
    }
}
Also used : ScriptException(javax.script.ScriptException) RubyHash(org.jruby.RubyHash) Iterator(java.util.Iterator) ScriptContext(javax.script.ScriptContext) PyDictionary(org.python.core.PyDictionary) Map(java.util.Map) ScriptEngine(javax.script.ScriptEngine)

Example 73 with ScriptContext

use of javax.script.ScriptContext in project proxyee-down by monkeyWie.

the class ExtensionUtil method invoke.

/**
 * 运行一个js方法
 */
public static Object invoke(ExtensionInfo extensionInfo, Event event, Object param, boolean async) throws NoSuchMethodException, ScriptException, FileNotFoundException, InterruptedException {
    // 初始化js引擎
    ScriptEngine engine = ExtensionUtil.buildExtensionRuntimeEngine(extensionInfo);
    Invocable invocable = (Invocable) engine;
    // 执行resolve方法
    Object result = invocable.invokeFunction(StringUtils.isEmpty(event.getMethod()) ? event.getOn() : event.getMethod(), param);
    // 结果为null或者异步调用直接返回
    if (result == null || async) {
        return result;
    }
    final Object[] ret = { null };
    // 判断是不是返回Promise对象
    ScriptContext ctx = new SimpleScriptContext();
    ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE);
    boolean isPromise = (boolean) engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx);
    if (isPromise) {
        // 如果是返回的Promise则等待执行完成
        CountDownLatch countDownLatch = new CountDownLatch(1);
        invocable.invokeMethod(result, "then", (Function) o -> {
            try {
                ret[0] = o;
            } catch (Exception e) {
                LOGGER.error("An exception occurred while resolve()", e);
            } finally {
                countDownLatch.countDown();
            }
            return null;
        });
        invocable.invokeMethod(result, "catch", (Function) o -> {
            countDownLatch.countDown();
            return null;
        });
        // 等待解析完成
        countDownLatch.await();
    } else {
        ret[0] = result;
    }
    return ret[0];
}
Also used : ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) LoggerFactory(org.slf4j.LoggerFactory) TaskForm(org.pdown.rest.form.TaskForm) SimpleScriptContext(javax.script.SimpleScriptContext) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) FileUtil(org.pdown.core.util.FileUtil) Meta(org.pdown.gui.extension.Meta) Event(org.pdown.gui.extension.HookScript.Event) Path(java.nio.file.Path) ScriptException(javax.script.ScriptException) ExtensionContent(org.pdown.gui.extension.ExtensionContent) OutputStream(java.io.OutputStream) NativeController(org.pdown.gui.http.controller.NativeController) Logger(org.slf4j.Logger) Files(java.nio.file.Files) DownApplication(org.pdown.gui.DownApplication) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) HookScript(org.pdown.gui.extension.HookScript) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ScriptContext(javax.script.ScriptContext) ConfigUtil(org.pdown.gui.util.ConfigUtil) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHandlerUtil(org.pdown.gui.http.util.HttpHandlerUtil) Invocable(javax.script.Invocable) AppUtil(org.pdown.gui.util.AppUtil) Paths(java.nio.file.Paths) ScriptEngine(javax.script.ScriptEngine) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) JavascriptEngine(org.pdown.gui.extension.jsruntime.JavascriptEngine) PDownConfigContent(org.pdown.gui.content.PDownConfigContent) InputStream(java.io.InputStream) StringUtils(org.springframework.util.StringUtils) Invocable(javax.script.Invocable) SimpleScriptContext(javax.script.SimpleScriptContext) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) CountDownLatch(java.util.concurrent.CountDownLatch) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 74 with ScriptContext

use of javax.script.ScriptContext in project proxyee-down by monkeyWie.

the class JavascriptEngine method main.

public static void main(String[] args) throws ScriptException, NoSuchMethodException, JsonProcessingException, InterruptedException {
    ScriptEngine engine = buildEngine();
    Invocable invocable = (Invocable) engine;
    engine.eval("load('E:/study/extensions/bilibili-helper/dist/hook.js')");
    HttpRequestForm requestForm = new HttpRequestForm();
    requestForm.setUrl("https://www.bilibili.com/video/av34765642");
    Object result = invocable.invokeFunction("error");
    ScriptContext ctx = new SimpleScriptContext();
    ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE);
    System.out.println(engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx));
}
Also used : Invocable(javax.script.Invocable) SimpleScriptContext(javax.script.SimpleScriptContext) HttpRequestForm(org.pdown.rest.form.HttpRequestForm) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) ScriptEngine(javax.script.ScriptEngine)

Example 75 with ScriptContext

use of javax.script.ScriptContext in project OpenAM by OpenRock.

the class RhinoScriptEngine method compile.

/**
     * {@inheritDoc}
     */
@Override
public CompiledScript compile(final Reader reader) throws ScriptException {
    Reject.ifNull(reader);
    final Context context = factory.getContext();
    try {
        // Use configured ScriptContext from parent class, if specified
        final String filename = getFilename(getContext());
        final Script compiledScript = context.compileReader(reader, filename, 1, null);
        return new RhinoCompiledScript(this, compiledScript);
    } catch (RhinoException ex) {
        throw convertException(ex);
    } catch (IOException ex) {
        throw new ScriptException(ex);
    } finally {
        factory.releaseContext(context);
    }
}
Also used : Context(org.mozilla.javascript.Context) ScriptContext(javax.script.ScriptContext) Script(org.mozilla.javascript.Script) CompiledScript(javax.script.CompiledScript) ScriptException(javax.script.ScriptException) RhinoException(org.mozilla.javascript.RhinoException) IOException(java.io.IOException)

Aggregations

ScriptContext (javax.script.ScriptContext)126 SimpleScriptContext (javax.script.SimpleScriptContext)83 Bindings (javax.script.Bindings)33 Test (org.junit.Test)30 SimpleBindings (javax.script.SimpleBindings)28 Test (org.junit.jupiter.api.Test)19 ScriptEngine (javax.script.ScriptEngine)18 ScriptException (javax.script.ScriptException)18 HashMap (java.util.HashMap)13 CompiledScript (javax.script.CompiledScript)11 IOException (java.io.IOException)9 Map (java.util.Map)8 ScriptEngineManager (javax.script.ScriptEngineManager)8 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)7 Test (org.testng.annotations.Test)7 StringWriter (java.io.StringWriter)6 NashornScriptEngine (jdk.nashorn.api.scripting.NashornScriptEngine)6 XWikiException (com.xpn.xwiki.XWikiException)5 Reader (java.io.Reader)5 StringReader (java.io.StringReader)5