コード例 #1
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;
	}
コード例 #2
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();
  }
コード例 #3
0
	@Override
	protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{
		if (args.length < 1)
		{
			throw new NotEnoughArgumentsException();
		}
		final String whois = args[0].toLowerCase(Locale.ENGLISH);
		for (Player onlinePlayer : server.getOnlinePlayers())
		{
			final User u = ess.getUser(onlinePlayer);
			if (u.isHidden())
			{
				continue;
			}
			final String displayName = Util.stripColor(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
			if (!whois.equals(displayName)
				&& !displayName.equals(Util.stripColor(ess.getSettings().getNicknamePrefix()) + whois)
				&& !whois.equalsIgnoreCase(u.getName()))
			{
				continue;
			}
			sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName());
		}
	}
コード例 #4
0
 /*     */ public Player getPlayer(String partialName, boolean exact) /*     */ {
   /* 149 */ if ((partialName == null) || (partialName.isEmpty())) {
     /* 151 */ return null;
     /*     */ }
   /* 154 */ Collection<? extends Player> players = server.getOnlinePlayers();
   /* 157 */ for (Player player : players) {
     /* 159 */ if (partialName.equalsIgnoreCase(player.getName())) {
       /* 161 */ return player;
       /*     */ }
     /*     */ }
   /* 165 */ if (exact) {
     /* 167 */ return null;
     /*     */ }
   /* 171 */ for (Player player : players) {
     /* 173 */ if (player.getName().toLowerCase().contains(partialName.toLowerCase())) {
       /* 175 */ return player;
       /*     */ }
     /*     */ }
   /* 180 */ for (Player player : players) {
     /* 182 */ if (player.getDisplayName().toLowerCase().contains(partialName.toLowerCase())) {
       /* 184 */ return player;
       /*     */ }
     /*     */ }
   /* 188 */ return null;
   /*     */ }
コード例 #5
0
  private void usePowertools(final PlayerAnimationEvent event) {
    if (event.getAnimationType() != PlayerAnimationType.ARM_SWING) {
      return;
    }
    final User user = ess.getUser(event.getPlayer());
    final ItemStack is = user.getItemInHand();
    if (is == null || is.getType() == Material.AIR || !user.arePowerToolsEnabled()) {
      return;
    }
    final List<String> commandList = user.getPowertool(is);
    if (commandList == null || commandList.isEmpty()) {
      return;
    }

    // We need to loop through each command and execute
    for (String command : commandList) {
      if (command.matches(".*\\{player\\}.*")) {
        // user.sendMessage("Click a player to use this command");
        continue;
      } else if (command.startsWith("c:")) {
        for (Player p : server.getOnlinePlayers()) {
          p.sendMessage(user.getDisplayName() + ":" + command.substring(2));
        }
      } else {
        user.getServer().dispatchCommand(event.getPlayer(), command);
      }
    }
  }
コード例 #6
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);
  }
コード例 #7
0
 public List<Player> getAllchatRecipients(Server server) {
   List<Player> players = new ArrayList<Player>();
   for (Player player : server.getOnlinePlayers()) {
     if (player.hasPermission("example6.allchat")) players.add(player);
   }
   return players;
 }
コード例 #8
0
 /**
  * Broadcast the given warning on the server.
  *
  * @param message - warning to broadcast.
  */
 public void broadcastWarning(String message) {
   // Send the warning to every player (console will be informed differently)
   for (Player player : server.getOnlinePlayers()) {
     if (CustomPermission.INFO.check(player)) {
       player.sendMessage(formatMessage(message));
     }
   }
 }
コード例 #9
0
ファイル: Backup.java プロジェクト: EderHD/Essentials
	public Backup(final IEssentials ess)
	{
		this.ess = ess;
		server = ess.getServer();
		if (server.getOnlinePlayers().length > 0)
		{
			startTask();
		}
	}
コード例 #10
0
  public List<String> getPlayerNames() {
    List<String> names = new ArrayList<String>();

    for (Player p : Server.getOnlinePlayers()) {
      names.add(p.getName());
    }

    return names;
  }
