Example #1
0
  public static void main(String[] args) throws Exception {
    try {
      // Boilerplate startup stuff
      Implementation.setServerType(Implementation.Type.BUKKIT);
      ClassDiscovery.getDefaultInstance()
          .addDiscoveryLocation(ClassDiscovery.GetClassContainer(DocGen.class));
      ExtensionManager.Initialize(ClassDiscovery.getDefaultInstance());
      Installer.Install(CommandHelperFileLocations.getDefault().getConfigDirectory());
      Prefs.init(CommandHelperFileLocations.getDefault().getPreferencesFile());
      CHLog.initialize(CommandHelperFileLocations.getDefault().getConfigDirectory());

      // System.out.println(functions("wiki", api.Platforms.INTERPRETER_JAVA, true));
      System.out.println(examples("if", true));
      // System.exit(0);
      // events("wiki");
      // System.out.println(Template("persistence_network"));
    } catch (Throwable t) {
      t.printStackTrace();
      System.exit(1);
    } finally {
      System.exit(0);
    }
  }
  /**
   * 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();
  }