Search in sources :

Example 1 with CommandHelperEnvironment

use of com.laytonsmith.core.environments.CommandHelperEnvironment in project CommandHelper by EngineHub.

the class CommandHelperInterpreterListener method execute.

public void execute(String script, final MCPlayer p) throws ConfigCompileException, ConfigCompileGroupException {
    TokenStream stream = MethodScriptCompiler.lex(script, new File("Interpreter"), true);
    ParseTree tree = MethodScriptCompiler.compile(stream);
    interpreterMode.remove(p.getName());
    GlobalEnv gEnv = new GlobalEnv(plugin.executionQueue, plugin.profiler, plugin.persistenceNetwork, CommandHelperFileLocations.getDefault().getConfigDirectory(), plugin.profiles, new TaskManager());
    gEnv.SetDynamicScriptingMode(true);
    CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
    cEnv.SetPlayer(p);
    Environment env = Environment.createEnvironment(gEnv, cEnv);
    try {
        MethodScriptCompiler.registerAutoIncludes(env, null);
        MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {

            @Override
            public void done(String output) {
                output = output.trim();
                if (output.isEmpty()) {
                    Static.SendMessage(p, ":");
                } else {
                    if (output.startsWith("/")) {
                        // Run the command
                        Static.SendMessage(p, ":" + MCChatColor.YELLOW + output);
                        p.chat(output);
                    } else {
                        // output the results
                        Static.SendMessage(p, ":" + MCChatColor.GREEN + output);
                    }
                }
                interpreterMode.add(p.getName());
            }
        }, null);
    } catch (CancelCommandException e) {
        interpreterMode.add(p.getName());
    } catch (ConfigRuntimeException e) {
        ConfigRuntimeException.HandleUncaughtException(e, env);
        Static.SendMessage(p, MCChatColor.RED + e.toString());
        interpreterMode.add(p.getName());
    } catch (Exception e) {
        Static.SendMessage(p, MCChatColor.RED + e.toString());
        Logger.getLogger(CommandHelperInterpreterListener.class.getName()).log(Level.SEVERE, null, e);
        interpreterMode.add(p.getName());
    }
}
Also used : TokenStream(com.laytonsmith.core.compiler.TokenStream) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) MethodScriptComplete(com.laytonsmith.core.MethodScriptComplete) TaskManager(com.laytonsmith.core.taskmanager.TaskManager) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Environment(com.laytonsmith.core.environments.Environment) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) File(java.io.File) ParseTree(com.laytonsmith.core.ParseTree)

Example 2 with CommandHelperEnvironment

use of com.laytonsmith.core.environments.CommandHelperEnvironment in project CommandHelper by EngineHub.

the class AliasCore method alias.

/**
 * This is the workhorse function. It takes a given command, then converts it into the actual command(s). If the
 * command maps to a defined alias, it will run the specified alias. It will search through the global list of
 * aliases, as well as the aliases defined for that specific player. This function doesn't handle the /alias command
 * however.
 *
 * @param command
 * @return
 */
