Search in sources :

Example 31 with Invocable

use of javax.script.Invocable 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 32 with Invocable

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

the class JavascriptEngine method buildEngine.

public static ScriptEngine buildEngine() throws ScriptException, NoSuchMethodException {
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine engine = factory.getScriptEngine(new SafeClassFilter());
    Window window = new Window();
    Object global = engine.eval("this");
    Object jsObject = engine.eval("Object");
    Invocable invocable = (Invocable) engine;
    invocable.invokeMethod(jsObject, "bindProperties", global, window);
    engine.eval("var window = this");
    return engine;
}
Also used : Window(org.pdown.gui.extension.jsruntime.polyfill.Window) NashornScriptEngineFactory(jdk.nashorn.api.scripting.NashornScriptEngineFactory) Invocable(javax.script.Invocable) ScriptEngine(javax.script.ScriptEngine)

Example 33 with Invocable

use of javax.script.Invocable in project rivescript-java by aichaos.

the class Jsr223ScriptingHandler method call.

/**
 * {@inheritDoc}
 */
@Override
public String call(RiveScript rs, String name, String[] fields) {
    String result = null;
    if (scriptEngine == null) {
        logger.warn("Cannot call macro '{}' as no script engine was found for '{}'", name, engineName);
    } else {
        long startTime = System.currentTimeMillis();
        // Invoke the function in the script engine.
        try {
            Invocable invocable = (Invocable) scriptEngine;
            Object value = invocable.invokeFunction(resolveFunctionName(name), rs, fields);
            if (value != null) {
                result = value.toString();
            }
            if (logger.isDebugEnabled()) {
                long elapsedTime = System.currentTimeMillis() - startTime;
                if (result == null) {
                    logger.debug("Returned null from macro '{}' in {} ms", name, elapsedTime);
                } else {
                    logger.debug("Returned '{}' from macro '{}' in {} ms", result, name, elapsedTime);
                }
            }
        } catch (ScriptException e) {
            logger.error("Error invoking function for macro '{}'", name, e);
        } catch (NoSuchMethodException e) {
            logger.error("Error invoking function for macro '{}'", name, e);
        }
    }
    return result;
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException)

Example 34 with Invocable

use of javax.script.Invocable in project spring-framework by spring-projects.

the class ScriptTemplateView method renderMergedOutputModel.

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        ScriptEngine engine = getEngine();
        Invocable invocable = (Invocable) engine;
        String url = getUrl();
        String template = getTemplate(url);
        Function<String, String> templateLoader = path -> {
            try {
                return getTemplate(path);
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        };
        RenderingContext context = new RenderingContext(this.getApplicationContext(), this.locale, templateLoader, url);
        Object html;
        if (this.renderObject != null) {
            Object thiz = engine.eval(this.renderObject);
            html = invocable.invokeMethod(thiz, this.renderFunction, template, model, context);
        } else {
            html = invocable.invokeFunction(this.renderFunction, template, model, context);
        }
        response.getWriter().write(String.valueOf(html));
    } catch (ScriptException ex) {
        throw new ServletException("Failed to render script template", new StandardScriptEvalException(ex));
    }
}
Also used : Arrays(java.util.Arrays) ServletException(javax.servlet.ServletException) BeanFactoryUtils(org.springframework.beans.factory.BeanFactoryUtils) HashMap(java.util.HashMap) ApplicationContextException(org.springframework.context.ApplicationContextException) Function(java.util.function.Function) StandardScriptUtils(org.springframework.scripting.support.StandardScriptUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) Charset(java.nio.charset.Charset) Locale(java.util.Locale) Map(java.util.Map) ScriptException(javax.script.ScriptException) Resource(org.springframework.core.io.Resource) ResourceLoader(org.springframework.core.io.ResourceLoader) ObjectUtils(org.springframework.util.ObjectUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScriptEngineManager(javax.script.ScriptEngineManager) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) StandardCharsets(java.nio.charset.StandardCharsets) NamedThreadLocal(org.springframework.core.NamedThreadLocal) Invocable(javax.script.Invocable) AbstractUrlBasedView(org.springframework.web.servlet.view.AbstractUrlBasedView) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ScriptEngine(javax.script.ScriptEngine) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) FileCopyUtils(org.springframework.util.FileCopyUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) ServletException(javax.servlet.ServletException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine)

Example 35 with Invocable

use of javax.script.Invocable in project lucene-solr by apache.

the class StatelessScriptUpdateProcessorFactory method initEngines.

//================================================ Helper Methods ==================================================
/**
   * Initializes a list of script engines - an engine per script file.
   *
   * @param req The solr request.
   * @param rsp The solr response
   * @return The list of initialized script engines.
   */
private List<EngineInfo> initEngines(SolrQueryRequest req, SolrQueryResponse rsp) throws SolrException {
    List<EngineInfo> scriptEngines = new ArrayList<>();
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager(resourceLoader.getClassLoader());
    scriptEngineManager.put("logger", log);
    scriptEngineManager.put("req", req);
    scriptEngineManager.put("rsp", rsp);
    if (params != null) {
        scriptEngineManager.put("params", params);
    }
    for (ScriptFile scriptFile : scriptFiles) {
        ScriptEngine engine = null;
        if (null != engineName) {
            engine = scriptEngineManager.getEngineByName(engineName);
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, false);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by name: " + engineName + (null != details ? " -- supported names: " + details : ""));
            }
        } else {
            engine = scriptEngineManager.getEngineByExtension(scriptFile.getExtension());
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, true);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by file extension: " + scriptFile.getFileName() + (null != details ? " -- supported extensions: " + details : ""));
            }
        }
        if (!(engine instanceof Invocable)) {
            String msg = "Engine " + ((null != engineName) ? engineName : ("for script " + scriptFile.getFileName())) + " does not support function invocation (via Invocable): " + engine.getClass().toString() + " (" + engine.getFactory().getEngineName() + ")";
            log.error(msg);
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);
        }
        if (scriptEngineCustomizer != null) {
            scriptEngineCustomizer.customize(engine);
        }
        scriptEngines.add(new EngineInfo((Invocable) engine, scriptFile));
        try {
            Reader scriptSrc = scriptFile.openReader(resourceLoader);
            try {
                engine.eval(scriptSrc);
            } catch (ScriptException e) {
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to evaluate script: " + scriptFile.getFileName(), e);
            } finally {
                IOUtils.closeQuietly(scriptSrc);
            }
        } catch (IOException ioe) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to evaluate script: " + scriptFile.getFileName(), ioe);
        }
    }
    return scriptEngines;
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ArrayList(java.util.ArrayList) ScriptEngineManager(javax.script.ScriptEngineManager) Reader(java.io.Reader) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine) SolrException(org.apache.solr.common.SolrException)

Aggregations

Invocable (javax.script.Invocable)68 ScriptException (javax.script.ScriptException)41 ScriptEngine (javax.script.ScriptEngine)30 ScriptEngineManager (javax.script.ScriptEngineManager)22 IOException (java.io.IOException)19 File (java.io.File)10 InputStreamReader (java.io.InputStreamReader)10 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)10 FileReader (java.io.FileReader)9 Reader (java.io.Reader)9 Compilable (javax.script.Compilable)5 CompiledScript (javax.script.CompiledScript)5 BufferedReader (java.io.BufferedReader)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Bindings (javax.script.Bindings)4 ScriptContext (javax.script.ScriptContext)4 Writer (java.io.Writer)3 SimpleScriptContext (javax.script.SimpleScriptContext)3 ValidationResult (org.apache.nifi.components.ValidationResult)3