Search in sources :

Example 71 with ScriptEngine

use of javax.script.ScriptEngine in project JMRI by JMRI.

the class FileLineEndingsTest method lineEndings.

@Test
public void lineEndings() {
    try {
        String path = this.file.getCanonicalPath();
        // is also the escape character
        if (File.separator.equals("\\")) {
            path = path.replace("\\", "/");
        }
        String script = String.join("\n", "import os", "failing = False", "if \"\\r\\n\" in open(os.path.normpath(\"" + path + "\"),\"rb\").read():", "    failing = True");
        try {
            ScriptEngine engine = JmriScriptEngineManager.getDefault().getEngine(JmriScriptEngineManager.PYTHON);
            engine.eval(script);
            Assert.assertFalse("File " + file.getPath() + " has incorrect line endings.", Boolean.valueOf(engine.get("failing").toString()));
        } catch (ScriptException ex) {
            log.error("Unable to execute script for test", ex);
            Assert.fail("Unable to execute script for test");
        }
    } catch (IOException ex) {
        log.error("Unable to get path for {}", this.file, ex);
        Assert.fail("Unable to get get path " + file.getPath() + " for test");
    }
}
Also used : ScriptException(javax.script.ScriptException) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine) Test(org.junit.Test)

Example 72 with ScriptEngine

use of javax.script.ScriptEngine in project JMRI by JMRI.

the class Jdk9Application method setAboutHandler.

@Override
public void setAboutHandler(final AboutHandler handler) {
    if (handler != null) {
        try {
            // NOI18N
            InputStreamReader reader = new InputStreamReader(Jdk9Application.class.getResourceAsStream("AboutHandler.js"));
            // NOI18N
            ScriptEngine engine = JmriScriptEngineManager.getDefault().getEngineByMimeType("js");
            JmriScriptEngineManager.getDefault().eval(reader, engine, this.getContext(handler));
        } catch (ScriptException ex) {
            log.error("Unable to execute script AboutHandler.js", ex);
        }
    } else {
        // NOI18N
        this.setHandler("setAboutHandler", "java.awt.desktop.AboutHandler", null);
    }
}
Also used : ScriptException(javax.script.ScriptException) InputStreamReader(java.io.InputStreamReader) ScriptEngine(javax.script.ScriptEngine)

Example 73 with ScriptEngine

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

the class SlyBindingsValuesProvider method ensureFactoriesLoaded.

private void ensureFactoriesLoaded(Bindings bindings) {
    JsEnvironment jsEnvironment = null;
    ResourceResolver resolver = null;
    try {
        ScriptEngine scriptEngine = obtainEngine();
        if (scriptEngine == null) {
            return;
        }
        jsEnvironment = new JsEnvironment(scriptEngine);
        jsEnvironment.initialize();
        resolver = rrf.getServiceResourceResolver(null);
        factories = new HashMap<>(scriptPaths.size());
        for (Map.Entry<String, String> entry : scriptPaths.entrySet()) {
            factories.put(entry.getKey(), loadFactory(resolver, jsEnvironment, entry.getValue(), bindings));
        }
        qScript = loadQScript(resolver);
    } catch (LoginException e) {
        LOGGER.error("Cannot load HTL Use-API factories.", e);
    } finally {
        if (jsEnvironment != null) {
            jsEnvironment.cleanup();
        }
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : JsEnvironment(org.apache.sling.scripting.sightly.js.impl.JsEnvironment) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException) HashMap(java.util.HashMap) Map(java.util.Map) ScriptEngine(javax.script.ScriptEngine)

Example 74 with ScriptEngine

use of javax.script.ScriptEngine in project GeoGig by boundlessgeo.

the class Scripting method runJVMScript.

/**
     * Runs a script
     * 
     * @param scriptFile the script file to run
     * @param operation the operation triggering the script, to provide context for the script. This
     *        object might get modified if the script modifies it to alter how the command is called
     *        (for instance, changing the commit message in a commit operation)
     * @throws CannotRunGeogigOperationException
     */
@SuppressWarnings("unchecked")
public static void runJVMScript(AbstractGeoGigOp<?> operation, File scriptFile) throws CannotRunGeogigOperationException {
    checkArgument(scriptFile.exists(), "Script file does not exist %s", scriptFile.getPath());
    LOGGER.info("Running jvm script {}", scriptFile.getAbsolutePath());
    final String filename = scriptFile.getName();
    final String ext = Files.getFileExtension(filename);
    final ScriptEngine engine = factory.getEngineByExtension(ext);
    try {
        Map<String, Object> params = getParamMap(operation);
        engine.put(PARAMS, params);
        Repository repo = operation.command(ResolveRepository.class).call();
        GeoGigAPI api = new GeoGigAPI(repo);
        engine.put(GEOGIG, api);
        engine.eval(new FileReader(scriptFile));
        Object map = engine.get(PARAMS);
        setParamMap((Map<String, Object>) map, operation);
    } catch (ScriptException e) {
        Throwable cause = Throwables.getRootCause(e);
        // TODO: improve this hack to check exception type
        if (cause != e) {
            String msg = cause.getMessage();
            msg = msg.substring(CannotRunGeogigOperationException.class.getName().length() + 2, msg.lastIndexOf("(")).trim();
            msg += " (command aborted by .geogig/hooks/" + scriptFile.getName() + ")";
            throw new CannotRunGeogigOperationException(msg);
        } else {
            throw new CannotRunGeogigOperationException(String.format("Script %s threw an exception: '%s'", scriptFile, e.getMessage()), e);
        }
    } catch (Exception e) {
    }
}
Also used : ScriptException(javax.script.ScriptException) Repository(org.locationtech.geogig.repository.Repository) ResolveRepository(org.locationtech.geogig.api.plumbing.ResolveRepository) FileReader(java.io.FileReader) ResolveRepository(org.locationtech.geogig.api.plumbing.ResolveRepository) ScriptEngine(javax.script.ScriptEngine) IOException(java.io.IOException) ScriptException(javax.script.ScriptException)

Example 75 with ScriptEngine

use of javax.script.ScriptEngine in project opennms by OpenNMS.

the class Scripting method loadScripts.

private List<StatusScript<S>> loadScripts() {
    final List<StatusScript<S>> scripts = Lists.newArrayList();
    try (final DirectoryStream<Path> stream = Files.newDirectoryStream(this.scriptPath)) {
        for (final Path path : stream) {
            final String extension = FilenameUtils.getExtension(path.toString());
            final ScriptEngine scriptEngine = this.scriptEngineManager.getEngineByExtension(extension);
            if (scriptEngine == null) {
                LOG.warn("No script engine found for extension '{}'", extension);
                continue;
            }
            LOG.debug("Found script: path={}, extension={}, engine={}", path, extension, scriptEngine);
            try (final Stream<String> lines = Files.lines(path, Charset.defaultCharset())) {
                final String source = lines.collect(Collectors.joining("\n"));
                scripts.add(new StatusScript(scriptEngine, source));
            }
        }
    } catch (final IOException e) {
        LOG.error("Failed to walk template directory: " + this.scriptPath, e);
        return Collections.emptyList();
    }
    return scripts;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) 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