コード例 #1
0
  public boolean unloadChunks() {
    if (!this.world.savingDisabled) {
      // CraftBukkit start
      Server server = this.world.getServer();
      for (int i = 0; i < 50 && !this.unloadQueue.isEmpty(); i++) {
        long chunkcoordinates = this.unloadQueue.popFirst();
        Chunk chunk = this.chunks.get(chunkcoordinates);
        if (chunk == null) continue;

        ChunkUnloadEvent event = new ChunkUnloadEvent(chunk.bukkitChunk);
        server.getPluginManager().callEvent(event);
        if (!event.isCancelled()) {
          chunk.removeEntities();
          this.saveChunk(chunk);
          this.saveChunkNOP(chunk);
          // this.unloadQueue.remove(integer);
          this.chunks.remove(chunkcoordinates); // CraftBukkit
          this.chunkList.remove(chunk);
        }
      }
      // CraftBukkit end

      if (this.e != null) {
        this.e.a();
      }
    }

    return this.chunkProvider.unloadChunks();
  }
コード例 #2
0
ファイル: Backup.java プロジェクト: EderHD/Essentials
	@Override
	public void run()
	{
		if (!active.compareAndSet(false, true))
		{
			return;
		}

		final ISettings settings = ess.getSettings();

		final net.ess3.settings.Backup backupSettings = settings.getData().getGeneral().getBackup();

		String backupCommand = backupSettings.getCommand() == null || backupSettings.getCommand().isEmpty() ? ("NORUN") : backupSettings.getCommand();
		
		/*if (backupCommand.equals("NORUN")) { TODO: Un-comment if you do not want commands to be run if there is no backup command
			return;
		}*/

		ess.getLogger().log(Level.INFO, _("backupStarted"));

		if (!backupSettings.getCommandsBeforeBackup().isEmpty())
		{
			final CommandSender consoleSender = server.getConsoleSender();
			for (String command : backupSettings.getCommandsBeforeBackup())
			{
				server.dispatchCommand(consoleSender, command);
			}
		}

		ess.getPlugin().scheduleAsyncDelayedTask(new BackupRunner(backupCommand));
	}
コード例 #3
0
 public void changeWorld(Player player, String fromWorld, String toWorld) {
   Location location = new Location(mockServer.getWorld(toWorld), 0.0, 70.0, 0.0);
   player.teleport(location);
   Assert.assertEquals(location, player.getLocation());
   listener.playerChangedWorld(
       new PlayerChangedWorldEvent(player, mockServer.getWorld(fromWorld)));
 }
コード例 #4
0
 public final synchronized void addPlayer(String player) {
   if (player == null) {
     return;
   }
   if (players.size()
       >= PartyMan.getPartyMan().getConfiguration().getInt("partyman.max-members", 3)) {
     sendPartyMessage("Maximum member limit reached!");
     sendPlayerMessage(player, "Maximum member limit reached!");
     return;
   }
   if (!this.players.contains(player)) {
     sendPartyMessage(getColoredName(player) + " joined the party.");
     sendPlayerMessage(
         player,
         colorizeMessage(
             getPartyMessagePrefix() + " you joined the party. " + getPartyMessageSuffix()));
     server.dispatchCommand(
         server.getConsoleSender(), "pex group " + pexgroup + " user add " + player);
     this.players.add(player);
     Boolean chatMode =
         PartyMan.getPartyMan().getSavedParties().getBoolean("players." + player + ".chat");
     if (chatMode == null) {
       chatMode = false;
     }
     PartyMan.getPartyMan().getSavedParties().createSection("players." + player);
     PartyMan.getPartyMan().getSavedParties().set("players." + player + ".party", this.name);
     PartyMan.getPartyMan().getPartyManager().setPartyChatMode(player, chatMode);
     PartyMan.getPartyMan().saveConfigs();
   }
 }