コード例 #11
0
  public void run() {
    if (server == null) return;

    Player[] players = server.getOnlinePlayers();

    for (int i = 0; i < players.length; i++) {
      checkPlayer(players[i], null, false);
    }
  }
コード例 #12
0
  public String topInGame() {
    String most = "";

    for (Player p : server.getOnlinePlayers()) {
      if (getScore(p) > getScore(most)) {
        most = p.getName();
      }
    }

    return most;
  }
コード例 #13
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);
   }
 }
コード例 #14
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{
		if (args.length < 1)
		{
			throw new NotEnoughArgumentsException();
		}
		final User user = getPlayer(server, args, 0, true);
		if (!user.isOnline())
		{
			if (sender instanceof Player
				&& !ess.getUser(sender).isAuthorized("essentials.ban.offline"))
			{
				sender.sendMessage(_("banExempt"));
				return;
			}
		}
		else
		{
			if (user.isAuthorized("essentials.ban.exempt"))
			{
				sender.sendMessage(_("banExempt"));
				return;
			}
		}
		
		final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
		String banReason;
		if (args.length > 1)
		{
			banReason = _("banFormat", getFinalArg(args, 1), senderName);
		}
		else
		{
			banReason = _("banFormat", _("defaultBanReason"), senderName);
		}
		
		user.setBanReason(banReason);
		user.setBanned(true);
		user.kickPlayer(banReason);

		for (Player onlinePlayer : server.getOnlinePlayers())
		{
			final User player = ess.getUser(onlinePlayer);
			if (player.isAuthorized("essentials.ban.notify"))
			{
				onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason));
			}
		}
	}
コード例 #15
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();
	}
コード例 #16
0
ファイル: SayCommand.java プロジェクト: JoshMorgan/Ore-Logger
  @Override
  public boolean handlePlayer(TregminePlayer player, String[] args) {
    Server server = player.getServer();
    String msg = argsToMessage(args);

    server.broadcastMessage("<" + RED + "GOD" + WHITE + "> " + LIGHT_PURPLE + msg);

    LOGGER.info(player.getName() + ": <GOD> " + msg);

    Player[] players = server.getOnlinePlayers();
    for (Player p : players) {
      TregminePlayer current = tregmine.getPlayer((p.getName()));
      if (current.isAdmin()) {
        current.sendMessage(DARK_AQUA + "/say used by: " + player.getChatName());
      }
    }

    return true;
  }
コード例 #17
0
	@EventHandler(priority = EventPriority.HIGHEST)
	public void onLocalChat(final EssentialsLocalChatEvent event)
	{
		final Player sender = event.getPlayer();
		final Location loc = sender.getLocation();
		final World world = loc.getWorld();

		for (Player onlinePlayer : server.getOnlinePlayers())
		{
			String type = _("chatTypeLocal");
			final IUser user = ess.getUser(onlinePlayer);
			if (user.isIgnoringPlayer(ess.getUser(sender)))
			{
				continue;
			}
			if (!user.equals(sender))
			{
				boolean abort = false;
				final Location playerLoc = user.getLocation();
				if (playerLoc.getWorld() != world)
				{
					abort = true;
				}
				final double delta = playerLoc.distanceSquared(loc);

				if (delta > event.getRadius())
				{
					abort = true;
				}

				if (abort)
				{
					if (ChatPermissions.getPermission("spy").isAuthorized(user))
					{
						type = type.concat(_("chatTypeSpy"));
					}
				}
			}
			final String message = type.concat(String.format(event.getFormat(), sender.getDisplayName(), event.getMessage()));
			user.sendMessage(message);
		}
	}
コード例 #18
0
  @Override
  public void onPlayerLogin(final PlayerLoginEvent event) {
    if (event.getResult() != Result.ALLOWED
        && event.getResult() != Result.KICK_FULL
        && event.getResult() != Result.KICK_BANNED) {
      LOGGER.log(
          Level.INFO,
          "Disconnecting user "
              + event.getPlayer().toString()
              + " due to "
              + event.getResult().toString());
      return;
    }
    User user = ess.getUser(event.getPlayer());
    user.setNPC(false);

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

    if (banExpired == false && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) {
      final String banReason = user.getBanReason();
      event.disallow(
          Result.KICK_BANNED,
          banReason != null && !banReason.isEmpty() && !banReason.equalsIgnoreCase("ban")
              ? banReason
              : Util.i18n("defaultBanReason"));
      return;
    }

    if (server.getOnlinePlayers().length >= server.getMaxPlayers()
        && !user.isAuthorized("essentials.joinfullserver")) {
      event.disallow(Result.KICK_FULL, Util.i18n("serverFull"));
      return;
    }
    event.allow();

    user.setLastLogin(System.currentTimeMillis());
    updateCompass(user);
  }
