Search in sources :

Example 16 with Interpreter

use of bsh.Interpreter in project spring-framework by spring-projects.

the class BshScriptUtils method evaluateBshScript.

/**
	 * Evaluate the specified BeanShell script based on the given script source,
	 * keeping a returned script Class or script Object as-is.
	 * <p>The script may either be a simple script that needs a corresponding proxy
	 * generated (implementing the specified interfaces), or declare a full class
	 * or return an actual instance of the scripted object (in which case the
	 * specified interfaces, if any, need to be implemented by that class/instance).
	 * @param scriptSource the script source text
	 * @param scriptInterfaces the interfaces that the scripted Java object is
	 * supposed to implement (may be {@code null} or empty if the script itself
	 * declares a full class or returns an actual instance of the scripted object)
	 * @param classLoader the ClassLoader to use for evaluating the script
	 * @return the scripted Java class or Java object
	 * @throws EvalError in case of BeanShell parsing failure
	 */
static Object evaluateBshScript(String scriptSource, Class<?>[] scriptInterfaces, ClassLoader classLoader) throws EvalError {
    Assert.hasText(scriptSource, "Script source must not be empty");
    Interpreter interpreter = new Interpreter();
    interpreter.setClassLoader(classLoader);
    Object result = interpreter.eval(scriptSource);
    if (result != null) {
        return result;
    } else {
        // Simple BeanShell script: Let's create a proxy for it, implementing the given interfaces.
        Assert.notEmpty(scriptInterfaces, "Given script requires a script proxy: At least one script interface is required.");
        XThis xt = (XThis) interpreter.eval("return this");
        return Proxy.newProxyInstance(classLoader, scriptInterfaces, new BshObjectInvocationHandler(xt));
    }
}
Also used : Interpreter(bsh.Interpreter) XThis(bsh.XThis)

Example 17 with Interpreter

use of bsh.Interpreter in project MantaroBot by Mantaro.

the class OwnerCmd method owner.

