public Construct exec(Target t, Env env, Construct... args)
        throws CancelCommandException, ConfigRuntimeException {
      double x = 0;
      double y = 0;
      double z = 0;
      float size = 3;
      MCWorld w = null;
      MCPlayer m = null;

      if (args.length == 2 && args[1] instanceof CInt) {
        CInt temp = (CInt) args[1];
        size = temp.getInt();
      }

      if (size > 100) {
        throw new ConfigRuntimeException(
            "A bit excessive, don't you think? Let's scale that back some, huh?",
            ExceptionType.RangeException,
            t);
      }

      if (!(args[0] instanceof CArray)) {
        throw new ConfigRuntimeException(
            "Expecting an array at parameter 1 of explosion", ExceptionType.CastException, t);
      }

      MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], w, t);
      w = loc.getWorld();
      x = loc.getX();
      z = loc.getZ();
      y = loc.getY();

      if (w == null) {
        if (!(env.GetCommandSender() instanceof MCPlayer)) {
          throw new ConfigRuntimeException(
              this.getName()
                  + " needs a world in the location array, or a player so it can take the current world of that player.",
              ExceptionType.PlayerOfflineException,
              t);
        }

        m = env.GetPlayer();
        w = m.getWorld();
      }

      w.explosion(x, y, z, size);
      return new CVoid(t);
    }
 @Test(timeout = 10000)
 public void testBroadcast()
     throws NoSuchFieldException, InstantiationException, IllegalAccessException,
         NoSuchMethodException, IllegalArgumentException, InvocationTargetException,
         CancelCommandException {
   Echoes.broadcast a = new Echoes.broadcast();
   when(fakePlayer.getServer()).thenReturn(fakeServer);
   CommandHelperPlugin.myServer = fakeServer;
   a.exec(Target.UNKNOWN, env, C.onstruct("Hello World!"));
   verify(fakeServer).broadcastMessage("Hello World!");
 }
 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");
   }
 }
 public Construct exec(Target t, Env environment, Construct... args)
     throws ConfigRuntimeException {
   MCLocation l;
   MCPlayer p;
   p = environment.GetPlayer();
   MCWorld w = (p != null ? p.getWorld() : null);
   l = ObjectGenerator.GetGenerator().location(args[0], w, t);
   if (l.getWorld() instanceof CraftWorld) {
     CraftWorld cw = (CraftWorld) l.getWorld();
     net.minecraft.server.Block.byId[l.getBlock().getTypeId()].dropNaturally(
         cw.getHandle(),
         l.getBlockX(),
         l.getBlockY(),
         l.getBlockZ(),
         l.getBlock().getData(),
         1.0f,
         0);
   }
   l.getBlock().setTypeId(0);
   CraftServer cs = (CraftServer) ((BukkitMCServer) Static.getServer()).__Server();
   cs.getHandle().a(new Packet0KeepAlive(), 0);
   return new CVoid(t);
 }
    public void compileMSA(List<Script> scripts, MCPlayer player) {

      for (FileInfo fi : msa) {
        List<Script> tempScripts;
        try {
          tempScripts =
              MethodScriptCompiler.preprocess(
                  MethodScriptCompiler.lex(fi.contents, fi.file, false));
          for (Script s : tempScripts) {
            try {
              try {
                s.compile();
                s.checkAmbiguous((ArrayList<Script>) scripts);
                scripts.add(s);
              } catch (ConfigCompileException e) {
                ConfigRuntimeException.React(
                    e,
                    "Compile error in script. Compilation will attempt to continue, however.",
                    player);
              }
            } catch (RuntimeException ee) {
              throw new RuntimeException(
                  "While processing a script, "
                      + "("
                      + fi.file()
                      + ") an unexpected exception occurred. (No further information"
                      + " is available, unfortunately.)",
                  ee);
            }
          }
        } catch (ConfigCompileException e) {
          ConfigRuntimeException.React(
              e, "Could not compile file " + fi.file + " compilation will halt.", player);
          return;
        }
      }
      int errors = 0;
      for (Script s : scripts) {
        if (s.compilerError) {
          errors++;
        }
      }
      if (errors > 0) {
        System.out.println(
            TermColors.YELLOW
                + "[CommandHelper]: "
                + (scripts.size() - errors)
                + " alias(es) defined, "
                + TermColors.RED
                + "with "
                + errors
                + " aliases with compile errors."
                + TermColors.reset());
        if (player != null) {
          player.sendMessage(
              MCChatColor.YELLOW
                  + "[CommandHelper]: "
                  + (scripts.size() - errors)
                  + " alias(es) defined, "
                  + MCChatColor.RED
                  + "with "
                  + errors
                  + " aliases with compile errors.");
        }
      } else {
        System.out.println(
            TermColors.YELLOW
                + "[CommandHelper]: "
                + scripts.size()
                + " alias(es) defined."
                + TermColors.reset());
        if (player != null) {
          player.sendMessage(
              MCChatColor.YELLOW + "[CommandHelper]: " + scripts.size() + " alias(es) defined.");
        }
      }
    }
  /**
   * 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();
  }