コード例 #5
0
  public void enablePlugin(final Plugin plugin) {
    if (!(plugin instanceof JavaPlugin)) {
      throw new IllegalArgumentException("Plugin is not associated with this PluginLoader");
    }

    if (!plugin.isEnabled()) {
      JavaPlugin jPlugin = (JavaPlugin) plugin;

      String pluginName = jPlugin.getDescription().getName();

      if (!loaders.containsKey(pluginName)) {
        loaders.put(pluginName, (PluginClassLoader) jPlugin.getClassLoader());
      }

      try {
        jPlugin.setEnabled(true);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred while enabling "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?): "
                    + ex.getMessage(),
                ex);
      }

      // Perhaps abort here, rather than continue going, but as it stands,
      // an abort is not possible the way it's currently written
      server.getPluginManager().callEvent(new PluginEnableEvent(plugin));
    }
  }
コード例 #6
0
  /**
   * Attempt to load the MCPC remapper.
   *
   * @return TRUE if we succeeded, FALSE otherwise.
   * @throws RemapperUnavaibleException If the remapper is not present.
   */
  public RemappedClassSource initialize() {
    try {
      Server server = Bukkit.getServer();
      if (server == null) {
        throw new IllegalStateException("Bukkit not initialized.");
      }

      String version = server.getVersion();
      if (!version.contains("MCPC") && !version.contains("Cauldron")) {
        throw new RemapperUnavaibleException(Reason.MCPC_NOT_PRESENT);
      }

      // Obtain the Class remapper used by MCPC+/Cauldron
      this.classRemapper = FieldUtils.readField(getClass().getClassLoader(), "remapper", true);

      if (this.classRemapper == null) {
        throw new RemapperUnavaibleException(Reason.REMAPPER_DISABLED);
      }

      // Initialize some fields and methods used by the Jar Remapper
      Class<?> renamerClazz = classRemapper.getClass();

      this.mapType =
          MethodUtils.getAccessibleMethod(renamerClazz, "map", new Class<?>[] {String.class});

      return this;

    } catch (RemapperUnavaibleException e) {
      throw e;
    } catch (Exception e) {
      // Damn it
      throw new RuntimeException("Cannot access MCPC remapper.", e);
    }
  }
コード例 #7
0
  @Override
  public void run(Server server, CommandSender sender, String commandLabel, String[] args)
      throws Exception {
    if (args.length < 1) {
      throw new NotEnoughArgumentsException();
    }

    if (server.matchPlayer(args[0]).isEmpty()) {
      ((CraftServer) server).getHandle().a(args[0]);
      sender.sendMessage(Util.format("playerBanned", args[0]));
    } else {
      final User player = ess.getUser(server.matchPlayer(args[0]).get(0));
      String banReason;
      if (args.length > 1) {
        banReason = getFinalArg(args, 1);
        player.setBanReason(commandLabel);
      } else {
        banReason = Util.i18n("defaultBanReason");
      }
      player.kickPlayer(banReason);
      ((CraftServer) server).getHandle().a(player.getName());
      sender.sendMessage(Util.format("playerBanned", player.getName()));
    }
    ess.loadBanList();
  }
コード例 #8
0
  @Override
  public void run(Server server, CommandSender sender, String commandLabel, String[] args)
      throws Exception {

    User user = null;
    if (sender instanceof Player) {
      user = ess.getUser(((Player) sender));
    }
    if (args.length < 1 & user != null) {
      user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation());
      return;
    }

    if (server.matchPlayer(args[0]).isEmpty()) {
      throw new Exception(Util.i18n("playerNotFound"));
    }

    for (Player p : server.matchPlayer(args[0])) {
      sender.sendMessage(Util.format("lightningUse", p.getDisplayName()));
      p.getWorld().strikeLightning(p.getLocation());
      if (!ess.getUser(p).isGodModeEnabled()) {
        p.setHealth(p.getHealth() < 5 ? 0 : p.getHealth() - 5);
      }
      if (ess.getSettings().warnOnSmite()) {
        p.sendMessage(Util.i18n("lightningSmited"));
      }
    }
  }
