Search in sources :

Example 96 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project yyl_example by Relucent.

the class Java8JsTester method main.

public static void main(String[] args) {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
    try {
        String script = //
        "" + " var T = Java.type('" + Java8JsTester.class.getName() + //
        "'); \n" + //
        " T.test1(); \n" + //
        " var map = new java.util.HashMap(); \n" + //
        " map.put('k1','V1'); \n" + //
        " map.put('k2','V2'); \n" + //
        " map.put('k3','V3'); \n" + //
        " print(map); \n" + //
        " map.remove('k3'); \n" + //
        " print(map); \n" + " map;";
        Object result = nashorn.eval(script);
        System.out.println("result\n type->" + result.getClass());
        System.out.println(result);
    } catch (ScriptException e) {
        e.printStackTrace();
    }
}
Also used : ScriptException(javax.script.ScriptException) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 97 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project bnd by bndtools.

the class Macro method _js.

public Object _js(String[] args) throws Exception {
    verifyCommand(args, _js, null, 2, Integer.MAX_VALUE);
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < args.length; i++) sb.append(args[i]).append(';');
    if (context == null) {
        synchronized (this) {
            if (engine == null)
                engine = new ScriptEngineManager().getEngineByName("javascript");
        }
        context = engine.getContext();
        bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("domain", domain);
        String javascript = domain.mergeProperties("javascript", ";");
        if (javascript != null && javascript.length() > 0) {
            engine.eval(javascript, context);
        }
        context.setErrorWriter(stderr);
        context.setWriter(stdout);
    }
    Object eval = engine.eval(sb.toString(), context);
    StringBuffer buffer = stdout.getBuffer();
    if (buffer.length() > 0) {
        domain.error("Executing js: %s: %s", sb, buffer);
        buffer.setLength(0);
    }
    if (eval != null) {
        return toString(eval);
    }
    String out = stdout.toString();
    stdout.getBuffer().setLength(0);
    return out;
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager)

Example 98 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project sling by apache.

the class ScriptableHealthCheckTest method assertExpression.

private void assertExpression(String expression, String languageExtension, boolean expected) throws Exception {
    final ScriptEngine rhino = new ScriptEngineManager().getEngineByExtension("js");
    assertNotNull("With the rhino jar in our classpath, we should get a js script engine", rhino);
    final ScriptEngineManager manager = Mockito.mock(ScriptEngineManager.class);
    Mockito.when(manager.getEngineByExtension(Matchers.same("ecma"))).thenReturn(rhino);
    final Field f = hc.getClass().getDeclaredField("scriptEngineManager");
    f.setAccessible(true);
    f.set(hc, manager);
    props.put(ScriptableHealthCheck.PROP_EXPRESSION, expression);
    if (languageExtension != null) {
        props.put(ScriptableHealthCheck.PROP_LANGUAGE_EXTENSION, languageExtension);
    }
    Mockito.when(ctx.getProperties()).thenReturn(props);
    hc.activate(ctx);
    final Result r = hc.execute();
    assertEquals("Expecting result " + expected, expected, r.isOk());
}
Also used : Field(java.lang.reflect.Field) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine) Result(org.apache.sling.hc.api.Result)

Example 99 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project cas by apereo.

the class ScriptingUtils method executeGroovyScriptEngine.

/**
 * Execute groovy script engine t.
 *
 * @param <T>        the type parameter
 * @param scriptFile the script file
 * @param args       the args
 * @param clazz      the clazz
 * @return the t
 */