コード例 #19
0
  @Override
  public void run() {
    for (Player p : server.getOnlinePlayers()) {
      TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(p);
      playerdata.resetMsgCount();
      playerdata.resetBlockDestroyCount();
      playerdata.resetBlockPlaceCount();
    }

    if (TotalFreedomMod.autoEntityWipe) {
      TFM_Util.wipeEntities(!TotalFreedomMod.allowExplosions, false);
    }

    if (TotalFreedomMod.disableNight) {
      try {
        for (World world : server.getWorlds()) {
          if (world.getTime() > 12000L) {
            TFM_Util.setWorldTime(world, 1000L);
          }
        }
      } catch (NullPointerException ex) {
      }
    }

    if (TotalFreedomMod.disableWeather) {
      for (World world : server.getWorlds()) {
        if (world.getWeatherDuration() > 0) {
          world.setThundering(false);
          world.setWeatherDuration(0);
        } else if (world.getThunderDuration() > 0) {
          world.setStorm(false);
          world.setThunderDuration(0);
        }
      }
    }
  }
コード例 #20
0
ファイル: ExtrasRandom.java プロジェクト: Adamki11s/HeadGear
 @Override
 public Player getRandomPlayer(Server s) {
   return s.getOnlinePlayers()[getRandomInt(s.getOnlinePlayers().length - 1, 0)];
 }
コード例 #21
0
  public void startSetup() {
    clearAll();

    int i = 0;

    for (Player p : server.getOnlinePlayers()) {
      if (!isSpectator(p) && !isTribute(p)) {
        hidePlayer(p);
      }

      if (isTribute(p)) {
        if (i >= getTubes().size()) i = 0;

        Location to = getTubes().get(i);
        p.setHealth(20);
        p.setFoodLevel(20);
        p.setSprinting(false);
        p.setSneaking(false);
        p.setPassenger(null);
        p.setGameMode(GameMode.SURVIVAL);
        p.setFireTicks(0);
        clearItems(p);
        getTribute(p).start = to;
        p.teleport(toCenter(to));

        i++;
      }
    }

    for (String s : ServerGames.worlds) {
      World w = ServerGames.server.getWorld(s);
      w.getEntities().clear();
      w.setThundering(false);
      w.setTime(0);
      w.setWeatherDuration(0);
      w.setStorm(false);
    }

    // ----- WORLD RESETTING -----
    LogBlock logblock = (LogBlock) getServer().getPluginManager().getPlugin("LogBlock");
    QueryParams params = new QueryParams(logblock);

    params.world = getCorn().getWorld();
    params.silent = false;

    try {
      logblock.getCommandsHandler()
      .new CommandRollback(this.getServer().getConsoleSender(), params, false);
    } catch (Exception e) {
    }

    clearEnt();

    // ----- WORLD RESETTING -----

    server.broadcastMessage(DARK_AQUA + "This plugin was created by Brenhien and NerdsWBNerds.");
    server.broadcastMessage(
        DARK_AQUA
            + "Email [email protected] or tweet us (@NerdsWBNerds) with ideas or bugs you have found.");

    load();

    state = State.SET_UP;
    game = new Setup(this);

    startTimer();
  }
コード例 #22
0
  public static void handlePlayerLogin(PlayerLoginEvent event) {
    final Server server = TotalFreedomMod.server;
    final Player player = event.getPlayer();
    final String username = player.getName();
    final String ip = event.getAddress().getHostAddress().trim();
    final UUID uuid = TFM_UuidManager.newPlayer(player, ip);

    // Check username length
    if (username.length() < 3 || username.length() > TotalFreedomMod.MAX_USERNAME_LENGTH) {
      event.disallow(
          Result.KICK_OTHER,
          "Your username is an invalid length (must be between 3 and 20 characters long).");
      return;
    }

    // Check username characters
    if (!USERNAME_REGEX.matcher(username).find()) {
      event.disallow(Result.KICK_OTHER, "Your username contains invalid characters.");
      return;
    }

    // Check force-IP match
    if (TFM_ConfigEntry.FORCE_IP_ENABLED.getBoolean()) {
      final String hostname =
          event
              .getHostname()
              .replace(
                  "\u0000FML\u0000",
                  ""); // Forge fix - https://github.com/TotalFreedom/TotalFreedomMod/issues/493
      final String connectAddress = TFM_ConfigEntry.SERVER_ADDRESS.getString();
      final int connectPort = TotalFreedomMod.server.getPort();

      if (!hostname.equalsIgnoreCase(connectAddress + ":" + connectPort)
          && !hostname.equalsIgnoreCase(connectAddress + ".:" + connectPort)) {
        final int forceIpPort = TFM_ConfigEntry.FORCE_IP_PORT.getInteger();
        event.disallow(
            PlayerLoginEvent.Result.KICK_OTHER,
            TFM_ConfigEntry.FORCE_IP_KICKMSG
                .getString()
                .replace(
                    "%address%",
                    TFM_ConfigEntry.SERVER_ADDRESS.getString()
                        + (forceIpPort == TFM_PlayerListener.DEFAULT_PORT
                            ? ""
                            : ":" + forceIpPort)));
        return;
      }
    }

    // Check if player is admin
    // Not safe to use TFM_Util.isSuperAdmin(player) because player.getAddress() will return a null
    // until after player login.
    final boolean isAdmin = TFM_AdminList.isSuperAdminSafe(uuid, ip);

    // Validation below this point
    if (isAdmin) // Player is superadmin
    {
      // Force-allow log in
      event.allow();

      int count = server.getOnlinePlayers().size();
      if (count >= server.getMaxPlayers()) {
        for (Player onlinePlayer : server.getOnlinePlayers()) {
          if (!TFM_AdminList.isSuperAdmin(onlinePlayer)) {
            onlinePlayer.kickPlayer("You have been kicked to free up room for an admin.");
            count--;
          }

          if (count < server.getMaxPlayers()) {
            break;
          }
        }
      }

      if (count >= server.getMaxPlayers()) {
        event.disallow(
            Result.KICK_OTHER, "The server is full and a player could not be kicked, sorry!");
        return;
      }

      return;
    }

    // Player is not an admin
    // Server full check
    if (server.getOnlinePlayers().size() >= server.getMaxPlayers()) {
      event.disallow(Result.KICK_FULL, "Sorry, but this server is full.");
      return;
    }

    // Admin-only mode
    if (TFM_ConfigEntry.ADMIN_ONLY_MODE.getBoolean()) {
      event.disallow(Result.KICK_OTHER, "Server is temporarily open to admins only.");
      return;
    }

    // Lockdown mode
    if (TotalFreedomMod.lockdownEnabled) {
      event.disallow(Result.KICK_OTHER, "Server is currently in lockdown mode.");
      return;
    }

    // Whitelist
    if (isWhitelisted()) {
      if (!getWhitelisted().contains(username.toLowerCase())) {
        event.disallow(Result.KICK_OTHER, "You are not whitelisted on this server.");
        return;
      }
    }

    // UUID ban
    if (TFM_BanManager.isUuidBanned(uuid)) {
      final TFM_Ban ban = TFM_BanManager.getByUuid(uuid);
      event.disallow(Result.KICK_OTHER, ban.getKickMessage());
      return;
    }

    // IP ban
    if (TFM_BanManager.isIpBanned(ip)) {
      final TFM_Ban ban = TFM_BanManager.getByIp(ip);
      event.disallow(Result.KICK_OTHER, ban.getKickMessage());
      return;
    }

    // Permbanned IPs
    for (String testIp : TFM_PermbanList.getPermbannedIps()) {
      if (TFM_Util.fuzzyIpMatch(testIp, ip, 4)) {
        event.disallow(
            Result.KICK_OTHER,
            ChatColor.RED
                + "Your IP address is permanently banned from this server.\n"
                + "Release procedures are available at\n"
                + ChatColor.GOLD
                + TFM_ConfigEntry.SERVER_PERMBAN_URL.getString());
        return;
      }
    }

    // Permbanned usernames
    for (String testPlayer : TFM_PermbanList.getPermbannedPlayers()) {
      if (testPlayer.equalsIgnoreCase(username)) {
        event.disallow(
            Result.KICK_OTHER,
            ChatColor.RED
                + "Your username is permanently banned from this server.\n"
                + "Release procedures are available at\n"
                + ChatColor.GOLD
                + TFM_ConfigEntry.SERVER_PERMBAN_URL.getString());
        return;
      }
    }
  }
