Search in sources :

Example 41 with ScriptEngineManager

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

the class OSGiScriptEngineManager method getEngineByExtension.

public ScriptEngine getEngineByExtension(String extension) {
    // TODO this is a hack to deal with context class loader issues
    ScriptEngine engine = null;
    for (ScriptEngineManager manager : classLoaders.keySet()) {
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(classLoaders.get(manager));
        engine = manager.getEngineByExtension(extension);
        Thread.currentThread().setContextClassLoader(old);
        if (engine != null)
            break;
    }
    return engine;
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 42 with ScriptEngineManager

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

the class OSGiScriptEngineManager method getEngineByName.

public ScriptEngine getEngineByName(String shortName) {
    // TODO this is a hack to deal with context class loader issues
    for (ScriptEngineManager manager : classLoaders.keySet()) {
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(classLoaders.get(manager));
        ScriptEngine engine = manager.getEngineByName(shortName);
        Thread.currentThread().setContextClassLoader(old);
        if (engine != null) {
            return new OSGiScriptEngine(engine, new OSGiScriptEngineFactory(engine.getFactory(), classLoaders.get(manager)));
        }
    }
    return null;
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 43 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project MantaroBot by Mantaro.

the class OwnerCmd method eval.

@Subscribe
public void eval(CommandRegistry cr) {
    // has no state
    JavaEvaluator javaEvaluator = new JavaEvaluator();
    Map<String, Evaluator> evals = new HashMap<>();
    evals.put("js", (event, code) -> {
        ScriptEngine script = new ScriptEngineManager().getEngineByName("nashorn");
        script.put("mantaro", MantaroBot.getInstance());
        script.put("db", MantaroData.db());
        script.put("jda", event.getJDA());
        script.put("event", event);
        script.put("guild", event.getGuild());
        script.put("channel", event.getChannel());
        try {
            return script.eval(String.join("\n", "load(\"nashorn:mozilla_compat.js\");", "imports = new JavaImporter(java.util, java.io, java.net);", "(function() {", "with(imports) {", code, "}", "})()"));
        } catch (Exception e) {
            return e;
        }
    });
    evals.put("bsh", (event, code) -> {
        Interpreter interpreter = new Interpreter();
        try {
            interpreter.set("mantaro", MantaroBot.getInstance());
            interpreter.set("db", MantaroData.db());
            interpreter.set("jda", event.getJDA());
            interpreter.set("event", event);
            interpreter.set("guild", event.getGuild());
            interpreter.set("channel", event.getChannel());
            return interpreter.eval(String.join("\n", "import *;", code));
        } catch (Exception e) {
            return e;
        }
    });
    evals.put("java", (event, code) -> {
        try {
            CompilationResult r = javaEvaluator.compile().addCompilerOptions("-Xlint:unchecked").source("Eval", JAVA_EVAL_IMPORTS + "\n\n" + "public class Eval {\n" + "   public static Object run(GuildMessageReceivedEvent event) {\n" + "       try {\n" + "           return null;\n" + "       } finally {\n" + "           " + (code + ";").replaceAll(";{2,}", ";") + "\n" + "       }\n" + "   }\n" + "}").execute();
            EvalClassLoader ecl = new EvalClassLoader();
            r.getClasses().forEach((name, bytes) -> ecl.define(bytes));
            return ecl.loadClass("Eval").getMethod("run", GuildMessageReceivedEvent.class).invoke(null, event);
        } catch (CompilationException e) {
            StringBuilder sb = new StringBuilder("\n");
            if (e.getCompilerOutput() != null)
                sb.append(e.getCompilerOutput());
            if (!e.getDiagnostics().isEmpty()) {
                if (sb.length() > 0)
                    sb.append("\n\n");
                e.getDiagnostics().forEach(d -> sb.append(d).append('\n'));
            }
            return new Error(sb.toString()) {

                @Override
                public String toString() {
                    return getMessage();
                }
            };
        } catch (Exception e) {
            return e;
        }
    });
    cr.register("eval", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Evaluator evaluator = evals.get(args[0]);
            if (evaluator == null) {
                onHelp(event);
                return;
            }
            String[] values = SPLIT_PATTERN.split(content, 2);
            if (values.length < 2) {
                onHelp(event);
                return;
            }
            String v = values[1];
            Object result = evaluator.eval(event, v);
            boolean errored = result instanceof Throwable;
            event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Evaluated " + (errored ? "and errored" : "with success"), null, event.getAuthor().getAvatarUrl()).setColor(errored ? Color.RED : Color.GREEN).setDescription(result == null ? "Executed successfully with no objects returned" : ("Executed " + (errored ? "and errored: " : "successfully and returned: ") + result.toString())).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Eval cmd").setDescription("**Evaluates stuff (A: js/bsh)**").build();
        }
    });
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) CompilationException(com.github.natanbc.javaeval.CompilationException) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Player(net.kodehawa.mantarobot.db.entities.Player) Interpreter(bsh.Interpreter) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) CompilationResult(com.github.natanbc.javaeval.CompilationResult) ScriptEngineManager(javax.script.ScriptEngineManager) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) User(net.dv8tion.jda.core.entities.User) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) MantaroObj(net.kodehawa.mantarobot.db.entities.MantaroObj) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) ScriptEngine(javax.script.ScriptEngine) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) CompilationException(com.github.natanbc.javaeval.CompilationException) Interpreter(bsh.Interpreter) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ScriptEngineManager(javax.script.ScriptEngineManager) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) ScriptEngine(javax.script.ScriptEngine) CompilationException(com.github.natanbc.javaeval.CompilationException) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) CompilationResult(com.github.natanbc.javaeval.CompilationResult) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 44 with ScriptEngineManager

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

the class MeecrowaveRunMojo method scriptCustomization.

private void scriptCustomization(final List<String> customizers, final String ext, final Map<String, Object> customBindings) {
    if (customizers == null || customizers.isEmpty()) {
        return;
    }
    final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(ext);
    if (engine == null) {
        throw new IllegalStateException("No engine for " + ext + ". Maybe add the JSR223 implementation as plugin dependency.");
    }
    for (final String js : customizers) {
        try {
            final SimpleBindings bindings = new SimpleBindings();
            bindings.put("project", project);
            engine.eval(new StringReader(js), bindings);
            bindings.putAll(customBindings);
        } catch (final ScriptException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
Also used : ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) ScriptEngineManager(javax.script.ScriptEngineManager) StringReader(java.io.StringReader) ScriptEngine(javax.script.ScriptEngine)

Example 45 with ScriptEngineManager

use of javax.script.ScriptEngineManager in project metrics by dropwizard.

the class PickledGraphiteTest method setUp.

@Before
public void setUp() throws Exception {
    final AtomicBoolean connected = new AtomicBoolean(true);
    final AtomicBoolean closed = new AtomicBoolean(false);
    when(socket.isConnected()).thenAnswer(invocation -> connected.get());
    when(socket.isClosed()).thenAnswer(invocation -> closed.get());
    doAnswer(invocation -> {
        connected.set(false);
        closed.set(true);
        return null;
    }).when(socket).close();
    when(socket.getOutputStream()).thenReturn(output);
    // Mock behavior of socket.getOutputStream().close() calling socket.close();
    doAnswer(invocation -> {
        invocation.callRealMethod();
        socket.close();
        return null;
    }).when(output).close();
    when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket);
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
    Compilable compilable = (Compilable) engine;
    try (InputStream is = PickledGraphiteTest.class.getResource("/upickle.py").openStream()) {
        unpickleScript = compilable.compile(new InputStreamReader(is, UTF_8));
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Compilable(javax.script.Compilable) ScriptEngineManager(javax.script.ScriptEngineManager) InetAddress(java.net.InetAddress) ScriptEngine(javax.script.ScriptEngine) Before(org.junit.Before)

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