public static <T> T executeGroovyScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) {
    try {
        final String engineName = getScriptEngineName(scriptFile);
        final ScriptEngine engine = new ScriptEngineManager().getEngineByName(engineName);
        if (engine == null || StringUtils.isBlank(engineName)) {
            LOGGER.warn("Script engine is not available for [{}]", engineName);
            return null;
        }
        final AbstractResource resourceFrom = ResourceUtils.getResourceFrom(scriptFile);
        final File theScriptFile = resourceFrom.getFile();
        if (theScriptFile.exists()) {
            LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());
            engine.eval(Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8));
            final Invocable invocable = (Invocable) engine;
            LOGGER.debug("Executing script's run method, with parameters [{}]", args);
            final Object result = invocable.invokeFunction("run", args);
            LOGGER.debug("Groovy script result is [{}]", result);
            if (result != null && !clazz.isAssignableFrom(result.getClass())) {
                throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
            }
            return (T) result;
        }
        LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : Invocable(javax.script.Invocable) ScriptEngineManager(javax.script.ScriptEngineManager) GroovyObject(groovy.lang.GroovyObject) AbstractResource(org.springframework.core.io.AbstractResource) File(java.io.File) ScriptEngine(javax.script.ScriptEngine)

Example 100 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project vcell by virtualcell.

the class ScriptingPanel method run.

private void run() {
    // create scripting engine
    ScriptEngineManager manager = new ScriptEngineManager();
    // ScriptEngine engine = manager.getEngineByName("JavaScript");
    ScriptEngine engine = manager.getEngineByName("jython");
    // create environment for the script to run in.
    // 1) capture stdout and send to the resultsTextField
    // 2) predefine variables for windowManager, bioModel, model, and current selections
    // 
    ScriptContext scriptContext = new SimpleScriptContext();
    scriptContext.setBindings(new SimpleBindings(), ScriptContext.GLOBAL_SCOPE);
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    scriptContext.setWriter(printWriter);
    Bindings globals = scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
    // }
    if (getBioModel() != null) {
        globals.put("biomodel", getBioModel());
        globals.put("model", getBioModel().getModel());
    }
    engine.setContext(scriptContext);
    // 
    try {
        String fullScript = getPredefinedJythonFunctions();
        fullScript += scriptTextArea.getText();
        System.out.println(fullScript);
        engine.eval(fullScript);
        try {
            Bindings engineBindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
            printWriter.println("\n\n\nengine variable bindings: ");
            for (Map.Entry<String, Object> entry : engineBindings.entrySet()) {
                if (entry.getKey().equals("__builtins__")) {
                    continue;
                }
                printWriter.println("  " + entry.getKey() + " : " + entry.getValue());
            }
            Bindings globalBindings = scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
            printWriter.println("\nglobal variable bindings: ");
            for (Map.Entry<String, Object> entry : globalBindings.entrySet()) {
                printWriter.println("  " + entry.getKey() + " : " + entry.getValue());
            }
            printWriter.flush();
            resultsTextArea.append(stringWriter.getBuffer().toString());
            // scroll to bottom.
            resultsTextArea.scrollRectToVisible(new Rectangle(0, resultsTextArea.getHeight() - 2, 1, 1));
        } catch (RuntimeException e1) {
            e1.printStackTrace();
        }
    } catch (ScriptException e1) {
        e1.printStackTrace();
    }
}
Also used : SimpleScriptContext(javax.script.SimpleScriptContext) ScriptEngineManager(javax.script.ScriptEngineManager) Rectangle(java.awt.Rectangle) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) StringWriter(java.io.StringWriter) SimpleBindings(javax.script.SimpleBindings) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Aggregations

ScriptEngineManager (javax.script.ScriptEngineManager)109 ScriptEngine (javax.script.ScriptEngine)66 Test (org.junit.Test)23 ScriptException (javax.script.ScriptException)20 ScriptEngineFactory (javax.script.ScriptEngineFactory)14 File (java.io.File)12 Invocable (javax.script.Invocable)11 QuickTest (com.hazelcast.test.annotation.QuickTest)10 IOException (java.io.IOException)10 FileReader (java.io.FileReader)9 Bindings (javax.script.Bindings)9 Before (org.junit.Before)9 Map (java.util.Map)8 GroovyScriptEngineFactory (org.codehaus.groovy.jsr223.GroovyScriptEngineFactory)8 Reader (java.io.Reader)7 HashMap (java.util.HashMap)6 SimpleBindings (javax.script.SimpleBindings)6 PrintWriter (java.io.PrintWriter)4 StringWriter (java.io.StringWriter)4 InputStreamReader (java.io.InputStreamReader)3