コード例 #23
0
ファイル: FastSwimming.java プロジェクト: N4m/MinecraftTLA
 public static void HandleSwim(Server server) {
   for (Player player : server.getOnlinePlayers()) {
     Abilities ability = Tools.getBendingAbility(player);
     if (Tools.isBender(player.getName(), BendingType.Water)
         && Tools.canBendPassive(player, BendingType.Water)
         && player.isSneaking()
         && Tools.isWater(player.getLocation().getBlock())
         && !TempBlock.isTempBlock(player.getLocation().getBlock())
         && !(ability == Abilities.WaterManipulation
             || ability == Abilities.Surge
             || ability == Abilities.HealingWaters
             || ability == Abilities.PhaseChange
             || ability == Abilities.Bloodbending
             || ability == Abilities.IceSpike
             || Tools.getBendingAbility(player) == Abilities.OctopusForm)) {
       player.setVelocity(
           player.getEyeLocation().getDirection().clone().normalize().multiply(factor));
     }
   }
   // for (Player p : s.getOnlinePlayers()) {
   // if ((!Tools.isBender(p, BendingType.Water)
   // || !Tools.canBendPassive(p, BendingType.Water) || p
   // .isSneaking()) && timers.containsKey(p))
   // timers.remove(p);
   // if (Tools.isBender(p, BendingType.Water)
   // && Tools.canBendPassive(p, BendingType.Water)
   // && p.getLocation().getBlock().isLiquid()
   // && !timers.containsKey(p)) {
   // timers.put(p, System.currentTimeMillis());
   // }
   // if (timers.containsKey(p)) {
   // if (timers.get(p) + (interval - 21) >= System
   // .currentTimeMillis()) {
   // locations.put(p, p.getLocation().getBlock().getLocation());
   // }
   // }
   // if (timers.containsKey(p)) {
   // if (!(timers.get(p) + interval >= System.currentTimeMillis())
   // && locations.containsKey(p)
   // && ((int) locations.get(p).getX() != (int) p
   // .getLocation().getBlock().getLocation().getX() || (int) locations
   // .get(p).getZ() != (int) p.getLocation()
   // .getBlock().getLocation().getZ())
   // && p.getLocation().getBlock().isLiquid()) {
   //
   // if (!p.getEyeLocation().getBlock().isLiquid()) {
   // timers.put(p, System.currentTimeMillis());
   // if ((p.getLocation().getYaw() > -45 && p.getLocation()
   // .getYaw() <= 45)
   // && locations.get(p).getZ() < p.getLocation()
   // .getZ()) {
   // Vector v = p.getLocation().getDirection().setY(0);
   // p.setVelocity(v.normalize().multiply(factor));
   // } else if ((p.getLocation().getYaw() > 45 && p
   // .getLocation().getYaw() <= 135)
   // && locations.get(p).getX() > p.getLocation()
   // .getX()) {
   // Vector v = p.getLocation().getDirection().setY(0);
   // p.setVelocity(v.normalize().multiply(factor));
   // } else if ((p.getLocation().getYaw() > 135 && p
   // .getLocation().getYaw() <= 225)
   // && locations.get(p).getZ() > p.getLocation()
   // .getZ()) {
   // Vector v = p.getLocation().getDirection().setY(0);
   // p.setVelocity(v.normalize().multiply(factor));
   // } else if ((p.getLocation().getYaw() > 225 && p
   // .getLocation().getYaw() <= 315)
   // && locations.get(p).getX() < p.getLocation()
   // .getX()) {
   // Vector v = p.getLocation().getDirection().setY(0);
   // p.setVelocity(v.normalize().multiply(factor));
   // }
   // } else {
   // timers.put(p, System.currentTimeMillis());
   // Vector v = p.getLocation().getDirection().normalize()
   // .multiply(factor);
   // p.setVelocity(v);
   // }
   // }
   // }
   // }
 }
