Search in sources :

Example 1 with GlobalEnv

use of com.laytonsmith.core.environments.GlobalEnv 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 GlobalEnv

use of com.laytonsmith.core.environments.GlobalEnv 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 GlobalEnv

use of com.laytonsmith.core.environments.GlobalEnv 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 GlobalEnv

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

the class RandomTests method testGetValues.

@Test
public void testGetValues() throws Exception {
    try {
        Environment env = Static.GenerateStandaloneEnvironment();
        GlobalEnv g = env.getEnv(GlobalEnv.class);
        ConnectionMixinFactory.ConnectionMixinOptions options;
        options = new ConnectionMixinFactory.ConnectionMixinOptions();
        options.setWorkingDirectory(new File("."));
        PersistenceNetwork network = new PersistenceNetwork("**=json://persistence.json", new URI("default"), options);
        ReflectionUtils.set(GlobalEnv.class, g, "persistenceNetwork", network);
        Run("store_value('t.test1', 'test')\n" + "store_value('t.test2', 'test')\n" + "store_value('t.test3.third', 'test')\n" + "msg(get_values('t'))", fakePlayer, new MethodScriptComplete() {

            @Override
            public void done(String output) {
            // 
            }
        }, env);
        verify(fakePlayer).sendMessage("{t.test1: test, t.test2: test, t.test3.third: test}");
    } finally {
        new File("persistence.json").deleteOnExit();
    }
}
Also used : MethodScriptComplete(com.laytonsmith.core.MethodScriptComplete) ConnectionMixinFactory(com.laytonsmith.persistence.io.ConnectionMixinFactory) Environment(com.laytonsmith.core.environments.Environment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) PersistenceNetwork(com.laytonsmith.persistence.PersistenceNetwork) CString(com.laytonsmith.core.constructs.CString) File(java.io.File) URI(java.net.URI) Test(org.junit.Test)

Example 5 with GlobalEnv

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

the class CompositeFunction method exec.

@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
    ParseTree tree;
    if (!cachedScripts.containsKey(this.getClass())) {
        try {
            String script = script();
            tree = MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)).getChildAt(0);
        } catch (ConfigCompileException | ConfigCompileGroupException ex) {
            // This is really bad.
            throw new Error(ex);
        }
        if (cacheCompile()) {
            cachedScripts.put(this.getClass(), tree);
        }
    } else {
        tree = cachedScripts.get(this.getClass());
    }
    GlobalEnv env = environment.getEnv(GlobalEnv.class);
    IVariableList oldVariables = env.GetVarList();
    IVariableList newVariables = new IVariableList();
    newVariables.set(new IVariable(CClassType.get("array"), "@arguments", new CArray(t, args.length, args), t));
    env.SetVarList(newVariables);
    Construct ret = CVoid.VOID;
    try {
        env.GetScript().eval(tree, environment);
    } catch (FunctionReturnException ex) {
        ret = ex.getReturn();
    }
    env.SetVarList(oldVariables);
    return ret;
}
Also used : IVariable(com.laytonsmith.core.constructs.IVariable) IVariableList(com.laytonsmith.core.constructs.IVariableList) CArray(com.laytonsmith.core.constructs.CArray) Construct(com.laytonsmith.core.constructs.Construct) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ParseTree(com.laytonsmith.core.ParseTree)

Aggregations

GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)8 CommandHelperEnvironment (com.laytonsmith.core.environments.CommandHelperEnvironment)6 Environment (com.laytonsmith.core.environments.Environment)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)4 PersistenceNetwork (com.laytonsmith.persistence.PersistenceNetwork)4 ConnectionMixinFactory (com.laytonsmith.persistence.io.ConnectionMixinFactory)4 File (java.io.File)4 CancelCommandException (com.laytonsmith.core.exceptions.CancelCommandException)3 Profiler (com.laytonsmith.core.profiler.Profiler)3 IOException (java.io.IOException)3 URI (java.net.URI)3 MethodScriptComplete (com.laytonsmith.core.MethodScriptComplete)2 ParseTree (com.laytonsmith.core.ParseTree)2 CString (com.laytonsmith.core.constructs.CString)2 Construct (com.laytonsmith.core.constructs.Construct)2 IVariable (com.laytonsmith.core.constructs.IVariable)2 ProgramFlowManipulationException (com.laytonsmith.core.exceptions.ProgramFlowManipulationException)2