コード例 #9
0
  public void startLobby() {
    server.broadcastMessage(GOLD + "[ServerGames]" + GREEN + " Countdown started.");

    clearAll();

    bets.clear();
    this.clearEnt();
    load();
    tpAll(waiting);
    ServerGames.current = worlds.get(new Random().nextInt(ServerGames.worlds.size()));

    for (Player p : server.getOnlinePlayers()) {
      showAllFor(p);
      showPlayer(p);

      if (isTribute(p) || isSpectator(p)) clearItems(p);
    }

    loaded.clear();

    this.resetPlayers();

    state = State.LOBBY;
    game = new Lobby(this);

    startTimer();
  }
コード例 #10
0
  @Before
  public void setUp() throws Exception {
    // create our fake-stuff
    database = mock(EbeanServer.class);
    factory = new TamedEndermanDefaultFactory(database);

    Server mockServer = mock(Server.class);
    when(mockServer.getOfflinePlayer(anyString()))
        .thenAnswer(
            new Answer<OfflinePlayer>() {
              public OfflinePlayer answer(InvocationOnMock invocation) throws Throwable {
                OfflinePlayer op = mock(OfflinePlayer.class);
                when(op.getName()).thenReturn((String) invocation.getArguments()[0]);
                return op;
              }
            });

    TameEnder plugin = PowerMockito.mock(TameEnder.class); // we want to mock some final methods
    // FileConfiguration fakeConfig = mock(FileConfiguration.class);
    // PluginManager fakePluginManager = mock(PluginManager.class);

    TameEnder.setInstance(plugin);
    when(plugin.getServer()).thenReturn(mockServer);
    when(plugin.getDatabase()).thenReturn(database);
    // when(plugin.getConfig()).thenReturn(fakeConfig);
    // when(mockServer.getPluginManager()).thenReturn(fakePluginManager);
  }
コード例 #11
0
  public static void initialize(Server server) {
    Plugin permissionsEx = server.getPluginManager().getPlugin("PermissionsEx");
    Plugin groupManager = server.getPluginManager().getPlugin("GroupManager");
    Plugin permissions = server.getPluginManager().getPlugin("Permissions");

    if (permissionsEx != null) {
      permissionPlugin = permissionsEx;
      handler = PermissionHandler.PERMISSIONSEX;
      String version = permissionsEx.getDescription().getVersion();
      ButtonControlLogger.info("Permissions enabled using: PermissionsEx v" + version);
    } else if (groupManager != null) {
      permissionPlugin = groupManager;
      handler = PermissionHandler.GROUPMANAGER;
      String version = groupManager.getDescription().getVersion();
      ButtonControlLogger.info("Permissions enabled using: GroupManager v" + version);
    } else if (permissions != null) {
      permissionPlugin = permissions;
      handler = PermissionHandler.PERMISSIONS;
      String version = permissions.getDescription().getVersion();
      ButtonControlLogger.info("Permissions enabled using: Permissions v" + version);
    } else {
      handler = PermissionHandler.NONE;
      ButtonControlLogger.warning("A permission plugin isn't loaded.");
    }
  }
コード例 #12
0
ファイル: WarpPermissions.java プロジェクト: ZachBora/MyWarp
  public static void initialize(Server server) {
    Plugin permissionsEx = server.getPluginManager().getPlugin("PermissionsEx");
    Plugin groupManager = server.getPluginManager().getPlugin("GroupManager");
    Plugin permissions = server.getPluginManager().getPlugin("Permissions");

    if (permissionsEx != null) {
      permissionPlugin = permissionsEx;
      handler = PermissionHandler.PERMISSIONSEX;
      String version = permissionsEx.getDescription().getVersion();
      WarpLogger.info("Permissions enabled using: PermissionsEx v" + version);
    } else if (groupManager != null) {
      permissionPlugin = groupManager;
      handler = PermissionHandler.GROUPMANAGER;
      String version = groupManager.getDescription().getVersion();
      WarpLogger.info("Permissions enabled using: GroupManager v" + version);
    } else if (permissions != null) {
      permissionPlugin = permissions;
      String version = permissions.getDescription().getVersion();
      if (version.contains("3.")) {
        handler = PermissionHandler.PERMISSIONS3;
      } else {
        handler = PermissionHandler.PERMISSIONS;
      }
      WarpLogger.info("Permissions enabled using: Permissions v" + version);
    } else if (server.getPluginManager().getPermissions() != null) {
      handler = PermissionHandler.SUPERPERMS;
      WarpLogger.info("Permissions enabled using: SuperPerms");
    } else {
      handler = PermissionHandler.NONE;
      WarpLogger.warning("A permission plugin isn't loaded.");
    }
  }
