@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { String id = null; if (args.length == 1) { // We are cancelling an arbitrary event id = args[0].val(); } else { // We are cancelling this event. If we are not in an event, throw an exception if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( "No event ID specified, and not running inside an event", ExceptionType.BindException, t); } id = environment.getEnv(GlobalEnv.class).GetEvent().getBoundEvent().getId(); } BoundEvent be = EventUtils.GetEventById(id); Event event = null; if (be != null) { event = be.getEventDriver(); } EventUtils.UnregisterEvent(id); // Only remove the counter if it had been added in the first place. if (event != null && event.addCounter()) { synchronized (bindCounter) { bindCounter.decrementAndGet(); if (bindCounter.get() == 0) { environment.getEnv(GlobalEnv.class).GetDaemonManager().deactivateThread(null); } } } return CVoid.VOID; }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( "lock must be called from within an event handler", ExceptionType.BindException, t); } BoundEvent.ActiveEvent e = environment.getEnv(GlobalEnv.class).GetEvent(); Priority p = e.getBoundEvent().getPriority(); List<String> params = new ArrayList<String>(); if (args.length == 0) { e.lock(null); } else { if (args[0] instanceof CArray) { CArray ca = (CArray) args[1]; for (int i = 0; i < ca.size(); i++) { params.add(ca.get(i, t).val()); } } else { for (int i = 0; i < args.length; i++) { params.add(args[i].val()); } } } for (String param : params) { e.lock(param); } return CVoid.VOID; }
public static Environment createEnvironment(EnvironmentImpl... envs) { Environment e = new Environment(); for (EnvironmentImpl ee : envs) { e.addEnv(ee); } return e; }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( "consume may only be called from an event handler!", ExceptionType.BindException, t); } environment.getEnv(GlobalEnv.class).GetEvent().consume(); return CVoid.VOID; }
@Override public Environment clone() throws CloneNotSupportedException { Environment clone = new Environment(); clone.environments = new HashMap<Class<? extends EnvironmentImpl>, Environment.EnvironmentImpl>(); for (Class c : environments.keySet()) { clone.environments.put(c, environments.get(c).clone()); } return clone; }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( "is_consumed must be called from within an event handler", ExceptionType.BindException, t); } return CBoolean.get(environment.getEnv(GlobalEnv.class).GetEvent().isConsumed()); }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( "is_locked may only be called from inside an event handler", ExceptionType.BindException, t); } return CBoolean.get(environment.getEnv(GlobalEnv.class).GetEvent().isLocked(args[0].val())); }
public void compileMS(MCPlayer player, Environment env) { for (FileInfo fi : ms) { boolean exception = false; try { env.getEnv(CommandHelperEnvironment.class) .SetCommandSender(Static.getServer().getConsole()); MethodScriptCompiler.registerAutoIncludes(env, null); MethodScriptCompiler.execute( MethodScriptCompiler.compile(MethodScriptCompiler.lex(fi.contents, fi.file, true)), env, null, null); } catch (ConfigCompileException e) { exception = true; ConfigRuntimeException.React( e, fi.file.getAbsolutePath() + " could not be compiled, due to a compile error.", player); } catch (ConfigRuntimeException e) { exception = true; ConfigRuntimeException.React(e, env); } catch (CancelCommandException e) { if (e.getMessage() != null && !"".equals(e.getMessage().trim())) { logger.log(Level.INFO, e.getMessage()); } } catch (ProgramFlowManipulationException e) { exception = true; ConfigRuntimeException.React( ConfigRuntimeException.CreateUncatchableException( "Cannot break program flow in main files.", e.getTarget()), env); } finally { env.getEnv(CommandHelperEnvironment.class).SetCommandSender(null); } if (exception) { if (Prefs.HaltOnFailure()) { logger.log( Level.SEVERE, TermColors.RED + "[CommandHelper]: Compilation halted due to unrecoverable failure." + TermColors.reset()); return; } } } logger.log( Level.INFO, TermColors.YELLOW + "[CommandHelper]: MethodScript files processed" + TermColors.reset()); if (player != null) { player.sendMessage(MCChatColor.YELLOW + "[CommandHelper]: MethodScript files processed"); } }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { String parameter = args[0].val(); Construct value = args[1]; boolean throwOnFailure = false; if (args.length == 3) { throwOnFailure = Static.getBoolean(args[3]); } if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( this.getName() + " must be called from within an event handler", ExceptionType.BindException, t); } Event e = environment.getEnv(GlobalEnv.class).GetEvent().getEventDriver(); if (environment .getEnv(GlobalEnv.class) .GetEvent() .getBoundEvent() .getPriority() .equals(Priority.MONITOR)) { throw new ConfigRuntimeException( "Monitor level handlers may not modify an event!", ExceptionType.BindException, t); } ActiveEvent active = environment.getEnv(GlobalEnv.class).GetEvent(); boolean success = false; if (!active.isLocked(parameter)) { try { success = e.modifyEvent( parameter, value, environment.getEnv(GlobalEnv.class).GetEvent().getUnderlyingEvent()); } catch (ConfigRuntimeException ex) { ex.setFile(t.file()); ex.setLineNum(t.line()); ex.setColumn(t.col()); throw ex; } } else { success = false; } if (throwOnFailure && !success) { throw new ConfigRuntimeException( "Event parameter is already locked!", ExceptionType.BindException, t); } return CBoolean.get(success); }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (environment.getEnv(GlobalEnv.class).GetEvent() == null) { throw new ConfigRuntimeException( "event_meta must be called from within an event handler!", ExceptionType.BindException, t); } CArray history = new CArray(t); for (String entry : environment.getEnv(GlobalEnv.class).GetEvent().getHistory()) { history.push(new CString(entry, t), t); } return history; }
@Before public void setUp() throws Exception { fakeServer = GetFakeServer(); fakePlayer = GetOnlinePlayer(fakeServer); env.getEnv(CommandHelperEnvironment.class).SetPlayer(fakePlayer); StaticTest.InstallFakeConvertor(fakePlayer); Static.InjectPlayer(fakePlayer); }
/** * Runs eval on the code tree, and if it returns an ival, resolves it. * * @param c * @param env * @return */ public Construct seval(ParseTree c, final Environment env) { Construct ret = eval(c, env); while (ret instanceof IVariable) { IVariable cur = (IVariable) ret; ret = env.getEnv(GlobalEnv.class).GetVarList().get(cur.getName(), cur.getTarget()).ival(); } return ret; }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { BoundEvent.ActiveEvent original = environment.getEnv(GlobalEnv.class).GetEvent(); if (original == null) { throw new ConfigRuntimeException( "is_cancelled cannot be called outside an event handler", ExceptionType.BindException, t); } boolean result = false; if (original.getUnderlyingEvent() != null && original.isCancellable()) { result = original.isCancelled(); } return CBoolean.get(result); }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { boolean cancelled = true; if (args.length == 1) { cancelled = Static.getBoolean(args[0]); } BoundEvent.ActiveEvent original = environment.getEnv(GlobalEnv.class).GetEvent(); if (original == null) { throw new ConfigRuntimeException( "cancel cannot be called outside an event handler", ExceptionType.BindException, t); } if (original.getUnderlyingEvent() != null && original.isCancellable()) { original.setCancelled(cancelled); } return CVoid.VOID; }
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { String name = args[0].val(); String endpoint = args[1].val(); int type = ZMQ.PUB; if (args.length == 3) { String stype = args[2].val().toUpperCase(); if (!"PUB".equals(stype) && !"SUB".equals(stype)) { throw new ConfigRuntimeException( "You must specify PUB or SUB" + " for comm_listen's third argument!", Exceptions.ExceptionType.NotFoundException, t); } if ("SUB".equals(stype)) { type = ZMQ.SUB; } } NodePoint node; DaemonManager daemon = environment.getEnv(GlobalEnv.class).GetDaemonManager(); try { node = Tracking.getOrCreate(daemon, type, name); } catch (InvalidNameException ex) { throw new ConfigRuntimeException( "Invalid name " + name + " given to comm_listen!", Exceptions.ExceptionType.FormatException, t); } try { node.listen(endpoint); } catch (ZMQException e) { throw new ConfigRuntimeException( "Exception while listening: " + e.getMessage(), Exceptions.ExceptionType.IOException, t); } return CNull.NULL; }
@Override public Construct exec(final Target t, final Environment environment, Construct... args) throws ConfigRuntimeException { startup(); Construct arg = args[args.length - 1]; if (!(arg instanceof CClosure)) { throw new ConfigRuntimeException( "The last argument to " + getName() + " must be a closure.", ExceptionType.CastException, t); } final CClosure closure = ((CClosure) arg); final Construct[] newArgs = new Construct[args.length - 1]; // Make a new array minus the closure System.arraycopy(args, 0, newArgs, 0, newArgs.length); queue.invokeLater( environment.getEnv(GlobalEnv.class).GetDaemonManager(), new Runnable() { @Override public void run() { Construct returnValue = new CNull(); Construct exception = new CNull(); try { returnValue = new query().exec(t, environment, newArgs); } catch (ConfigRuntimeException ex) { exception = ObjectGenerator.GetGenerator().exception(ex, t); } final Construct cret = returnValue; final Construct cex = exception; StaticLayer.GetConvertor() .runOnMainThreadLater( environment.getEnv(GlobalEnv.class).GetDaemonManager(), new Runnable() { @Override public void run() { closure.execute(new Construct[] {cret, cex}); } }); } }); return new CVoid(t); }
public void run(final List<Variable> vars, Environment myEnv, final MethodScriptComplete done) { // Some things, such as the label are determined at compile time this.CurrentEnv = myEnv; this.CurrentEnv.getEnv(GlobalEnv.class).SetLabel(this.label); MCCommandSender p = myEnv.getEnv(CommandHelperEnvironment.class).GetCommandSender(); if (!hasBeenCompiled || compilerError) { Target target = Target.UNKNOWN; if (left.size() >= 1) { try { target = new Target(left.get(0).line_num, left.get(0).file, left.get(0).column); } catch (NullPointerException e) { // Oh well, we tried to get more information } } throw new ConfigRuntimeException( "Unable to run command, script not yet compiled, or a compiler error occured for that command." + " To see the compile error, run /reloadaliases", null, target); } if (p instanceof MCPlayer) { if (CurrentEnv.getEnv(GlobalEnv.class).GetLabel() != null) { PermissionsResolver perms = CurrentEnv.getEnv(GlobalEnv.class).GetPermissionsResolver(); String[] groups = CurrentEnv.getEnv(GlobalEnv.class).GetLabel().split("/"); for (String group : groups) { if (group.startsWith("-") && perms.inGroup(((MCPlayer) p).getName(), group.substring(1))) { // negative permission throw new ConfigRuntimeException( "You do not have permission to use that command", ExceptionType.InsufficientPermissionException, Target.UNKNOWN); } else if (perms.inGroup(((MCPlayer) p).getName(), group)) { // They do have permission. break; } } } } try { for (ParseTree rootNode : cright) { for (Construct tempNode : rootNode.getAllData()) { if (tempNode instanceof Variable) { if (left_vars == null) { throw new ConfigRuntimeException( "$variables may not be used in this context. Only @variables may be.", null, tempNode.getTarget()); } ((Variable) tempNode) .setVal( new CString( Static.resolveDollarVar( left_vars.get(((Variable) tempNode).getName()), vars) .toString(), tempNode.getTarget())); } } MethodScriptCompiler.registerAutoIncludes(CurrentEnv, this); MethodScriptCompiler.execute(rootNode, CurrentEnv, done, this); } } catch (ConfigRuntimeException ex) { // We don't know how to handle this really, so let's pass it up the chain. throw ex; } catch (CancelCommandException e) { // p.sendMessage(e.getMessage()); // The message in the exception is actually empty } catch (LoopBreakException e) { if (p != null) { p.sendMessage("The break() function must be used inside a for() or foreach() loop"); } System.out.println("The break() function must be used inside a for() or foreach() loop"); } catch (LoopContinueException e) { if (p != null) { p.sendMessage("The continue() function must be used inside a for() or foreach() loop"); } System.out.println("The continue() function must be used inside a for() or foreach() loop"); } catch (FunctionReturnException e) { if (myEnv.getEnv(CommandHelperEnvironment.class).GetEvent() != null) { // Oh, we're running in an event handler. Those know how to catch it too. throw e; } if (p != null) { p.sendMessage("The return() function must be used inside a procedure."); } System.out.println("The return() function must be used inside a procedure."); } catch (Throwable t) { System.out.println("An unexpected exception occured during the execution of a script."); t.printStackTrace(); if (p != null) { p.sendMessage( "An unexpected exception occured during the execution of your script. Please check the console for more information."); } } if (done != null) { done.done(null); } }
private Procedure getProc(String name) { return CurrentEnv.getEnv(GlobalEnv.class).GetProcs().get(name); }
/** * 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, List<Script> playerCommands) { GlobalEnv gEnv; try { gEnv = new GlobalEnv( parent.executionQueue, parent.profiler, parent.persistenceNetwork, parent.permissionsResolver, MethodScriptFileLocations.getDefault().getConfigDirectory(), new Profiles(MethodScriptFileLocations.getDefault().getSQLProfilesFile())); } catch (IOException ex) { Logger.getLogger(AliasCore.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Profiles.InvalidProfileException ex) { throw ConfigRuntimeException.CreateUncatchableException(ex.getMessage(), Target.UNKNOWN); } CommandHelperEnvironment cEnv = new CommandHelperEnvironment(); cEnv.SetCommandSender(player); Environment env = Environment.createEnvironment(gEnv, cEnv); if (player instanceof MCBlockCommandSender) { cEnv.SetBlockCommandSender((MCBlockCommandSender) player); } if (scripts == null) { throw ConfigRuntimeException.CreateUncatchableException( "Cannot run alias commands, no config file is loaded", Target.UNKNOWN); } boolean match = false; try { // catch RuntimeException // If player is null, we are running the test harness, so don't // 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; } // Global aliases override personal ones, so check the list first 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()); } 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) { System.err.println(e.getMessage()); player.sendMessage(MCChatColor.RED + e.getMessage()); } finally { Static.getAliasCore().removePlayerReference(player); } } }); } finally { alias.stop(); } } catch (ConfigRuntimeException ex) { ex.setEnv(env); ConfigRuntimeException.React(ex, env); } catch (Throwable e) { // This is not a simple user script error, this is a deeper problem, so we always // handle this. System.err.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) { System.err.println("An unexpected exception occured inside the command " + s.toString()); e.printStackTrace(); } } if (player instanceof MCPlayer) { if (match == false && playerCommands != null) { // if we are still looking, look in the aliases for this player for (Script ac : playerCommands) { // RunnableAlias b = ac.getRunnableAliases(command, player); try { ac.compile(); if (ac.match(command)) { Static.getAliasCore().addPlayerReference(player); ProfilePoint alias = env.getEnv(GlobalEnv.class) .GetProfiler() .start( "User Alias (" + player.getName() + ") - \"" + command + "\"", LogLevel.ERROR); try { ac.run( ac.getVariables(command), env, new MethodScriptComplete() { @Override public void done(String output) { if (output != null) { if (!output.trim().isEmpty() && output.trim().startsWith("/")) { if (Prefs.DebugMode()) { Static.getLogger() .log( Level.INFO, "[CommandHelper]: Executing command on " + ((MCPlayer) player).getName() + ": " + output.trim()); } ((MCPlayer) player).chat(output.trim()); } } Static.getAliasCore().removePlayerReference(player); } }); } finally { alias.stop(); } match = true; break; } } catch (ConfigRuntimeException e) { // Unlike system scripts, this should just report the problem to the player // env.getEnv(CommandHelperEnvironment.class).SetCommandSender(player); Static.getAliasCore().removePlayerReference(player); e.setEnv(env); ConfigRuntimeException.React(e, env); match = true; } catch (ConfigCompileException e) { // Something strange happened, and a bad alias was added // to the database. Our best course of action is to just // skip it. } } } } } 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" + StringUtil.joinString(Arrays.asList(e.getStackTrace()), "\n", 0)); } return match; }
public Construct eval(ParseTree c, final Environment env) throws CancelCommandException { final Construct m = c.getData(); CurrentEnv = env; // TODO: Reevaluate if this line is needed. The script doesn't know the label inherently, the // environment does, and setting it this way taints the environment. CurrentEnv.getEnv(GlobalEnv.class).SetLabel(this.label); if (m.getCType() == ConstructType.FUNCTION) { env.getEnv(GlobalEnv.class).SetScript(this); if (m.val().matches("^_[^_].*")) { // Not really a function, so we can't put it in Function. Procedure p = getProc(m.val()); if (p == null) { throw new ConfigRuntimeException( "Unknown procedure \"" + m.val() + "\"", ExceptionType.InvalidProcedureException, m.getTarget()); } Environment newEnv = env; try { newEnv = env.clone(); } catch (Exception e) { } ProfilePoint pp = env.getEnv(GlobalEnv.class).GetProfiler().start(m.val() + " execution", LogLevel.INFO); Construct ret = p.cexecute(c.getChildren(), newEnv, m.getTarget()); pp.stop(); return ret; } final Function f; try { f = (Function) FunctionList.getFunction(m); } catch (ConfigCompileException e) { // Turn it into a config runtime exception. This shouldn't ever happen though. throw new ConfigRuntimeException("Unable to find function " + m.val(), m.getTarget()); } // We have special handling for loop and other control flow functions if (f instanceof assign) { if (c.getChildAt(0).getData() instanceof CFunction) { CFunction test = (CFunction) c.getChildAt(0).getData(); if (test.val().equals("array_get")) { env.getEnv(GlobalEnv.class).SetFlag("array_get_alt_mode", true); Construct arrayAndIndex = eval(c.getChildAt(0), env); env.getEnv(GlobalEnv.class).ClearFlag("array_get_alt_mode"); return ((assign) f) .array_assign(m.getTarget(), env, arrayAndIndex, eval(c.getChildAt(1), env)); } } } if (f.useSpecialExec()) { ProfilePoint p = null; if (f.shouldProfile() && env.getEnv(GlobalEnv.class).GetProfiler() != null && env.getEnv(GlobalEnv.class).GetProfiler().isLoggable(f.profileAt())) { p = env.getEnv(GlobalEnv.class) .GetProfiler() .start(f.profileMessageS(c.getChildren()), f.profileAt()); } Construct ret = f.execs(m.getTarget(), env, this, c.getChildren().toArray(new ParseTree[] {})); if (p != null) { p.stop(); } return ret; } ArrayList<Construct> args = new ArrayList<Construct>(); for (ParseTree c2 : c.getChildren()) { args.add(eval(c2, env)); } if (f.isRestricted()) { boolean perm = Static.hasCHPermission(f.getName(), env); if (!perm) { throw new ConfigRuntimeException( "You do not have permission to use the " + f.getName() + " function.", ExceptionType.InsufficientPermissionException, m.getTarget()); } } Object[] a = args.toArray(); Construct[] ca = new Construct[a.length]; for (int i = 0; i < a.length; i++) { ca[i] = (Construct) a[i]; // CArray, CBoolean, CDouble, CInt, CNull, CString, CVoid, CEntry, CLabel (only to sconcat). if (!(ca[i] instanceof CArray || ca[i] instanceof CBoolean || ca[i] instanceof CDouble || ca[i] instanceof CInt || ca[i] instanceof CNull || ca[i] instanceof CString || ca[i] instanceof CVoid || ca[i] instanceof IVariable || ca[i] instanceof CEntry || ca[i] instanceof CLabel) && (!f.getName().equals("__autoconcat__") && (ca[i] instanceof CLabel))) { throw new ConfigRuntimeException( "Invalid Construct (" + ca[i].getClass() + ") being passed as an argument to a function (" + f.getName() + ")", null, m.getTarget()); } if (env.getEnv(GlobalEnv.class).GetFlag("array_get_alt_mode") == Boolean.TRUE && i == 0) { continue; } while (f.preResolveVariables() && ca[i] instanceof IVariable) { IVariable cur = (IVariable) ca[i]; ca[i] = env.getEnv(GlobalEnv.class).GetVarList().get(cur.getName(), cur.getTarget()).ival(); } } { // It takes a moment to generate the toString of some things, so lets not do it // if we actually aren't going to profile ProfilePoint p = null; if (f.shouldProfile() && env.getEnv(GlobalEnv.class).GetProfiler() != null && env.getEnv(GlobalEnv.class).GetProfiler().isLoggable(f.profileAt())) { p = env.getEnv(GlobalEnv.class).GetProfiler().start(f.profileMessage(ca), f.profileAt()); } Construct ret = f.exec(m.getTarget(), env, ca); if (p != null) { p.stop(); } return ret; } } else if (m.getCType() == ConstructType.VARIABLE) { return new CString(m.val(), m.getTarget()); } else { return m; } }
/** * Loads the global alias file in from the file system. If a player is running the command, send a * reference to them, and they will see compile errors, otherwise, null. * * @param player * @param settings The argument list for the settings. */ public final void reload(MCPlayer player, String[] settings) { boolean reloadGlobals = true; boolean reloadTimeouts = true; boolean reloadExecutionQueue = true; boolean reloadPersistenceConfig = true; boolean reloadPreferences = true; boolean reloadProfiler = true; boolean reloadScripts = true; boolean reloadExtensions = true; if (settings != null) { ArgumentParser.ArgumentParserResults results; try { results = reloadOptions.match(settings); } catch (ArgumentParser.ValidationException ex) { Logger.getLogger(AliasCore.class.getName()).log(Level.SEVERE, null, ex); return; } if (results.isFlagSet('h')) { if (player != null) { player.sendMessage(reloadOptions.getBuiltDescription()); } else { System.out.println(reloadOptions.getBuiltDescription()); } return; } if (results.isFlagSet("whitelist")) { // Invert the results reloadGlobals = false; reloadTimeouts = false; reloadExecutionQueue = false; reloadPersistenceConfig = false; reloadPreferences = false; reloadProfiler = false; reloadScripts = false; reloadExtensions = false; } if (results.isFlagSet('g')) { reloadGlobals = !reloadGlobals; } if (results.isFlagSet('t')) { reloadTimeouts = !reloadTimeouts; } if (results.isFlagSet('e')) { reloadExecutionQueue = !reloadExecutionQueue; } if (results.isFlagSet('r') || results.isFlagSet("persistence-config")) { reloadPersistenceConfig = !reloadPersistenceConfig; } if (results.isFlagSet('p')) { reloadPreferences = !reloadPreferences; } if (results.isFlagSet('f')) { reloadProfiler = !reloadProfiler; } if (results.isFlagSet('s')) { reloadScripts = !reloadScripts; } if (results.isFlagSet('x')) { reloadExtensions = !reloadExtensions; } } try { if (Prefs.AllowDynamicShell()) { CHLog.GetLogger() .Log( CHLog.Tags.GENERAL, LogLevel.WARNING, "allow-dynamic-shell is set to true in " + CommandHelperFileLocations.getDefault().getProfilerConfigFile().getName() + " you should set this to false, except during development.", Target.UNKNOWN); } // Allow new-style extensions know we are about to reload aliases. ExtensionManager.PreReloadAliases( reloadGlobals, reloadTimeouts, reloadExecutionQueue, reloadPersistenceConfig, reloadPreferences, reloadProfiler, reloadScripts, reloadExtensions); StaticLayer.GetConvertor().runShutdownHooks(); CHLog.initialize(MethodScriptFileLocations.getDefault().getConfigDirectory()); // Clear out the data source cache DataSourceFactory.DisconnectAll(); if (reloadExtensions) { ExtensionManager.Startup(); } CHLog.GetLogger() .Log(CHLog.Tags.GENERAL, LogLevel.VERBOSE, "Scripts reloading...", Target.UNKNOWN); if (parent.profiler == null || reloadProfiler) { parent.profiler = new Profiler(MethodScriptFileLocations.getDefault().getProfilerConfigFile()); } if (parent.persistenceNetwork == null || reloadPersistenceConfig) { MemoryDataSource.ClearDatabases(); // PacketJumper.startup(); ConnectionMixinFactory.ConnectionMixinOptions options = new ConnectionMixinFactory.ConnectionMixinOptions(); options.setWorkingDirectory(MethodScriptFileLocations.getDefault().getConfigDirectory()); parent.persistenceNetwork = new PersistenceNetwork( MethodScriptFileLocations.getDefault().getPersistenceConfig(), new URI( "sqlite:/" + MethodScriptFileLocations.getDefault() .getDefaultPersistenceDBFile() .getCanonicalFile() .toURI() .getRawSchemeSpecificPart() .replace("\\", "/")), options); } GlobalEnv gEnv; try { gEnv = new GlobalEnv( parent.executionQueue, parent.profiler, parent.persistenceNetwork, parent.permissionsResolver, MethodScriptFileLocations.getDefault().getConfigDirectory(), new Profiles(MethodScriptFileLocations.getDefault().getSQLProfilesFile())); } catch (Profiles.InvalidProfileException ex) { CHLog.GetLogger().e(CHLog.Tags.GENERAL, ex.getMessage(), Target.UNKNOWN); return; } if (reloadExecutionQueue) { parent.executionQueue.stopAllNow(); } CommandHelperEnvironment cEnv = new CommandHelperEnvironment(); Environment env = Environment.createEnvironment(gEnv, cEnv); if (reloadGlobals) { Globals.clear(); } if (reloadTimeouts) { Scheduling.ClearScheduledRunners(); } if (!aliasConfig.exists()) { aliasConfig.getParentFile().mkdirs(); aliasConfig.createNewFile(); try { String samp_config = getStringResource(AliasCore.class.getResourceAsStream("/samp_config.txt")); // Because the sample config may have been written an a machine that isn't this type, // replace all // line endings samp_config = samp_config.replaceAll("\n|\r\n", System.getProperty("line.separator")); file_put_contents(aliasConfig, samp_config, "o"); } catch (Exception e) { logger.log(Level.WARNING, "CommandHelper: Could not write sample config file"); } } if (!mainFile.exists()) { mainFile.getParentFile().mkdirs(); mainFile.createNewFile(); try { String samp_main = getStringResource(AliasCore.class.getResourceAsStream("/samp_main.txt")); samp_main = samp_main.replaceAll("\n|\r\n", System.getProperty("line.separator")); file_put_contents(mainFile, samp_main, "o"); } catch (Exception e) { logger.log(Level.WARNING, "CommandHelper: Could not write sample main file"); } } if (!Prefs.isInitialized() || reloadPreferences) { Prefs.init(prefFile); } if (reloadScripts) { EventUtils.UnregisterAll(); ExtensionManager.RunHooks(); IncludeCache.clearCache(); // Clear the include cache, so it re-pulls files Static.getServer() .getMessenger() .closeAllChannels(); // Close all channel messager channels registered by CH. scripts = new ArrayList<Script>(); LocalPackage localPackages = new LocalPackage(); // Run the main file once String main = file_get_contents(mainFile.getAbsolutePath()); localPackages.appendMS(main, mainFile); String alias_config = file_get_contents(aliasConfig.getAbsolutePath()); // get the file again localPackages.appendMSA(alias_config, aliasConfig); // Now that we've included the default files, search the local_packages directory GetAuxAliases(auxAliases, localPackages); autoIncludes = localPackages.getAutoIncludes(); ProfilePoint compilerMS = parent.profiler.start("Compilation of MS files in Local Packages", LogLevel.VERBOSE); try { localPackages.compileMS(player, env); } finally { compilerMS.stop(); } ProfilePoint compilerMSA = parent.profiler.start("Compilation of MSA files in Local Packages", LogLevel.VERBOSE); try { localPackages.compileMSA(scripts, player); } finally { compilerMSA.stop(); } } } catch (IOException ex) { logger.log( Level.SEVERE, "[CommandHelper]: Path to config file is not correct/accessable. Please" + " check the location and try loading the plugin again."); } catch (Throwable t) { t.printStackTrace(); } if (!Economy.setupEconomy()) { if (Prefs.DebugMode()) { logger.log( Level.WARNING, "[CommandHelper]: Economy could not be initialized. No further" + " errors will occur, unless you try to use an Economy function."); } } ExtensionManager.PostReloadAliases(); }
@Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { try { Profiles.Profile profile; if (args[0] instanceof CArray) { Map<String, String> data = new HashMap<String, String>(); for (String key : ((CArray) args[0]).keySet()) { data.put(key, ((CArray) args[0]).get(key).val()); } profile = Profiles.getProfile(data); } else { Profiles profiles = environment.getEnv(GlobalEnv.class).getSQLProfiles(); profile = profiles.getProfileById(args[0].val()); } String query = args[1].val(); Construct[] params = new Construct[args.length - 2]; for (int i = 2; i < args.length; i++) { int index = i - 2; params[index] = args[i]; } // Parameters are now all parsed into java objects. Connection conn = DriverManager.getConnection(profile.getConnectionString()); PreparedStatement ps = null; try { ps = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); for (int i = 0; i < params.length; i++) { int type = ps.getParameterMetaData().getParameterType(i + 1); if (params[i] == null) { if (ps.getParameterMetaData().isNullable(i + 1) == ParameterMetaData.parameterNoNulls) { throw new ConfigRuntimeException( "Parameter " + (i + 1) + " cannot be set to null. Check your parameters and try again.", ExceptionType.SQLException, t); } else { ps.setNull(i + 1, type); continue; } } try { if (params[i] instanceof CInt) { ps.setLong(i + 1, Static.getInt(params[i], t)); } else if (params[i] instanceof CDouble) { ps.setDouble(i + 1, (Double) Static.getDouble(params[i], t)); } else if (params[i] instanceof CString) { ps.setString(i + 1, (String) params[i].val()); } else if (params[i] instanceof CByteArray) { ps.setBytes(i + 1, ((CByteArray) params[i]).asByteArrayCopy()); } else if (params[i] instanceof CBoolean) { ps.setBoolean(i + 1, Static.getBoolean(params[i])); } else { throw new ConfigRuntimeException( "The type " + params[i].getClass().getSimpleName() + " of parameter " + (i + 1) + " is not supported.", ExceptionType.CastException, t); } } catch (ClassCastException ex) { throw new ConfigRuntimeException( "Could not cast parameter " + (i + 1) + " to " + ps.getParameterMetaData().getParameterTypeName(i + 1) + " from " + params[i].getClass().getSimpleName() + ".", ExceptionType.CastException, t, ex); } } boolean isResultSet = ps.execute(); if (isResultSet) { // Result set CArray ret = new CArray(t); ResultSetMetaData md = ps.getMetaData(); ResultSet rs = ps.getResultSet(); while (rs.next()) { CArray row = new CArray(t); for (int i = 1; i <= md.getColumnCount(); i++) { Construct value; int columnType = md.getColumnType(i); if (columnType == Types.INTEGER || columnType == Types.TINYINT || columnType == Types.SMALLINT || columnType == Types.BIGINT) { value = new CInt(rs.getLong(i), t); } else if (columnType == Types.FLOAT || columnType == Types.DOUBLE || columnType == Types.REAL || columnType == Types.DECIMAL || columnType == Types.NUMERIC) { value = new CDouble(rs.getDouble(i), t); } else if (columnType == Types.VARCHAR || columnType == Types.CHAR || columnType == Types.LONGVARCHAR) { value = new CString(rs.getString(i), t); } else if (columnType == Types.BLOB || columnType == Types.BINARY || columnType == Types.VARBINARY || columnType == Types.LONGVARBINARY) { value = CByteArray.wrap(rs.getBytes(i), t); } else if (columnType == Types.DATE || columnType == Types.TIME || columnType == Types.TIMESTAMP) { if (md.getColumnTypeName(i).equals("YEAR")) { value = new CInt(rs.getLong(i), t); } else { value = new CInt(rs.getTimestamp(i).getTime(), t); } } else if (columnType == Types.BOOLEAN || columnType == Types.BIT) { value = new CBoolean(rs.getBoolean(i), t); } else { throw new ConfigRuntimeException( "SQL returned a unhandled column type " + md.getColumnTypeName(i) + " for column " + md.getColumnName(i) + ".", ExceptionType.CastException, t); } row.set(md.getColumnName(i), value, t); } ret.push(row); } return ret; } else { ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { // This was an insert or something that returned generated keys. So we return // that here. return new CInt(rs.getInt(1), t); } // Update count. Just return null. return new CNull(t); } } finally { if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } } catch (Profiles.InvalidProfileException ex) { throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.SQLException, t, ex); } catch (SQLException ex) { throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.SQLException, t, ex); } }
@Override public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) { if (nodes.length < 5) { throw new ConfigRuntimeException( "bind accepts 5 or more parameters", ExceptionType.InsufficientArgumentsException, t); } Construct name = parent.seval(nodes[0], env); Construct options = parent.seval(nodes[1], env); Construct prefilter = parent.seval(nodes[2], env); Construct event_obj = parent.eval(nodes[3], env); IVariableList custom_params = new IVariableList(); for (int a = 0; a < nodes.length - 5; a++) { Construct var = parent.eval(nodes[4 + a], env); if (!(var instanceof IVariable)) { throw new ConfigRuntimeException( "The custom parameters must be ivariables", ExceptionType.CastException, t); } IVariable cur = (IVariable) var; custom_params.set( env.getEnv(GlobalEnv.class).GetVarList().get(cur.getName(), cur.getTarget())); } Environment newEnv = env; try { newEnv = env.clone(); } catch (Exception e) { } newEnv.getEnv(GlobalEnv.class).SetVarList(custom_params); ParseTree tree = nodes[nodes.length - 1]; // Check to see if our arguments are correct if (!(options instanceof CNull || options instanceof CArray)) { throw new ConfigRuntimeException( "The options must be an array or null", ExceptionType.CastException, t); } if (!(prefilter instanceof CNull || prefilter instanceof CArray)) { throw new ConfigRuntimeException( "The prefilters must be an array or null", ExceptionType.CastException, t); } if (!(event_obj instanceof IVariable)) { throw new ConfigRuntimeException( "The event object must be an IVariable", ExceptionType.CastException, t); } CString id; if (options instanceof CNull) { options = null; } if (prefilter instanceof CNull) { prefilter = null; } Event event; try { BoundEvent be = new BoundEvent( name.val(), (CArray) options, (CArray) prefilter, ((IVariable) event_obj).getName(), newEnv, tree, t); EventUtils.RegisterEvent(be); id = new CString(be.getId(), t); event = EventList.getEvent(be.getEventName()); } catch (EventException ex) { throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.BindException, t); } // Set up our bind counter, but only if the event is supposed to be added to the counter if (event.addCounter()) { synchronized (bindCounter) { if (bindCounter.get() == 0) { env.getEnv(GlobalEnv.class).GetDaemonManager().activateThread(null); StaticLayer.GetConvertor() .addShutdownHook( new Runnable() { @Override public void run() { synchronized (bindCounter) { bindCounter.set(0); } } }); } bindCounter.incrementAndGet(); } } return id; }