public boolean alias(String command, final MCCommandSender player) {
    if (scripts == null) {
        throw ConfigRuntimeException.CreateUncatchableException("Cannot run alias commands, no config file is loaded", Target.UNKNOWN);
    }
    boolean match = false;
    try {
        // actually add the player to the array.
        if (player != null && player instanceof MCPlayer && echoCommand.contains(((MCPlayer) player).getName())) {
            // we are running one of the expanded commands, so exit with false
            return false;
        }
        for (Script s : scripts) {
            try {
                if (s.match(command)) {
                    this.addPlayerReference(player);
                    if (Prefs.ConsoleLogCommands() && s.doLog()) {
                        StringBuilder b = new StringBuilder("CH: Running original command ");
                        if (player instanceof MCPlayer) {
                            b.append("on player ").append(((MCPlayer) player).getName());
                        } else {
                            b.append("from a MCCommandSender");
                        }
                        b.append(" ----> ").append(command);
                        Static.getLogger().log(Level.INFO, b.toString());
                    }
                    GlobalEnv gEnv = new GlobalEnv(parent.executionQueue, parent.profiler, parent.persistenceNetwork, MethodScriptFileLocations.getDefault().getConfigDirectory(), parent.profiles, new TaskManager());
                    CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
                    cEnv.SetCommandSender(player);
                    Environment env = Environment.createEnvironment(gEnv, cEnv);
                    try {
                        env.getEnv(CommandHelperEnvironment.class).SetCommand(command);
                        ProfilePoint alias = env.getEnv(GlobalEnv.class).GetProfiler().start("Global Alias - \"" + command + "\"", LogLevel.ERROR);
                        try {
                            s.run(s.getVariables(command), env, new MethodScriptComplete() {

                                @Override
                                public void done(String output) {
                                    try {
                                        if (output != null) {
                                            if (!output.trim().isEmpty() && output.trim().startsWith("/")) {
                                                if (Prefs.DebugMode()) {
                                                    if (player instanceof MCPlayer) {
                                                        Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((MCPlayer) player).getName() + ": " + output.trim());
                                                    } else {
                                                        Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + output.trim());
                                                    }
                                                }
                                                if (player instanceof MCPlayer) {
                                                    ((MCPlayer) player).chat(output.trim());
                                                } else {
                                                    Static.getServer().dispatchCommand(player, output.trim().substring(1));
                                                }
                                            }
                                        }
                                    } catch (Throwable e) {
                                        StreamUtils.GetSystemErr().println(e.getMessage());
                                        player.sendMessage(MCChatColor.RED + e.getMessage());
                                    } finally {
                                        Static.getAliasCore().removePlayerReference(player);
                                    }
                                }
                            });
                        } finally {
                            alias.stop();
                        }
                    } catch (ConfigRuntimeException ex) {
                        ex.setEnv(env);
                        ConfigRuntimeException.HandleUncaughtException(ex, env);
                    } catch (Throwable e) {
                        // This is not a simple user script error, this is a deeper problem, so we always handle this.
                        StreamUtils.GetSystemErr().println("An unexpected exception occured: " + e.getClass().getSimpleName());
                        player.sendMessage("An unexpected exception occured: " + MCChatColor.RED + e.getClass().getSimpleName());
                        e.printStackTrace();
                    } finally {
                        Static.getAliasCore().removePlayerReference(player);
                    }
                    match = true;
                    break;
                }
            } catch (Exception e) {
                StreamUtils.GetSystemErr().println("An unexpected exception occured inside the command " + s.toString());
                e.printStackTrace();
            }
        }
    } catch (Throwable e) {
        // Not only did an error happen, an error happened in our error handler
        throw new InternalException(TermColors.RED + "An unexpected error occured in the CommandHelper plugin. " + "Further, this is likely an error with the error handler, so it may be caused by your script, " + "however, there is no more information at this point. Check your script, but also report this " + "as a bug in CommandHelper. Also, it's possible that some commands will no longer work. As a temporary " + "workaround, restart the server, and avoid doing whatever it is you did to make this happen.\nThe error is as follows: " + e.toString() + "\n" + TermColors.reset() + "Stack Trace:\n" + StringUtils.Join(Arrays.asList(e.getStackTrace()), "\n"));
    }
    return match;
}
Also used : MCPlayer(com.laytonsmith.abstraction.MCPlayer) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) TaskManager(com.laytonsmith.core.taskmanager.TaskManager) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Environment(com.laytonsmith.core.environments.Environment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv)

Example 3 with CommandHelperEnvironment

use of com.laytonsmith.core.environments.CommandHelperEnvironment in project CommandHelper by EngineHub.

the class Manager method start.