コード例 #13
0
  @MatchEventHandler
  public void matchCompleted(MatchCompletedEvent event) {
    Match am = event.getMatch();
    MatchResult r = am.getResult();
    Matchup m = null;
    if (r.getVictors() != null && !r.getVictors().isEmpty()) {
      m = getMatchup(r.getVictors().iterator().next(), round);
    } else if (r.getLosers() != null && !r.getLosers().isEmpty()) {
      m = getMatchup(r.getLosers().iterator().next(), round);
    } else if (r.getDrawers() != null && !r.getDrawers().isEmpty()) {
      m = getMatchup(r.getDrawers().iterator().next(), round);
    }
    if (m == null) { // / This match wasnt in our tournament
      return;
    }
    if (am.getState() == MatchState.ONCANCEL) {
      endEvent();
      return;
    }
    Team victor = null;
    if (r.isDraw()) { // / match was a draw, pick a random lucky winner
      victor = pickRandomWinner(r, r.getDrawers());
    } else if (r.hasVictor() && r.getVictors().size() != 1) {
      victor = pickRandomWinner(r, r.getVictors());
    } else if (r.hasVictor()) {
      victor = r.getVictors().iterator().next(); // / single winner
    }
    m.setResult(r);
    for (Team t : r.getLosers()) {
      super.removeTeam(t);
    }
    aliveTeams.removeAll(r.getLosers());

    if (roundFinished()) {
      TimeUtil.testClock();
      if (Defaults.DEBUG) System.out.println("ROUND FINISHED !!!!!   " + aliveTeams);

      if (round + 1 == nrounds || isFinished()) {
        Server server = Bukkit.getServer();
        Team t = aliveTeams.get(0);
        server.broadcastMessage(
            Log.colorChat(
                eventParams.getPrefix()
                    + "&e Congratulations to &6"
                    + t.getDisplayName()
                    + "&e for winning!"));
        HashSet<Team> losers = new HashSet<Team>(competingTeams);
        losers.remove(victor);
        Set<Team> victors = new HashSet<Team>(Arrays.asList(victor));
        eventVictory(victors, losers);
        PerformTransition.transition(am, MatchState.FIRSTPLACE, t, false);
        PerformTransition.transition(am, MatchState.PARTICIPANTS, losers, false);
        eventCompleted();
      } else {
        makeNextRound();
        startRound();
      }
    }
  }
コード例 #14
0
 public boolean disablePlugin(String name) {
   try {
     Server.getPluginManager().disablePlugin(Server.getPluginManager().getPlugin(name));
     return true;
   } catch (NullPointerException e) {
     return false;
   }
 }
