public void onEnable() {
    if (Common.VERSION < 139) {
      getLogger().info("BKCommonLib outdated!");
      getServer().getPluginManager().disablePlugin(this);
      return;
    } else if (Common.VERSION > 139)
      getLogger().info("WARNING: BKCommonLib to new. Things may be broken!");

    config = new Config(this);

    // Register events
    Server s = getServer();
    PluginManager pm = s.getPluginManager();
    pm.registerEvents(new PortalStickPlayerListener(this), this);
    pm.registerEvents(new PortalStickBlockListener(this), this);
    pm.registerEvents(new PortalStickVehicleListener(this), this);
    pm.registerEvents(eL, this);

    worldGuard = (WorldGuardPlugin) pm.getPlugin("WorldGuard");

    config.load();
    i18n = new I18n(this, getFile());

    // Teleport all entities.
    s.getScheduler().scheduleSyncRepeatingTask(this, entityManager, 1L, 1L);
    // Garbage-collect the users drop lists.
    s.getScheduler().scheduleSyncRepeatingTask(this, userManager, 600L, 600L);

    // Register commands
    ArrayList<BaseCommand> tmpList = new ArrayList<BaseCommand>();
    tmpList.add(new RegionToolCommand(this));
    tmpList.add(new SetRegionCommand(this));
    tmpList.add(new ReloadCommand(this));
    tmpList.add(new DeleteAllCommand(this));
    tmpList.add(new DeleteCommand(this));
    tmpList.add(new HelpCommand(this));
    tmpList.add(new RegionListCommand(this));
    tmpList.add(new DeleteRegionCommand(this));
    tmpList.add(new FlagCommand(this));
    tmpList.add(new RegionInfoCommand(this));
    tmpList.add(new LanguageCommand(this));
    commands = tmpList.toArray(new BaseCommand[0]);
  }
  /**
   * Create a new packet filter manager.
   *
   * @return A new packet filter manager.
   */
  public InternalManager build() {
    if (reporter == null) throw new IllegalArgumentException("reporter cannot be NULL.");
    if (classLoader == null) throw new IllegalArgumentException("classLoader cannot be NULL.");

    asyncManager = new AsyncFilterManager(reporter, server.getScheduler());
    nettyEnabled = false;

    // Spigot
    if (SpigotPacketInjector.canUseSpigotListener()) {
      // If the server hasn't loaded yet - wait
      if (InjectedServerConnection.getServerConnection(reporter, server) == null) {
        // We need to delay this until we know if Netty is enabled
        final DelayedPacketManager delayed = new DelayedPacketManager(reporter, mcVersion);

        // They must reference each other
        delayed.setAsynchronousManager(asyncManager);
        asyncManager.setManager(delayed);

        Futures.addCallback(
            BukkitFutures.nextEvent(library, WorldInitEvent.class),
            new FutureCallback<WorldInitEvent>() {
              @Override
              public void onSuccess(WorldInitEvent event) {
                // Nevermind
                if (delayed.isClosed()) return;

                try {
                  registerSpigot(delayed);
                } catch (Exception e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable error) {
                reporter.reportWarning(
                    PacketFilterBuilder.this,
                    Report.newBuilder(REPORT_TEMPORARY_EVENT_ERROR).error(error));
              }
            });

        System.out.println("Delaying due to Spigot");

        // Let plugins use this version instead
        return delayed;
      } else {
        nettyEnabled =
            !MinecraftReflection.isMinecraftObject(
                InjectedServerConnection.getServerConnection(reporter, server));
      }
    }

    // Otherwise - construct the packet filter manager right away
    return buildInternal();
  }
 @Override
 public void onDisable() {
   server.getScheduler().cancelTasks(this);
   send("Tasks cancelled");
   try {
     sql.close();
   } catch (SQLException e) {
     sendErr("Could not close SQL connection");
   } catch (NullPointerException e) {
     sendErr("SQL is null. Connection doesn't exist");
   }
   send("SQL connection closed");
   cm = null;
   send("is now disabled.");
 }
  public void disablePlugin(final Plugin plugin) {
    if (plugin.isEnabled()) {
      try {
        plugin.getPluginLoader().disablePlugin(plugin);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred (in the plugin loader) while disabling "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?)",
                ex);
      }

      try {
        server.getScheduler().cancelTasks(plugin);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred (in the plugin loader) while cancelling tasks for "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?)",
                ex);
      }

      try {
        server.getServicesManager().unregisterAll(plugin);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred (in the plugin loader) while unregistering services for "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?)",
                ex);
      }

      try {
        HandlerList.unregisterAll(plugin);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred (in the plugin loader) while unregistering events for "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?)",
                ex);
      }

      try {
        server.getMessenger().unregisterIncomingPluginChannel(plugin);
        server.getMessenger().unregisterOutgoingPluginChannel(plugin);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred (in the plugin loader) while unregistering plugin channels for "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?)",
                ex);
      }
    }
  }
  @Override
  public boolean onCommand(
      CommandSender sender, Command command, String commandLabel, String[] args) {
    // Event handling
    CouponCodesCommandEvent ev =
        EventHandle.callCouponCodesCommandEvent(sender, command, commandLabel, args);
    if (ev.isCancelled()) return true;
    sender = ev.getSender();
    command = ev.getCommand();
    commandLabel = ev.getCommandLabel();
    args = ev.getArgs();

    if (args.length == 0) {
      help(sender);
      return true;
    }

    boolean pl = false;
    if (sender instanceof Player) pl = true;

    // Add command 2.0
    if (args[0].equalsIgnoreCase("add")) {
      if (args.length < 2) {
        helpAdd(sender);
        return true;
      }
      if (has(sender, "cc.add")) {
        server
            .getScheduler()
            .scheduleAsyncDelayedTask(this, new QuedAddCommand(this, sender, args));
        return true;
      } else {
        sender.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
        return true;
      }
    }

    // Remove command
    else if (args[0].equalsIgnoreCase("remove")) {
      if (has(sender, "cc.remove")) {
        server.getScheduler().scheduleAsyncDelayedTask(this, new QuedRemoveCommand(sender, args));
        return true;
      } else {
        sender.sendMessage(ChatColor.RED + "You do not have permission to use this command");
        return true;
      }
    }

    // Redeem command
    else if (args[0].equalsIgnoreCase("redeem")) {
      if (!pl) {
        sender.sendMessage("You must be a player to redeem a coupon");
        return true;
      } else {
        Player player = (Player) sender;
        if (has(player, "cc.redeem")) {
          server
              .getScheduler()
              .scheduleAsyncDelayedTask(this, new QuedRedeemCommand(this, player, args));
          return true;
        } else {
          player.sendMessage(ChatColor.RED + "You do not have permission to use this command");
          return true;
        }
      }
    }

    // List command
    else if (args[0].equalsIgnoreCase("list")) {
      if (has(sender, "cc.list")) {
        server.getScheduler().scheduleAsyncDelayedTask(this, new QuedListCommand(sender));
        return true;
      } else {
        sender.sendMessage(ChatColor.RED + "You do not have permission to use this command");
        return true;
      }
    }

    // Info command
    else if (args[0].equalsIgnoreCase("info")) {
      if (has(sender, "cc.info")) {
        server
            .getScheduler()
            .scheduleAsyncDelayedTask(this, new QuedInfoCommand(this, sender, args));
        return true;
      } else {
        sender.sendMessage(ChatColor.RED + "You do not have permission to use this command");
        return true;
      }
    }

    // Reload command
    else if (args[0].equalsIgnoreCase("reload")) {
      if (has(sender, "cc.reload")) {
        if (!sql.reload()) sender.sendMessage(ChatColor.DARK_RED + "Could not reload the database");
        else sender.sendMessage(ChatColor.GREEN + "Database reloaded");
        reloadConfig();
        config = new Config(this);
        debug = config.getDebug();
        sender.sendMessage(ChatColor.GREEN + "Config reloaded");
        return true;
      } else {
        sender.sendMessage(ChatColor.RED + "You do not have permission to use this command");
        return true;
      }
    } else {
      help(sender);
      return true;
    }
  }
 @Override
 public BukkitScheduler getScheduler() {
   return server.getScheduler();
 }