@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void start() throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
    Implementation.useAbstractEnumThread(false);
    Implementation.forceServerType(Implementation.Type.BUKKIT);
    ConnectionMixinFactory.ConnectionMixinOptions options = new ConnectionMixinFactory.ConnectionMixinOptions();
    options.setWorkingDirectory(chDirectory);
    persistenceNetwork = new PersistenceNetwork(CommandHelperFileLocations.getDefault().getPersistenceConfig(), CommandHelperFileLocations.getDefault().getDefaultPersistenceDBFile().toURI(), options);
    Installer.Install(chDirectory);
    CHLog.initialize(chDirectory);
    profiler = new Profiler(CommandHelperFileLocations.getDefault().getProfilerConfigFile());
    gEnv = new GlobalEnv(new MethodScriptExecutionQueue("Manager", "default"), profiler, persistenceNetwork, chDirectory, new Profiles(MethodScriptFileLocations.getDefault().getProfilesFile()), new TaskManager());
    cls();
    pl("\n" + Static.Logo() + "\n\n" + Static.DataManagerLogo());
    pl("Starting the Data Manager...");
    try {
        Environment env = Environment.createEnvironment(gEnv, new CommandHelperEnvironment());
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex("player()", null, true)), env, null, null);
    } catch (ConfigCompileException | ConfigCompileGroupException ex) {
    }
    pl(GREEN + "Welcome to the CommandHelper " + CYAN + "Data Manager!");
    pl(BLINKON + RED + "Warning!" + BLINKOFF + YELLOW + " Be sure your server is not running before using this tool to make changes to your database!");
    pl("------------------------");
    boolean finished = false;
    do {
        pl(YELLOW + "What function would you like to run? Type \"help\" for a full list of options.");
        String input = prompt();
        pl();
        if (input.toLowerCase().startsWith("help")) {
            help(input.replaceFirst("help ?", "").toLowerCase().split(" "));
        } else if (input.equalsIgnoreCase("refactor")) {
            refactor();
        } else if (input.toLowerCase().startsWith("print")) {
            print(input.replaceFirst("print ?", "").toLowerCase().split(" "));
        } else if (input.equalsIgnoreCase("cleardb")) {
            cleardb();
        } else if (input.equalsIgnoreCase("edit")) {
            edit();
        } else if (input.equalsIgnoreCase("merge")) {
            merge();
        } else if (input.equalsIgnoreCase("interpreter")) {
            new Interpreter(null, System.getProperty("user.dir"));
        } else if (input.equalsIgnoreCase("hidden-keys")) {
            hiddenKeys();
        } else if (input.equalsIgnoreCase("exit")) {
            pl("Thanks for using the " + CYAN + BOLD + "Data Manager!" + reset());
            finished = true;
        } else {
            pl("I'm sorry, that's not a valid command. Here's the help:");
            help(new String[] {});
        }
    } while (finished == false);
    StreamUtils.GetSystemOut().println(TermColors.reset());
}
Also used : PersistenceNetwork(com.laytonsmith.persistence.PersistenceNetwork) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) TaskManager(com.laytonsmith.core.taskmanager.TaskManager) Profiler(com.laytonsmith.core.profiler.Profiler) Profiles(com.laytonsmith.core.Profiles) ConnectionMixinFactory(com.laytonsmith.persistence.io.ConnectionMixinFactory) MethodScriptExecutionQueue(com.laytonsmith.core.MethodScriptExecutionQueue) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Environment(com.laytonsmith.core.environments.Environment) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException)

Example 4 with CommandHelperEnvironment

use of com.laytonsmith.core.environments.CommandHelperEnvironment in project CommandHelper by EngineHub.

the class BukkitMCCommand method handleCustomCommand.