@Command
public static void owner(CommandRegistry cr) {
    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("cw", (event, code) -> {
        Object[] returns;
        boolean errored = false;
        try {
            returns = MantaroData.connectionWatcher().eval(code);
        } catch (RuntimeException e) {
            errored = true;
            returns = new Object[] { e.getMessage() };
        }
        String result = returns.length == 1 ? returns[0] == null ? null : String.valueOf(returns[0]) : Arrays.asList(returns).toString();
        if (errored)
            return new Error(result == null ? "Internal error" : result) {

                @Override
                public String toString() {
                    return getMessage();
                }
            };
        return result;
    });
    cr.register("owner", new SimpleCommand(Category.OWNER) {

        @Override
        public CommandPermission permission() {
            return CommandPermission.OWNER;
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Owner command").setDescription("`~>owner shutdown/forceshutdown`: Shutdowns the bot\n" + "`~>owner restart/forcerestart`: Restarts the bot.\n" + "`~>owner scheduleshutdown time <time>` - Schedules a fixed amount of seconds the bot will wait to be shutted down.\n" + "`~>owner varadd <pat/hug/greeting/splash>` - Adds a link or phrase to the specified list.\n" + "`~>owner eval <bsh/js/cw> <line of code>` - Evals a specified code snippet.\n" + "`~>owner cw <info/eval>` - Shows info or evals specified code in the Connection Watcher.\n" + "`~>owner premium add <id> <days>` - Adds premium to the specified user for x days.").addField("Shush.", "If you aren't Adrian or Kode you shouldn't be looking at this, huh 👀" + EmoteReference.EYES, false).build();
        }

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 1) {
                onHelp(event);
                return;
            }
            String option = args[0];
            if (option.equals("cw")) {
                if (args.length < 2) {
                    onHelp(event);
                    return;
                }
                String sub = args[1].split("\\s+")[0];
                if (sub.equals("info")) {
                    event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Connection Watcher info", null, null).setDescription(MantaroData.connectionWatcher().get().toString()).setColor(event.getGuild().getSelfMember().getColor()).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
                } else if (sub.equals("eval")) {
                    String[] parts = event.getMessage().getRawContent().split(" ");
                    if (parts.length < 4) {
                        onHelp(event);
                        return;
                    }
                    Object[] returns;
                    boolean errored = false;
                    try {
                        returns = MantaroData.connectionWatcher().eval(String.join(" ", Arrays.copyOfRange(parts, 3, parts.length)));
                    } catch (RuntimeException e) {
                        errored = true;
                        returns = new Object[] { e.getMessage() };
                    }
                    String result = returns.length == 1 ? returns[0] == null ? null : String.valueOf(returns[0]) : Arrays.asList(returns).toString();
                    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)).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
                } else {
                    onHelp(event);
                }
                return;
            }
            if (option.equals("premium")) {
                String sub = args[1].substring(0, args[1].indexOf(' '));
                if (sub.equals("add")) {
                    try {
                        String[] values = SPLIT_PATTERN.split(args[1], 3);
                        try {
                            Long.parseLong(values[1]);
                        } catch (Exception e) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid user id").queue();
                            return;
                        }
                        DBUser db = MantaroData.db().getUser(values[1]);
                        db.incrementPremium(TimeUnit.DAYS.toMillis(Long.parseLong(values[2])));
                        db.saveAsync();
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "The premium feature for user " + db.getId() + " now is until " + new Date(db.getPremiumUntil())).queue();
                        return;
                    } catch (IndexOutOfBoundsException e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify id and number of days").queue();
                        e.printStackTrace();
                        return;
                    }
                }
                if (sub.equals("guild")) {
                    try {
                        String[] values = SPLIT_PATTERN.split(args[1], 3);
                        DBGuild db = MantaroData.db().getGuild(values[1]);
                        db.incrementPremium(TimeUnit.DAYS.toMillis(Long.parseLong(values[2])));
                        db.saveAsync();
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "The premium feature for guild " + db.getId() + " now is until " + new Date(db.getPremiumUntil())).queue();
                        return;
                    } catch (IndexOutOfBoundsException e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify id and number of days").queue();
                        e.printStackTrace();
                        return;
                    }
                }
            }
            if (option.equals("shutdown") || option.equals("restart")) {
                if (args.length == 2) {
                    try {
                        notifyMusic(args[1]).get();
                    } catch (InterruptedException | ExecutionException ignored) {
                    }
                }
                try {
                    prepareShutdown(event);
                } catch (Exception e) {
                    log.warn(EmoteReference.ERROR + "Couldn't prepare shutdown." + e.toString(), e);
                    return;
                }
                if (option.equals("restart")) {
                    try {
                        MantaroData.connectionWatcher().reboot(false);
                    } catch (Exception e) {
                        log.error("Error restarting via manager, manual reboot required", e);
                        System.exit(-1);
                    }
                } else {
                    System.exit(0);
                }
                return;
            }
            if (option.equals("forceshutdown") || option.equals("forcerestart")) {
                if (args.length == 2) {
                    try {
                        notifyMusic(args[1]).get();
                    } catch (InterruptedException | ExecutionException ignored) {
                    }
                }
                try {
                    prepareShutdown(event);
                } catch (Exception e) {
                    log.warn(EmoteReference.ERROR + "Couldn't prepare shutdown. I don't care, I'm gonna restart anyway." + e.toString(), e);
                }
                if (option.equals("forcerestart")) {
                    try {
                        MantaroData.connectionWatcher().reboot(false);
                    } catch (Exception e) {
                        log.error("Error restarting via manager, manual reboot required", e);
                        System.exit(-1);
                    }
                } else {
                    System.exit(0);
                }
                return;
            }
            if (args.length < 2) {
                onHelp(event);
                return;
            }
            String value = args[1];
            if (option.equals("notifymusic")) {
                notifyMusic(value);
                event.getChannel().sendMessage(EmoteReference.MEGA + "Guilds playing music were notified!").queue();
                return;
            }
            String[] values = SPLIT_PATTERN.split(value, 2);
            if (values.length < 2) {
                onHelp(event);
                return;
            }
            String k = values[0], v = values[1];
            if (option.equals("scheduleshutdown") || option.equals("schedulerestart")) {
                boolean restart = option.equals("schedulerestart");
                if (k.equals("time")) {
                    double s = Double.parseDouble(v);
                    int millis = (int) (s * 1000);
                    Async.thread(millis, TimeUnit.MILLISECONDS, () -> {
                        try {
                            prepareShutdown(event);
                        } catch (Exception e) {
                            log.warn(EmoteReference.ERROR + "Couldn't prepare shutdown. I don't care, I'm gonna restart anyway." + e.toString(), e);
                        }
                        if (restart) {
                            try {
                                MantaroData.connectionWatcher().reboot(false);
                            } catch (Exception e) {
                                log.error("Error restarting via manager, manual reboot required", e);
                                System.exit(-1);
                            }
                        } else {
                            System.exit(0);
                        }
                    });
                    event.getChannel().sendMessage(EmoteReference.STOPWATCH + " Sleeping in " + s + " seconds...").queue();
                    return;
                }
                if (k.equals("connections")) {
                    int connections = Integer.parseInt(v);
                    IntSupplier currentConnections = () -> (int) event.getJDA().getVoiceChannels().stream().filter(voiceChannel -> voiceChannel.getMembers().contains(voiceChannel.getGuild().getSelfMember())).count();
                    Async.task("Watching Thread.", s -> {
                        if (currentConnections.getAsInt() > connections)
                            return;
                        try {
                            prepareShutdown(event);
                        } catch (Exception e) {
                            log.warn("Couldn't prepare shutdown. I don't care, I'm gonna do it anyway." + e.toString(), e);
                        }
                        if (restart) {
                            try {
                                MantaroData.connectionWatcher().reboot(false);
                            } catch (Exception e) {
                                log.error("Error restarting via manager, manual reboot required", e);
                                System.exit(-1);
                            }
                        } else {
                            System.exit(0);
                        }
                        s.shutdown();
                    }, 2, TimeUnit.SECONDS);
                    return;
                }
                onHelp(event);
                return;
            }
            if (option.equals("varadd")) {
                try {
                    String v1 = values[1];
                    switch(values[0]) {
                        case "pat":
                            ActionCmds.PATS.get().add(v1);
                            ActionCmds.PATS.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to pat list: " + v).queue();
                            break;
                        case "hug":
                            ActionCmds.HUGS.get().add(v1);
                            ActionCmds.HUGS.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to hug list: " + v).queue();
                            break;
                        case "greeting":
                            ActionCmds.GREETINGS.get().add(content.replace("varadd greeting ", ""));
                            ActionCmds.GREETINGS.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to greet list: " + content.replace("greeting ", "")).queue();
                            break;
                        case "splash":
                            MantaroShard.SPLASHES.get().add(content.replace("varadd splash ", ""));
                            MantaroShard.SPLASHES.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to splash list: " + content.replace("splash ", "")).queue();
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            if (option.equals("eval")) {
                Evaluator evaluator = evals.get(k);
                if (evaluator == null) {
                    onHelp(event);
                    return;
                }
                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();
                return;
            }
            if (option.equals("query")) {
                try {
                    String[] values1 = SPLIT_PATTERN.split(content);
                    String expression = content.replace(values1[0] + " ", "");
                    SQLDatabase.getInstance().run((conn) -> {
                        try {
                            ResultSet set;
                            try {
                                set = conn.prepareStatement(expression).executeQuery();
                            } catch (SQLException e) {
                                try {
                                    conn.prepareStatement(expression).execute();
                                    event.getChannel().sendMessage(" Query was successfully executed!").queue();
                                } catch (SQLException e1) {
                                    event.getChannel().sendMessage("Failed to execute query! " + Utils.paste(getStackTrace(e1))).queue();
                                }
                                return;
                            }
                            List<String> header = new ArrayList<>();
                            List<List<String>> table = new ArrayList<>();
                            ResultSetMetaData metaData = set.getMetaData();
                            int columnsCount = metaData.getColumnCount();
                            for (int i = 0; i < columnsCount; i++) {
                                header.add(metaData.getColumnName(i + 1));
                            }
                            while (set.next()) {
                                List<String> row = new ArrayList<>();
                                for (int i = 0; i < columnsCount; i++) {
                                    String s = String.valueOf(set.getString(i + 1)).trim();
                                    row.add(s.substring(0, Math.min(30, s.length())));
                                }
                                table.add(row);
                            }
                            String output = makeAsciiTable(header, table, null);
                            event.getChannel().sendMessage(Utils.paste(output)).queue();
                        } catch (SQLException e) {
                            event.getChannel().sendMessage(" Failed to build ascii table! " + Utils.paste(getStackTrace(e))).queue();
                        }
                    }).queue();
                } catch (SQLException e) {
                    event.getChannel().sendMessage(" Failed to run query! " + Utils.paste(getStackTrace(e))).queue();
                }
                return;
            }
            onHelp(event);
        }

        @Override
        public String[] splitArgs(String content) {
            return SPLIT_PATTERN.split(content, 2);
        }
    });
}
Also used : SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Color(java.awt.Color) java.util(java.util) Async(br.com.brjdevs.java.utils.async.Async) Utils(net.kodehawa.mantarobot.utils.Utils) Module(net.kodehawa.mantarobot.modules.Module) CompletableFuture(java.util.concurrent.CompletableFuture) MantaroShard(net.kodehawa.mantarobot.MantaroShard) Message(net.dv8tion.jda.core.entities.Message) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SQLException(java.sql.SQLException) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) ResultSet(java.sql.ResultSet) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) SQLDatabase(net.kodehawa.mantarobot.utils.sql.SQLDatabase) Command(net.kodehawa.mantarobot.modules.Command) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) IntSupplier(java.util.function.IntSupplier) PrintWriter(java.io.PrintWriter) Interpreter(bsh.Interpreter) DBUser(net.kodehawa.mantarobot.data.entities.DBUser) StringWriter(java.io.StringWriter) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) ScriptEngineManager(javax.script.ScriptEngineManager) Category(net.kodehawa.mantarobot.modules.commands.base.Category) MantaroObj(net.kodehawa.mantarobot.data.entities.MantaroObj) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) ScriptEngine(javax.script.ScriptEngine) MantaroData(net.kodehawa.mantarobot.data.MantaroData) ResultSetMetaData(java.sql.ResultSetMetaData) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) IntSupplier(java.util.function.IntSupplier) SQLException(java.sql.SQLException) ScriptEngineManager(javax.script.ScriptEngineManager) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Interpreter(bsh.Interpreter) ScriptEngine(javax.script.ScriptEngine) SQLException(java.sql.SQLException) ExecutionException(java.util.concurrent.ExecutionException) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) DBUser(net.kodehawa.mantarobot.data.entities.DBUser) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 18 with Interpreter

use of bsh.Interpreter in project symmetric-ds by JumpMind.

the class BshDatabaseWriterFilter method getInterpreter.

protected Interpreter getInterpreter(Context context) {
    Interpreter interpreter = (Interpreter) context.get(INTERPRETER_KEY);
    if (interpreter == null) {
        interpreter = new Interpreter();
        context.put(INTERPRETER_KEY, interpreter);
    }
    return interpreter;
}
Also used : Interpreter(bsh.Interpreter)

Example 19 with Interpreter

use of bsh.Interpreter in project symmetric-ds by JumpMind.

the class BshDatabaseWriterFilter method executeScripts.

@Override
protected void executeScripts(DataContext context, String key, Set<String> scripts, boolean isFailOnError) {
    Interpreter interpreter = getInterpreter(context);
    String currentScript = null;
    try {
        bind(interpreter, context, null, null, null);
        if (scripts != null) {
            for (String script : scripts) {
                currentScript = script;
                interpreter.eval(script);
            }
        }
    } catch (EvalError e) {
        if (e instanceof ParseException) {
            String errorMsg = String.format("Evaluation error while parsing the following beanshell script:\n\n%s\n\nThe error was on line %d and the error message was: %s", currentScript, e.getErrorLineNumber(), e.getMessage());
            log.error(errorMsg, e);
            if (isFailOnError) {
                throw new SymmetricException(errorMsg);
            }
        } else if (e instanceof TargetError) {
            Throwable target = ((TargetError) e).getTarget();
            String errorMsg = String.format("Evaluation error occured in the following beanshell script:\n\n%s\n\nThe error was on line %d", currentScript, e.getErrorLineNumber());
            log.error(errorMsg, target);
            if (isFailOnError) {
                if (target instanceof RuntimeException) {
                    throw (RuntimeException) target;
                } else {
                    throw new SymmetricException(target);
                }
            } else {
                log.error("Failed while evaluating script", target);
            }
        }
    }
}
Also used : Interpreter(bsh.Interpreter) SymmetricException(org.jumpmind.symmetric.SymmetricException) EvalError(bsh.EvalError) ParseException(bsh.ParseException) TargetError(bsh.TargetError)

Example 20 with Interpreter

use of bsh.Interpreter in project symmetric-ds by JumpMind.

the class BshDatabaseWriterFilter method processLoadFilters.

@Override
protected boolean processLoadFilters(DataContext context, Table table, CsvData data, Exception error, WriteMethod writeMethod, List<LoadFilter> loadFiltersForTable) {
    boolean writeRow = true;
    LoadFilter currentFilter = null;
    try {
        Interpreter interpreter = getInterpreter(context);
        bind(interpreter, context, table, data, error);
        for (LoadFilter filter : loadFiltersForTable) {
            currentFilter = filter;
            if (filter.isFilterOnDelete() && data.getDataEventType().equals(DataEventType.DELETE) || filter.isFilterOnInsert() && data.getDataEventType().equals(DataEventType.INSERT) || filter.isFilterOnUpdate() && data.getDataEventType().equals(DataEventType.UPDATE)) {
                Object result = null;
                if (writeMethod.equals(WriteMethod.BEFORE_WRITE) && filter.getBeforeWriteScript() != null) {
                    result = interpreter.eval(filter.getBeforeWriteScript());
                } else if (writeMethod.equals(WriteMethod.AFTER_WRITE) && filter.getAfterWriteScript() != null) {
                    result = interpreter.eval(filter.getAfterWriteScript());
                } else if (writeMethod.equals(WriteMethod.HANDLE_ERROR) && filter.getHandleErrorScript() != null) {
                    result = interpreter.eval(filter.getHandleErrorScript());
                }
                if (result != null && result.equals(Boolean.FALSE)) {
                    writeRow = false;
                }
            }
        }
    } catch (EvalError ex) {
        processError(currentFilter, table, ex);
    }
    return writeRow;
}
Also used : Interpreter(bsh.Interpreter) LoadFilter(org.jumpmind.symmetric.model.LoadFilter) EvalError(bsh.EvalError)

Aggregations

Interpreter (bsh.Interpreter)24 EvalError (bsh.EvalError)9 TargetError (bsh.TargetError)5 Map (java.util.Map)3 Bundle (android.os.Bundle)2 ParseException (bsh.ParseException)2 Async (br.com.brjdevs.java.utils.async.Async)1 CollectionUtils.random (br.com.brjdevs.java.utils.collections.CollectionUtils.random)1 NameSpace (bsh.NameSpace)1 XThis (bsh.XThis)1 Color (java.awt.Color)1 File (java.io.File)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 ResultSet (java.sql.ResultSet)1 ResultSetMetaData (java.sql.ResultSetMetaData)1 SQLException (java.sql.SQLException)1 java.util (java.util)1