コード例 #24
0
 public static void hidePlayer(Player player) {
   for (Player p : server.getOnlinePlayers()) {
     p.hidePlayer(player);
   }
 }
コード例 #25
0
 public void hardResetPlayers() {
   for (Player p : server.getOnlinePlayers()) {
     tributes.add(new Tribute(p));
   }
 }
コード例 #26
0
  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;
  }
コード例 #27
0
  public void manage(final Server server) {
    for (final Player player : server.getOnlinePlayers()) {
      if (TouchOfEvil.instances.containsKey(player)) {
        final BendingPlayer bPlayer = GeneralMethods.getBendingPlayer(player.getName());
        if (bPlayer.effects != null) {
          for (final Effect e : bPlayer.effects.keySet()) {
            if (bPlayer.effects.get(e) == "Helix") {
              //
              this.effect = (HelixEffect) e;
              break;
            }
          }

        } else {
          this.effect = new HelixEffect(MegaBending.getEM());
          this.start = true;
          bPlayer.addCooldown("EvilAura", 9000);
        }

        if (!GeneralMethods.canBend(player.getName(), "TouchOfEvil")
            || (GeneralMethods.getBendingPlayer(player.getName()).eviltouch == false)) {
          // instances.get(player);
          TouchOfEvil.instances.remove(player);
          if (this.effect != null) {
            bPlayer.effects.remove(this.effect);
            this.effect.cancel();
          }

        } else {
          TouchOfEvil.instances.get(player).set();
          this.effect.setDynamicOrigin(new DynamicLocation(player.getEyeLocation().add(0, -1, 0)));
          // effect.setTargetEntity(player);
          this.effect.radius = 6;

          this.effect.particle = ParticleEffect.PORTAL;

          this.effect.iterations = 40;
          // effect.infinite();
          // effect.infinite();
          if (this.start == true) {
            this.effect.start();
            this.start = false;
          }
          for (final Entity e : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), 5)) {
            if (e instanceof LivingEntity) {
              if (e instanceof Player) {
                if ((Player) e == player) {
                  continue;
                }
              }
              if (!((LivingEntity) e).hasPotionEffect(PotionEffectType.POISON)) {
                new TempPotionEffect((LivingEntity) e, TouchOfEvil.poison);
              }
              if (!((LivingEntity) e).hasPotionEffect(PotionEffectType.WEAKNESS)) {
                new TempPotionEffect((LivingEntity) e, TouchOfEvil.weak);
              }
            }
          }
        }
      }
    }
    for (final Player player : TouchOfEvil.instances.keySet()) {
      if (!player.isOnline()
          || player.isDead()
          || !GeneralMethods.getBendingPlayer(player.getName()).isOnCooldown("EvilAura")) {
        // instances.get(player).revert();
        final BendingPlayer bPlayer = GeneralMethods.getBendingPlayer(player.getName());
        if (bPlayer.effects != null) {
          for (final Effect e : bPlayer.effects.keySet()) {
            if (bPlayer.effects.get(e) == "Helix") {
              bPlayer.eviltouch = false;
              this.effect = (HelixEffect) e;
              bPlayer.effects.remove(this.effect);
              player.sendMessage(ChatColor.DARK_GRAY + "The dark spirit returns to your body.");
              break;
            }
          }
        }

        TouchOfEvil.instances.remove(player);
        this.effect.cancel();
      }
    }
  }