@Override
public boolean handleCustomCommand(MCCommandSender sender, String label, String[] args) {
    if (Commands.onCommand.containsKey(cmd.getName().toLowerCase())) {
        Target t = Target.UNKNOWN;
        CArray cargs = new CArray(t);
        for (String arg : args) {
            cargs.push(new CString(arg, t), t);
        }
        CClosure closure = Commands.onCommand.get(cmd.getName().toLowerCase());
        CommandHelperEnvironment cEnv = closure.getEnv().getEnv(CommandHelperEnvironment.class);
        cEnv.SetCommandSender(sender);
        cEnv.SetCommand("/" + label + StringUtils.Join(args, " "));
        try {
            closure.execute(new CString(label, t), new CString(sender.getName(), t), cargs, // reserved for an obgen style command array
            new CArray(t));
        } catch (FunctionReturnException e) {
            Construct fret = e.getReturn();
            if (fret instanceof CBoolean) {
                return ((CBoolean) fret).getBoolean();
            }
        } catch (ConfigRuntimeException cre) {
            cre.setEnv(closure.getEnv());
            ConfigRuntimeException.HandleUncaughtException(cre, closure.getEnv());
        }
        return true;
    } else {
        return false;
    }
}
Also used : Target(com.laytonsmith.core.constructs.Target) CClosure(com.laytonsmith.core.constructs.CClosure) CBoolean(com.laytonsmith.core.constructs.CBoolean) CArray(com.laytonsmith.core.constructs.CArray) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Construct(com.laytonsmith.core.constructs.Construct) CString(com.laytonsmith.core.constructs.CString) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString)

Example 5 with CommandHelperEnvironment

use of com.laytonsmith.core.environments.CommandHelperEnvironment in project CommandHelper by EngineHub.

the class Manager method doAddEdit.

public static boolean doAddEdit(String key, String valueScript) {
    try {
        Environment env = Environment.createEnvironment(gEnv, new CommandHelperEnvironment());
        Construct c = MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(valueScript, null, true)), env, null, null);
        String value = Construct.json_encode(c, Target.UNKNOWN);
        pl(CYAN + "Adding: " + WHITE + value);
        String[] k = key.split("\\.");
        DaemonManager dm = new DaemonManager();
        persistenceNetwork.set(dm, k, value);
        try {
            dm.waitForThreads();
        } catch (InterruptedException e) {
        // 
        }
        return true;
    } catch (Exception ex) {
        pl(RED + ex.getMessage());
        return false;
    }
}
Also used : DaemonManager(com.laytonsmith.PureUtilities.DaemonManager) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Environment(com.laytonsmith.core.environments.Environment) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Construct(com.laytonsmith.core.constructs.Construct) URISyntaxException(java.net.URISyntaxException) ReadOnlyException(com.laytonsmith.persistence.ReadOnlyException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) DataSourceException(com.laytonsmith.persistence.DataSourceException) IOException(java.io.IOException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException)

Aggregations

CommandHelperEnvironment (com.laytonsmith.core.environments.CommandHelperEnvironment)8 Environment (com.laytonsmith.core.environments.Environment)6 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)6 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)6 TaskManager (com.laytonsmith.core.taskmanager.TaskManager)6 ConfigCompileGroupException (com.laytonsmith.core.exceptions.ConfigCompileGroupException)5 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)5 IOException (java.io.IOException)4 Construct (com.laytonsmith.core.constructs.Construct)3 CancelCommandException (com.laytonsmith.core.exceptions.CancelCommandException)3 Profiler (com.laytonsmith.core.profiler.Profiler)3 PersistenceNetwork (com.laytonsmith.persistence.PersistenceNetwork)3 ConnectionMixinFactory (com.laytonsmith.persistence.io.ConnectionMixinFactory)3 File (java.io.File)3 CString (com.laytonsmith.core.constructs.CString)2 ProgramFlowManipulationException (com.laytonsmith.core.exceptions.ProgramFlowManipulationException)2 ProfilePoint (com.laytonsmith.core.profiler.ProfilePoint)2 DataSourceException (com.laytonsmith.persistence.DataSourceException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2