コード例 #15
0
  @Override
  public void startEvent() {
    super.startEvent();
    Server server = Bukkit.getServer();

    int osize = teams.size();
    nrounds = getNRounds(osize);
    int nteams = (int) Math.pow(2, nrounds);
    server.broadcastMessage(
        Log.colorChat(
            eventParams.getPrefix()
                + "&e The "
                + eventParams.toPrettyString()
                + oParms.getName()
                + " tournament is starting!"));

    preliminary_round = teams.size() != nteams;
    if (preliminary_round) nrounds++;

    TreeMap<Double, Team> sortTeams = new TreeMap<Double, Team>(Collections.reverseOrder());
    BTInterface bti = new BTInterface(eventParams);
    //		System.out.println("startEvent:: bti=" + bti);
    for (Team t : teams) {
      Double elo = Defaults.DEFAULT_ELO;
      if (bti.isValid()) {
        elo = (double) bti.getElo(t);
      }
      while (sortTeams.containsKey(elo)) {
        elo += 0.0001;
      }
      sortTeams.put(elo, t);
    }
    competingTeams.addAll(teams);
    teams.clear();
    aliveTeams.clear();
    ArrayList<Team> ts = new ArrayList<Team>(sortTeams.values());
    for (Team t : ts) {
      teams.add(t);
      aliveTeams.add(t);
    }
    server.broadcastMessage(
        Log.colorChat(
            eventParams.getPrefix()
                + "&6 "
                + teams.size()
                + " &e"
                + MessageUtil.getTeamsOrPlayers(teams.size())
                + " will compete in a &6"
                + nrounds
                + "&e round tournament"));
    if (preliminary_round) {
      makePreliminaryRound();
    } else {
      makeNextRound();
    }
    startRound();
  }
コード例 #16
0
 public synchronized void clearParty() {
   sendPartyMessage("Party is being disbanded.");
   for (String player : players) {
     PartyMan.getPartyMan().getSavedParties().set("players." + player.toLowerCase(), null);
   }
   this.players.clear();
   PartyMan.getPartyMan().getSavedParties().set("parties." + name, null);
   server.dispatchCommand(server.getConsoleSender(), "pex group " + pexgroup + " delete");
   PartyMan.getPartyMan().saveConfigs();
 }
コード例 #17
0
  public void loadWorldSettings() {
    if (Settings != null) {
      Settings.clear();
    } else {
      Settings = new HashMap();
    }

    for (int i = 0; i < server.getWorlds().size(); ++i) {
      getOrCreateSettings(((World) server.getWorlds().get(i)).getName());
    }
  }
コード例 #18
0
  @Override
  public void onEnable() {
    instance = this;
    server = getServer();
    config = new Config(this);
    debug = config.getDebug();
    version = getDescription().getVersion();
    usethread = config.getUseThread();

    try {
      mt = new Metrics();
    } catch (IOException e) {
      e.printStackTrace();
    }

    setUpdateInfo();

    if (!setupVault()) {
      send("Vault support is disabled. This option can be changed in the config.");
      va = false;
    } else {
      send("Vault support is enabled.");
      va = true;
    }

    if (!version.equals(newversion) && !version.contains("TEST"))
      send(
          "New update is available for CouponCodes! Current version: "
              + version
              + " New version: "
              + newversion);

    // This is for this plugin's own events!
    server.getPluginManager().registerEvents(new DebugListen(this), this);

    // Bukkit listeners
    server.getPluginManager().registerEvents(new PlayerListen(this), this);

    if (!setupSQL()) {
      send("Database could not be setup. CouponCodes will now disable");
      server.getPluginManager().disablePlugin(this);
      return;
    }

    // Timers!
    if (usethread) {
      getServer().getScheduler().scheduleAsyncRepeatingTask(this, new CouponTimer(), 200L, 200L);
    }

    // This timer is required, so it can't be in (usethread)!
    getServer().getScheduler().scheduleAsyncDelayedTask(this, new CustomDataSender(this, mt));

    send("is now enabled! Version: " + version);
  }
コード例 #19
0
  public void registerServerAliases() {
    Map<String, String[]> values = server.getCommandAliases();

    for (String alias : values.keySet()) {
      if (alias.contains(":") || alias.contains(" ")) {
        server
            .getLogger()
            .warning(
                "Could not register alias " + alias + " because it contains illegal characters");
        continue;
      }

      String[] commandStrings = values.get(alias);
      List<String> targets = new ArrayList<String>();
      StringBuilder bad = new StringBuilder();

      for (String commandString : commandStrings) {
        String[] commandArgs = commandString.split(" ");
        Command command = getCommand(commandArgs[0]);

        if (command == null) {
          if (bad.length() > 0) {
            bad.append(", ");
          }
          bad.append(commandString);
        } else {
          targets.add(commandString);
        }
      }

      if (bad.length() > 0) {
        server
            .getLogger()
            .warning(
                "Could not register alias "
                    + alias
                    + " because it contains commands that do not exist: "
                    + bad);
        continue;
      }

      // We register these as commands so they have absolute priority.
      if (targets.size() > 0) {
        knownCommands.put(
            alias.toLowerCase(),
            new FormattedCommandAlias(
                alias.toLowerCase(), targets.toArray(new String[targets.size()])));
      } else {
        knownCommands.remove(alias.toLowerCase());
      }
    }
  }
コード例 #20
0
 public Player getPlayer(final String partialname) throws PlayerNotFoundException {
   List<Player> matches = server.matchPlayer(partialname);
   if (matches.isEmpty()) {
     for (Player player : server.getOnlinePlayers()) {
       if (player.getDisplayName().toLowerCase().contains(partialname.toLowerCase())) {
         return player;
       }
     }
     throw new PlayerNotFoundException(partialname);
   } else {
     return matches.get(0);
   }
 }
コード例 #21
0
	@EventHandler(priority = EventPriority.HIGH)
	public void onPlayerLogin(final PlayerLoginEvent event)
	{
		switch (event.getResult())
		{
		case ALLOWED:
		case KICK_FULL:
		case KICK_BANNED:
			break;
		default:
			return;
		}

		userMap.addPrejoinedPlayer(event.getPlayer());
		final IUser user = userMap.getUser(event.getPlayer());
		userMap.removePrejoinedPlayer(event.getPlayer());
		user.getData().setNpc(false);

		final long currentTime = System.currentTimeMillis();
		final boolean banExpired = user.checkBanTimeout(currentTime);
		user.checkMuteTimeout(currentTime);
		user.checkJailTimeout(currentTime);

		if (!banExpired && (user.isBanned() || event.getResult() == Result.KICK_BANNED))
		{
			String banReason = user.getData().getBan().getReason();
			if (banReason == null || banReason.isEmpty() || banReason.equalsIgnoreCase("ban"))
			{
				banReason = _("The Ban Hammer has spoken!");
			}
			if (user.getData().getBan().getTimeout() > 0)
			{
				//TODO: TL This
				banReason += "\n\n" + "Expires in " + DateUtil.formatDateDiff(user.getData().getBan().getTimeout());
			}
			event.disallow(Result.KICK_BANNED, banReason);
			return;
		}

		if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !Permissions.JOINFULLSERVER.isAuthorized(user))
		{
			event.disallow(Result.KICK_FULL, _("Server is full!"));
			return;
		}
		event.allow();

		user.setTimestamp(TimestampType.LOGIN, System.currentTimeMillis());
		user.updateCompass();
		user.queueSave();
	}
コード例 #22
0
 public PartyInstance(PartyType type, String name, String abbr, String creator) {
   this.type = type;
   this.name = name;
   this.abbr = abbr;
   this.leader = creator;
   this.players = new ArrayList<String>();
   this.players.add(leader);
   this.server = PartyMan.getPartyMan().getServer();
   this.pvpEnabled = true;
   String parent = PartyMan.getPartyMan().getConfiguration().getString("partyman.parentgroup");
   pexgroup = parent + "_" + name.toLowerCase();
   String prefix = PartyMan.getPartyMan().getConfiguration().getString("partyman.group.prefix");
   String suffix = PartyMan.getPartyMan().getConfiguration().getString("partyman.group.suffix");
   server.dispatchCommand(server.getConsoleSender(), "pex group " + pexgroup + " create");
   server.dispatchCommand(
       server.getConsoleSender(), "pex group " + pexgroup + " parents set " + parent);
   server.dispatchCommand(
       server.getConsoleSender(), "pex group " + pexgroup + " prefix " + prefix + abbr + suffix);
   server.dispatchCommand(
       server.getConsoleSender(), "pex group " + pexgroup + " user add " + leader);
   sendPlayerMessage(leader, "Party created. Start inviting others!");
   PartyMan.getPartyMan().getSavedParties().createSection("parties." + name);
   PartyMan.getPartyMan().getSavedParties().set("parties." + name + ".abbr", abbr);
   PartyMan.getPartyMan().getSavedParties().set("parties." + name + ".leader", leader);
   Boolean chatMode =
       PartyMan.getPartyMan().getSavedParties().getBoolean("players." + leader + ".chat");
   if (chatMode == null) {
     chatMode = false;
   }
   PartyMan.getPartyMan().getSavedParties().createSection("players." + leader);
   PartyMan.getPartyMan().getSavedParties().set("players." + leader + ".party", this.name);
   PartyMan.getPartyMan().getPartyManager().setPartyChatMode(leader, chatMode);
   PartyMan.getPartyMan().saveConfigs();
 }
コード例 #23
0
	/**
	 * Used to parse an argument of the type "users(s) selector"
	 */
	private Set<User> getUsers(final Server server, final CommandSender sender, final String selector) throws Exception
	{
		final Set<User> users = new TreeSet<User>(new UserNameComparator());
		// If there is no selector we want the sender itself. Or all users if sender isn't a user.
		if (selector == null)
		{
			final User user = ess.getUser(sender);
			if (user == null)
			{
				for (Player player : server.getOnlinePlayers())
				{
					users.add(ess.getUser(player));
				}
			}
			else
			{
				users.add(user);
			}
			return users;
		}

		// Try to find the user with name = selector
		User user = null;
		final List<Player> matchedPlayers = server.matchPlayer(selector);
		if (!matchedPlayers.isEmpty())
		{
			user = ess.getUser(matchedPlayers.get(0));
		}

		if (user != null)
		{
			users.add(user);
		}
		// If that fails, Is the argument something like "*" or "all"?
		else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all"))
		{
			for (Player player : server.getOnlinePlayers())
			{
				users.add(ess.getUser(player));
			}
		}
		// We failed to understand the world target...
		else
		{
			throw new Exception(_("playerNotFound"));
		}

		return users;
	}
コード例 #24
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{

		User user = null;
		if (sender instanceof Player)
		{
			user = ess.getUser(((Player)sender));
			if ((args.length < 1 || user != null && !user.isAuthorized("essentials.lightning.others")))
			{
				user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation());
				return;
			}
		}

		if (server.matchPlayer(args[0]).isEmpty())
		{
			throw new Exception(_("playerNotFound"));
		}

		int power = 5;
		if (args.length > 1)
		{
			try
			{
				power = Integer.parseInt(args[1]);
			}
			catch (NumberFormatException ex)
			{
			}
		}

		for (Player matchPlayer : server.matchPlayer(args[0]))
		{
			sender.sendMessage(_("lightningUse", matchPlayer.getDisplayName()));

			final LightningStrike strike = matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation());
			
			if (!ess.getUser(matchPlayer).isGodModeEnabled())
			{
				matchPlayer.damage(power, strike);
			}
			if (ess.getSettings().warnOnSmite())
			{
				matchPlayer.sendMessage(_("lightningSmited"));
			}
		}
	}
コード例 #25
0
ファイル: HubTools.java プロジェクト: TeamTeddeh/HubTools
  // On Plugin Enable
  @Override
  public void onEnable() {

    // Getting Server Info
    server = getServer();
    for (Player p : server.getOnlinePlayers())

      // Turns on the Commands
      initializeCommands();

    // Config Files
    this.getConfig().options().copyDefaults(true);
    saveDefaultConfig();

    // Permissions
    PluginManager pm = this.getServer().getPluginManager();
    pm.addPermission(new Permissions().HubToolsAdmin);
    pm.addPermission(new Permissions().canGiveBuffs);
    pm.addPermission(new Permissions().canStun);
    pm.addPermission(new Permissions().canUnstun);
    pm.addPermission(new Permissions().canGM);

    // Events
    pm.registerEvents(this, this);
  }
コード例 #26
0
ファイル: Util.java プロジェクト: Erycus/SwornRPG_M
  public static Player matchPlayer(String pl) {
    List<Player> players = server.matchPlayer(pl);

    if (players.size() >= 1) return players.get(0);

    return null;
  }
コード例 #27
0
 public List<String> getBannedPlayers() throws APIException {
   List<String> a = new ArrayList<String>();
   for (OfflinePlayer p : Server.getBannedPlayers()) {
     a.add(p.getName());
   }
   return a;
 }
コード例 #28
0
  @Test
  public void testWorldImportWithNoFolder() {
    // Make sure the world directory do NOT exist
    // (it was created by the TestInstanceCreator)
    File worldFile = new File(TestInstanceCreator.serverDirectory, "world");
    assertTrue(worldFile.exists());
    assertTrue(worldFile.delete());

    // Start actual testing.
    // Pull a core instance from the server.
    Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");

    // Make sure Core is not null
    assertNotNull(plugin);

    // Make sure Core is enabled
    assertTrue(plugin.isEnabled());
    // Initialize a fake command
    Command mockCommand = mock(Command.class);
    when(mockCommand.getName()).thenReturn("mv");
    String[] normalArgs = new String[] {"import", "world", "normal"};

    // Ensure we have a fresh copy of MV, 0 worlds.
    assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());

    // Import the first world. The world folder does not exist.
    plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);
    verify(mockCommandSender).sendMessage(ChatColor.RED + "FAILED.");
    verify(mockCommandSender)
        .sendMessage("That world folder does not exist. These look like worlds to me:");

    // We should still have no worlds.
    assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
  }
コード例 #29
0
  @Test
  public void testNullWorld() {
    // Pull a core instance from the server.
    Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");

    // Make sure Core is not null
    assertNotNull(plugin);

    // Make sure Core is enabled
    assertTrue(plugin.isEnabled());

    // Initialize a fake command
    Command mockCommand = mock(Command.class);
    when(mockCommand.getName()).thenReturn("mv");

    // Ensure that there are no worlds imported. This is a fresh setup.
    assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());

    // Create the NULL world
    // The safe check is now BALLS SLOW. Use the -n to skip checking.
    String[] normalArgs = new String[] {"create", "nullworld", "normal", "-n"};
    plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);

    // We should now have one world!
    assertEquals(1, creator.getCore().getMVWorldManager().getMVWorlds().size());

    // Verify
    verify(mockCommandSender).sendMessage("Starting creation of world 'nullworld'...");
    verify(mockCommandSender).sendMessage("Complete!");

    WorldCreatorMatcher matcher = new WorldCreatorMatcher(new WorldCreator("nullworld"));
    verify(mockServer).createWorld(Matchers.argThat(matcher));
  }
コード例 #30
0
  @Test
  public void testWorldCreateInvalidGenerator() {
    // Pull a core instance from the server.
    Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");

    // Make sure Core is not null
    assertNotNull(plugin);

    // Make sure Core is enabled
    assertTrue(plugin.isEnabled());

    // Initialize a fake command
    Command mockCommand = mock(Command.class);
    when(mockCommand.getName()).thenReturn("mv");

    // Ensure that there are no worlds imported. This is a fresh setup.
    assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());

    // Create the world
    String[] normalArgs = new String[] {"create", "newworld", "normal", "-g", "BogusGen"};
    plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);

    // This command should halt, not creating any worlds
    assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());

    // Verify
    verify(mockCommandSender)
        .sendMessage(
            "Invalid generator! 'BogusGen'. " + ChatColor.RED + "Aborting world creation.");
  }