Search in sources :

Example 86 with ScriptEngine

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

the class ScriptingUtils method executeGroovyScriptEngine.

/**
 * Execute inline groovy script engine.
 *
 * @param <T>       the type parameter
 * @param script    the script
 * @param variables the variables
 * @param clazz     the clazz
 * @return the t
 */
public static <T> T executeGroovyScriptEngine(final String script, final Map<String, Object> variables, final Class<T> clazz) {
    try {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
        if (engine == null) {
            LOGGER.warn("Script engine is not available for Groovy");
            return null;
        }
        final Bindings binding = new SimpleBindings();
        if (variables != null && !variables.isEmpty()) {
            binding.putAll(variables);
        }
        if (!binding.containsKey("logger")) {
            binding.put("logger", LOGGER);
        }
        final Object result = engine.eval(script, binding);
        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;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : SimpleBindings(javax.script.SimpleBindings) ScriptEngineManager(javax.script.ScriptEngineManager) GroovyObject(groovy.lang.GroovyObject) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine)

Example 87 with ScriptEngine

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

the class ComsolServiceScripting method solve.

@Override
public void solve(VCCModel vccModel, File reportFile, File javaFile, File mphFile) {
    ClassLoader origClassLoader = null;
    File comsolRootDir = VCellConfiguration.getFileProperty(PropertyLoader.comsolRootDir);
    File comsolJarDir = VCellConfiguration.getFileProperty(PropertyLoader.comsolJarDir);
    if (comsolRootDir == null || !comsolRootDir.exists()) {
        throw new RuntimeException("path to COMSOL root directory \"" + comsolRootDir + "\" not found, update preferences (or " + PropertyLoader.comsolRootDir + " in vcell.config)");
    }
    if (comsolJarDir == null || !comsolJarDir.exists()) {
        throw new RuntimeException("path to COMSOL plugin directory \"" + comsolJarDir + "\" not found, update preferences (or " + PropertyLoader.comsolJarDir + " in vcell.config)");
    }
    try {
        origClassLoader = Thread.currentThread().getContextClassLoader();
        System.setProperty("cs.root", comsolRootDir.getAbsolutePath());
        if (comsolClassloader == null) {
            ArrayList<URL> urls = new ArrayList<URL>();
            for (File f : comsolJarDir.listFiles()) {
                if (f.isFile() && f.getName().endsWith(".jar")) {
                    try {
                        urls.add(f.toURI().toURL());
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        throw new RuntimeException("failed to get URL for comsol dependency " + f.getAbsolutePath());
                    }
                }
            }
            comsolClassloader = new URLClassLoader(urls.toArray(new URL[0]), ClassLoader.getSystemClassLoader().getParent());
        }
        Thread.currentThread().setContextClassLoader(comsolClassloader);
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");
        File jsFile = new File(javaFile.getParentFile(), javaFile.getName().replace(".java", ".js"));
        run(engine, vccModel, reportFile, javaFile, mphFile, jsFile);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    } finally {
        Thread.currentThread().setContextClassLoader(origClassLoader);
        System.out.println("disconnecting");
        disconnectComsol();
        System.out.println("disconnected");
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) ScriptEngineManager(javax.script.ScriptEngineManager) URLClassLoader(java.net.URLClassLoader) File(java.io.File) URL(java.net.URL) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 88 with ScriptEngine

use of javax.script.ScriptEngine in project scheduling by ow2-proactive.

the class JavaClassScriptEngineFactoryTest method replication_index.

@Test
public void replication_index() throws Exception {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("java");
    StringWriter output = new StringWriter();
    StringWriter error = new StringWriter();
    engine.getContext().setWriter(output);
    engine.getContext().setErrorWriter(new PrintWriter(error));
    VariablesMap variables = new VariablesMap();
    variables.getInheritedMap().put(SchedulerVars.PA_TASK_REPLICATION.toString(), 42);
    engine.getContext().setAttribute("variables", variables, ScriptContext.ENGINE_SCOPE);
    Object result = engine.eval(ReturnReplicationIndex.class.getName());
    assertEquals(42, result);
}
Also used : StringWriter(java.io.StringWriter) ScriptEngineManager(javax.script.ScriptEngineManager) VariablesMap(org.ow2.proactive.scheduler.task.utils.VariablesMap) ScriptEngine(javax.script.ScriptEngine) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 89 with ScriptEngine

use of javax.script.ScriptEngine in project scheduling by ow2-proactive.

the class JavaClassScriptEngineFactoryTest method executable_with_localspace.

@Test
public void executable_with_localspace() throws Exception {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("java");
    StringWriter output = new StringWriter();
    StringWriter error = new StringWriter();
    engine.getContext().setWriter(output);
    engine.getContext().setErrorWriter(new PrintWriter(error));
    String localSpacePath = new File(".").getAbsolutePath();
    engine.getContext().setAttribute(SchedulerConstants.DS_SCRATCH_BINDING_NAME, localSpacePath, ScriptContext.ENGINE_SCOPE);
    String result = (String) engine.eval(ReturnLocalSpace.class.getName());
    assertEquals(result, localSpacePath);
}
Also used : StringWriter(java.io.StringWriter) ScriptEngineManager(javax.script.ScriptEngineManager) File(java.io.File) ScriptEngine(javax.script.ScriptEngine) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 90 with ScriptEngine

use of javax.script.ScriptEngine in project scheduling by ow2-proactive.

the class AbstractIModeCommand method execute.

@Override
public void execute(ApplicationContext currentContext) throws CLIException {
    currentContext.setProperty(IMODE, true);
    ScriptEngine engine = currentContext.getEngine();
    try {
        // load supported functions
        engine.eval(new InputStreamReader(script()));
    } catch (ScriptException error) {
        throw new CLIException(CLIException.REASON_OTHER, error);
    }
    while (!currentContext.getProperty(TERMINATE, Boolean.TYPE, false)) {
        try {
            String command = readLine(currentContext, "> ");
            if (command == null) {
                // EOF, exit interactive shell
                break;
            }
            engine.eval(command);
        } catch (ScriptException se) {
            handleError(String.format("An error occurred while executing the script:"), se, currentContext);
        }
    }
}
Also used : ScriptException(javax.script.ScriptException) InputStreamReader(java.io.InputStreamReader) CLIException(org.ow2.proactive_grid_cloud_portal.cli.CLIException) ScriptEngine(javax.script.ScriptEngine)

Aggregations

ScriptEngine (javax.script.ScriptEngine)175 ScriptEngineManager (javax.script.ScriptEngineManager)70 ScriptException (javax.script.ScriptException)46 Test (org.junit.Test)29 Bindings (javax.script.Bindings)20 IOException (java.io.IOException)19 Map (java.util.Map)14 Invocable (javax.script.Invocable)13 File (java.io.File)11 FileReader (java.io.FileReader)11 ScriptEngineFactory (javax.script.ScriptEngineFactory)11 HashMap (java.util.HashMap)10 ScriptContext (javax.script.ScriptContext)10 SimpleBindings (javax.script.SimpleBindings)10 InputStreamReader (java.io.InputStreamReader)9 GroovyTest (org.enumerable.lambda.support.groovy.GroovyTest)9 ScalaTest (org.enumerable.lambda.support.scala.ScalaTest)9 PrintWriter (java.io.PrintWriter)7 JavaScriptTest (org.enumerable.lambda.support.javascript.JavaScriptTest)7 JRubyTest (org.enumerable.lambda.support.jruby.JRubyTest)7