コード例 #28
0
ファイル: BukkitStringifier.java プロジェクト: Xon/jsonapi
  public static Object handle(Object obj) {
    if (obj instanceof World.Environment) {
      World.Environment e = (World.Environment) obj;
      if (e == World.Environment.NETHER) {
        return "nether";
      } else {
        return "normal";
      }
    } else if (obj instanceof File) {
      return ((File) obj).toString();
    } else if (obj instanceof Player) {
      Player p = (Player) obj;
      JSONObject o = new JSONObject();

      o.put("name", p.getName());
      o.put("op", p.isOp());
      o.put("health", p.getHealth());
      o.put("ip", p.getAddress().toString());
      o.put("itemInHand", p.getItemInHand());
      o.put("location", p.getLocation());
      o.put("inventory", p.getInventory());
      o.put("sneaking", p.isSneaking());
      o.put("inVehicle", p.isInsideVehicle());
      o.put("sleeping", p.isSleeping());
      o.put("world", p.getServer().getWorlds().indexOf(p.getWorld()));

      return o;
    } else if (obj instanceof Server) {
      Server s = (Server) obj;

      JSONObject o = new JSONObject();

      o.put("maxPlayers", s.getMaxPlayers());
      o.put("players", Arrays.asList(s.getOnlinePlayers()));
      o.put("port", s.getPort());
      o.put("name", s.getName());
      o.put("serverName", s.getServerName());
      o.put("version", s.getVersion());
      o.put("worlds", s.getWorlds());

      return o;
    } else if (obj instanceof World) {
      World w = (World) obj;

      JSONObject o = new JSONObject();

      o.put("environment", w.getEnvironment());
      o.put("fullTime", w.getFullTime());
      o.put("time", w.getTime());
      o.put("name", w.getName());
      o.put("isThundering", w.isThundering());
      o.put("hasStorm", w.hasStorm());

      return o;
    } else if (obj instanceof Plugin) {
      Plugin p = (Plugin) obj;
      PluginDescriptionFile d = p.getDescription();

      JSONObject o = new JSONObject();

      o.put("name", d.getName());
      o.put("description", d.getDescription());
      o.put("authors", d.getAuthors());
      o.put("version", d.getVersion());
      o.put("website", d.getWebsite());
      o.put("enabled", JSONAPI.instance.getServer().getPluginManager().isPluginEnabled(p));

      return o;
    } else if (obj instanceof ItemStack) {
      ItemStack i = (ItemStack) obj;

      JSONObject o = new JSONObject();

      o.put("type", i.getTypeId());
      o.put("durability", i.getDurability());
      o.put("amount", i.getAmount());

      return o;
    } else if (obj instanceof PlayerInventory) {
      PlayerInventory p = (PlayerInventory) obj;

      JSONObject o = new JSONObject();

      JSONObject armor = new JSONObject();
      armor.put("boots", p.getBoots());
      armor.put("chestplate", p.getChestplate());
      armor.put("helmet", p.getHelmet());
      armor.put("leggings", p.getLeggings());

      o.put("armor", armor);
      o.put("hand", p.getItemInHand());
      o.put("inventory", Arrays.asList(p.getContents()));

      return o;
    } else if (obj instanceof Location) {
      Location l = (Location) obj;

      JSONObject o = new JSONObject();

      o.put("x", l.getX());
      o.put("y", l.getY());
      o.put("z", l.getZ());
      o.put("pitch", l.getPitch());
      o.put("yaw", l.getYaw());

      return o;
    } else if (obj instanceof Plugin[]) {
      List<Plugin> l = Arrays.asList((Plugin[]) obj);

      Collections.sort(l, new PluginSorter());

      return l;
    } else if (obj instanceof Object[]) {
      int l = ((Object[]) obj).length;
      JSONArray a = new JSONArray();
      for (int i = 0; i < l; i++) {
        a.add(((Object[]) obj)[i]);
      }

      return a;
    }
    Logger.getLogger("JSONAPI").warning("Uncaugh object! Value:");
    Logger.getLogger("JSONAPI").warning(obj.toString());
    Logger.getLogger("JSONAPI").warning("Type:");
    Logger.getLogger("JSONAPI").warning(obj.getClass().getName());

    return new Object();
  }
コード例 #29
0
 public static void hideAllFrom(Player player) {
   for (Player p : server.getOnlinePlayers()) {
     player.hidePlayer(p);
   }
 }
コード例 #30
0
 public static void showAllFor(Player player) {
   for (Player p : server.getOnlinePlayers()) {
     player.showPlayer(p);
   }
 }