Ejemplo n.º 1
0
 @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;
 }
 @EventHandler(priority = EventPriority.LOWEST)
 public void onPlayerRespawn(PlayerRespawnEvent event) {
   EventUtils.TriggerListener(
       Driver.PLAYER_SPAWN,
       "player_spawn",
       new BukkitPlayerEvents.BukkitMCPlayerRespawnEvent(event));
 }
 @EventHandler(priority = EventPriority.LOWEST)
 public void onPlayerInteract(PlayerInteractEvent e) {
   EventUtils.TriggerListener(
       Driver.PLAYER_INTERACT,
       "player_interact",
       new BukkitPlayerEvents.BukkitMCPlayerInteractEvent(e));
 }
 @EventHandler(priority = EventPriority.LOWEST)
 public void onPlayerPreLogin(PlayerPreLoginEvent e) {
   EventUtils.TriggerListener(
       Driver.PLAYER_PRELOGIN,
       "player_prelogin",
       new BukkitPlayerEvents.BukkitMCPlayerPreLoginEvent(e));
 }
Ejemplo n.º 5
0
 @Override
 public void link(Target t, List<ParseTree> children) throws ConfigCompileException {
   String name = children.get(0).getData().val();
   try {
     EventUtils.verifyEventName(name);
   } catch (IllegalArgumentException ex) {
     throw new ConfigCompileException(ex.getMessage(), t);
   }
 }
 @EventHandler(priority = EventPriority.LOWEST)
 public void onPlayerTeleport(PlayerTeleportEvent event) {
   if (!event.getFrom().getWorld().equals(event.getTo().getWorld())) {
     EventUtils.TriggerListener(
         Driver.WORLD_CHANGED,
         "world_changed",
         new BukkitPlayerEvents.BukkitMCWorldChangedEvent(
             new PlayerChangedWorldEvent(event.getPlayer(), event.getFrom().getWorld())));
   }
 }
 @EventHandler(priority = EventPriority.LOWEST)
 public void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
   BukkitMCPlayer currentPlayer =
       (BukkitMCPlayer) Static.GetPlayer(event.getPlayer().getName(), Target.UNKNOWN);
   // Apparently this happens sometimes, so prevent it
   if (!event.getFrom().equals(currentPlayer._Player().getWorld())) {
     EventUtils.TriggerListener(
         Driver.WORLD_CHANGED,
         "world_changed",
         new BukkitPlayerEvents.BukkitMCWorldChangedEvent(event));
   }
 }
Ejemplo n.º 8
0
 @Override
 public Construct exec(Target t, Environment environment, Construct... args)
     throws ConfigRuntimeException {
   String id = args[0].val();
   for (Driver d : Driver.values()) {
     Set<BoundEvent> events = EventUtils.GetEvents(d);
     if (events != null) {
       for (BoundEvent b : events) {
         if (b.getId().equals(id)) {
           return CBoolean.TRUE;
         }
       }
     }
   }
   return CBoolean.FALSE;
 }
Ejemplo n.º 9
0
 @Override
 public Construct exec(Target t, Environment environment, Construct... args)
     throws ConfigRuntimeException {
   CArray obj = null;
   if (args[1] instanceof CNull) {
     obj = new CArray(t);
   } else if (args[1] instanceof CArray) {
     obj = (CArray) args[1];
   } else {
     throw new ConfigRuntimeException(
         "The eventObject must be null, or an array", ExceptionType.CastException, t);
   }
   boolean serverWide = false;
   if (args.length == 3) {
     serverWide = Static.getBoolean(args[2]);
   }
   EventUtils.ManualTrigger(args[0].val(), obj, t, serverWide);
   return CVoid.VOID;
 }
Ejemplo n.º 10
0
 public void fireEvent(final String name, final BindableEvent evt) {
   EventUtils.TriggerListener(Driver.EXTENSION, name, evt);
 }
 @EventHandler(priority = EventPriority.LOWEST)
 public void onPlayerQuit(PlayerQuitEvent event) {
   EventUtils.TriggerListener(
       Driver.PLAYER_QUIT, "player_quit", new BukkitPlayerEvents.BukkitMCPlayerQuitEvent(event));
 }
Ejemplo n.º 12
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();
  }
Ejemplo n.º 13
0
 @Override
 public Construct exec(Target t, Environment env, Construct... args)
     throws ConfigRuntimeException {
   return EventUtils.DumpEvents();
 }
Ejemplo n.º 14
0
    @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;
    }