Exemple #7
0
 public LevitateAction(Plugin plugin) {
   this.plugin = plugin;
   this.server = plugin.getServer();
   this.scheduler = server.getScheduler();
 }
  public boolean setUp() {
    try {
      FileUtils.deleteFolder(invDirectory);
      FileUtils.deleteFolder(serverDirectory);
      invDirectory.mkdirs();
      Assert.assertTrue(invDirectory.exists());

      MockGateway.MOCK_STANDARD_METHODS = false;

      plugin = PowerMockito.spy(new MultiverseInventories());
      core = PowerMockito.spy(new MultiverseCore());

      // Let's let all MV files go to bin/test
      doReturn(invDirectory).when(plugin).getDataFolder();
      // Let's let all MV files go to bin/test
      doReturn(coreDirectory).when(core).getDataFolder();

      // Return a fake PDF file.
      PluginDescriptionFile pdf =
          PowerMockito.spy(
              new PluginDescriptionFile(
                  "Multiverse-Inventories",
                  "2.4-test",
                  "com.onarandombox.multiverseinventories.MultiverseInventories"));
      when(pdf.getAuthors()).thenReturn(new ArrayList<String>());
      doReturn(pdf).when(plugin).getDescription();
      doReturn(core).when(plugin).getCore();
      doReturn(true).when(plugin).isEnabled();
      PluginDescriptionFile pdfCore =
          PowerMockito.spy(
              new PluginDescriptionFile(
                  "Multiverse-Core", "2.2-Test", "com.onarandombox.MultiverseCore.MultiverseCore"));
      when(pdfCore.getAuthors()).thenReturn(new ArrayList<String>());
      doReturn(pdfCore).when(core).getDescription();
      doReturn(true).when(core).isEnabled();
      plugin.setServerFolder(serverDirectory);

      // Add Core to the list of loaded plugins
      JavaPlugin[] plugins = new JavaPlugin[] {plugin, core};

      // Mock the Plugin Manager
      PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
      when(mockPluginManager.getPlugins()).thenReturn(plugins);
      when(mockPluginManager.getPlugin("Multiverse-Inventories")).thenReturn(plugin);
      when(mockPluginManager.getPlugin("Multiverse-Core")).thenReturn(core);
      when(mockPluginManager.getPermission(anyString())).thenReturn(null);

      // Make some fake folders to fool the fake MV into thinking these worlds exist
      File worldNormalFile = new File(plugin.getServerFolder(), "world");
      Util.log("Creating world-folder: " + worldNormalFile.getAbsolutePath());
      worldNormalFile.mkdirs();
      MockWorldFactory.makeNewMockWorld("world", Environment.NORMAL, WorldType.NORMAL);
      File worldNetherFile = new File(plugin.getServerFolder(), "world_nether");
      Util.log("Creating world-folder: " + worldNetherFile.getAbsolutePath());
      worldNetherFile.mkdirs();
      MockWorldFactory.makeNewMockWorld("world_nether", Environment.NETHER, WorldType.NORMAL);
      File worldSkylandsFile = new File(plugin.getServerFolder(), "world_the_end");
      Util.log("Creating world-folder: " + worldSkylandsFile.getAbsolutePath());
      worldSkylandsFile.mkdirs();
      MockWorldFactory.makeNewMockWorld("world_the_end", Environment.THE_END, WorldType.NORMAL);
      File world2File = new File(plugin.getServerFolder(), "world2");
      Util.log("Creating world-folder: " + world2File.getAbsolutePath());
      world2File.mkdirs();
      MockWorldFactory.makeNewMockWorld("world2", Environment.NORMAL, WorldType.NORMAL);

      // Initialize the Mock server.
      mockServer = mock(Server.class);
      when(mockServer.getName()).thenReturn("TestBukkit");
      Logger.getLogger("Minecraft").setParent(Util.logger);
      when(mockServer.getLogger()).thenReturn(Util.logger);
      when(mockServer.getWorldContainer()).thenReturn(worldsDirectory);
      when(plugin.getServer()).thenReturn(mockServer);
      when(core.getServer()).thenReturn(mockServer);
      when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
      Answer<Player> playerAnswer =
          new Answer<Player>() {
            public Player answer(InvocationOnMock invocation) throws Throwable {
              String arg;
              try {
                arg = (String) invocation.getArguments()[0];
              } catch (Exception e) {
                return null;
              }
              Player player = players.get(arg);
              if (player == null) {
                player = new MockPlayer(arg, mockServer);
                players.put(arg, player);
              }
              return player;
            }
          };
      when(mockServer.getPlayer(anyString())).thenAnswer(playerAnswer);
      when(mockServer.getOfflinePlayer(anyString())).thenAnswer(playerAnswer);
      when(mockServer.getOfflinePlayers())
          .thenAnswer(
              new Answer<OfflinePlayer[]>() {
                public OfflinePlayer[] answer(InvocationOnMock invocation) throws Throwable {
                  return players.values().toArray(new Player[players.values().size()]);
                }
              });
      when(mockServer.getOnlinePlayers())
          .thenAnswer(
              new Answer<Player[]>() {
                public Player[] answer(InvocationOnMock invocation) throws Throwable {
                  return players.values().toArray(new Player[players.values().size()]);
                }
              });

      // Give the server some worlds
      when(mockServer.getWorld(anyString()))
          .thenAnswer(
              new Answer<World>() {
                public World answer(InvocationOnMock invocation) throws Throwable {
                  String arg;
                  try {
                    arg = (String) invocation.getArguments()[0];
                  } catch (Exception e) {
                    return null;
                  }
                  return MockWorldFactory.getWorld(arg);
                }
              });

      when(mockServer.getWorld(any(UUID.class)))
          .thenAnswer(
              new Answer<World>() {
                @Override
                public World answer(InvocationOnMock invocation) throws Throwable {
                  UUID arg;
                  try {
                    arg = (UUID) invocation.getArguments()[0];
                  } catch (Exception e) {
                    return null;
                  }
                  return MockWorldFactory.getWorld(arg);
                }
              });

      when(mockServer.getWorlds())
          .thenAnswer(
              new Answer<List<World>>() {
                public List<World> answer(InvocationOnMock invocation) throws Throwable {
                  return MockWorldFactory.getWorlds();
                }
              });

      when(mockServer.createWorld(Matchers.isA(WorldCreator.class)))
          .thenAnswer(
              new Answer<World>() {
                public World answer(InvocationOnMock invocation) throws Throwable {
                  WorldCreator arg;
                  try {
                    arg = (WorldCreator) invocation.getArguments()[0];
                  } catch (Exception e) {
                    return null;
                  }
                  // Add special case for creating null worlds.
                  // Not sure I like doing it this way, but this is a special case
                  if (arg.name().equalsIgnoreCase("nullworld")) {
                    return MockWorldFactory.makeNewNullMockWorld(
                        arg.name(), arg.environment(), arg.type());
                  }
                  return MockWorldFactory.makeNewMockWorld(
                      arg.name(), arg.environment(), arg.type());
                }
              });

      when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true);

      // add mock scheduler
      BukkitScheduler mockScheduler = mock(BukkitScheduler.class);
      when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong()))
          .thenAnswer(
              new Answer<Integer>() {
                public Integer answer(InvocationOnMock invocation) throws Throwable {
                  Runnable arg;
                  try {
                    arg = (Runnable) invocation.getArguments()[1];
                  } catch (Exception e) {
                    return null;
                  }
                  arg.run();
                  return null;
                }
              });
      when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class)))
          .thenAnswer(
              new Answer<Integer>() {
                public Integer answer(InvocationOnMock invocation) throws Throwable {
                  Runnable arg;
                  try {
                    arg = (Runnable) invocation.getArguments()[1];
                  } catch (Exception e) {
                    return null;
                  }
                  arg.run();
                  return null;
                }
              });
      when(mockServer.getScheduler()).thenReturn(mockScheduler);

      // Set InventoriesListener
      InventoriesListener il = PowerMockito.spy(new InventoriesListener(plugin));
      Field inventoriesListenerField =
          MultiverseInventories.class.getDeclaredField("inventoriesListener");
      inventoriesListenerField.setAccessible(true);
      inventoriesListenerField.set(plugin, il);

      // Set Core
      Field coreField = MultiverseInventories.class.getDeclaredField("core");
      coreField.setAccessible(true);
      coreField.set(plugin, core);

      // Set server
      Field serverfield = JavaPlugin.class.getDeclaredField("server");
      serverfield.setAccessible(true);
      serverfield.set(plugin, mockServer);

      // Set worldManager
      WorldManager wm = PowerMockito.spy(new WorldManager(core));
      Field worldmanagerfield = MultiverseCore.class.getDeclaredField("worldManager");
      worldmanagerfield.setAccessible(true);
      worldmanagerfield.set(core, wm);

      // Set playerListener
      MVPlayerListener pl = PowerMockito.spy(new MVPlayerListener(core));
      Field playerlistenerfield = MultiverseCore.class.getDeclaredField("playerListener");
      playerlistenerfield.setAccessible(true);
      playerlistenerfield.set(core, pl);

      // Set entityListener
      MVEntityListener el = PowerMockito.spy(new MVEntityListener(core));
      Field entitylistenerfield = MultiverseCore.class.getDeclaredField("entityListener");
      entitylistenerfield.setAccessible(true);
      entitylistenerfield.set(core, el);

      // Set weatherListener
      MVWeatherListener wl = PowerMockito.spy(new MVWeatherListener(core));
      Field weatherlistenerfield = MultiverseCore.class.getDeclaredField("weatherListener");
      weatherlistenerfield.setAccessible(true);
      weatherlistenerfield.set(core, wl);

      // Init our command sender
      final Logger commandSenderLogger = Logger.getLogger("CommandSender");
      commandSenderLogger.setParent(Util.logger);
      commandSender = mock(CommandSender.class);
      doAnswer(
              new Answer<Void>() {
                public Void answer(InvocationOnMock invocation) throws Throwable {
                  commandSenderLogger.info(
                      ChatColor.stripColor((String) invocation.getArguments()[0]));
                  return null;
                }
              })
          .when(commandSender)
          .sendMessage(anyString());
      when(commandSender.getServer()).thenReturn(mockServer);
      when(commandSender.getName()).thenReturn("MockCommandSender");
      when(commandSender.isPermissionSet(anyString())).thenReturn(true);
      when(commandSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
      when(commandSender.hasPermission(anyString())).thenReturn(true);
      when(commandSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
      when(commandSender.addAttachment(plugin)).thenReturn(null);
      when(commandSender.isOp()).thenReturn(true);

      Bukkit.setServer(mockServer);

      // Load Multiverse Core
      core.onLoad();
      plugin.onLoad();

      // Enable it.
      core.onEnable();
      plugin.onEnable();

      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }