Java Code Examples for org.bukkit.Bukkit#getOnlinePlayers()

The following examples show how to use org.bukkit.Bukkit#getOnlinePlayers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BungeeChannel.java    From HolographicDisplays with GNU General Public License v3.0 6 votes vote down vote up
public void askPlayerCount(String server) {
	ByteArrayOutputStream b = new ByteArrayOutputStream();
	DataOutputStream out = new DataOutputStream(b);

	try {
		out.writeUTF("PlayerCount");
		out.writeUTF(server);
	} catch (IOException e) {
		// It should not happen.
		ConsoleLogger.log(Level.WARNING, "I/O Exception while asking for player count on server '" + server + "'.", e);
	}

	// OR, if you don't need to send it to a specific player
	Collection<? extends Player> players = Bukkit.getOnlinePlayers();
	if (players.size() > 0) {
		players.iterator().next().sendPluginMessage(HolographicDisplays.getInstance(), getTargetChannel(), b.toByteArray());
	}
}
 
Example 2
Source File: HomeCommand.java    From MarriageMaster with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String mainCommandAlias, @NotNull String alias, @NotNull String[] args)
{
	List<String> names = getMarriagePlugin().getCommandManager().getSimpleTabComplete(sender, args);
	if(sender.hasPermission(Permissions.HOME_OTHERS))
	{
		if(names == null)
		{
			names = new LinkedList<>();
		}
		String arg = args[args.length - 1].toLowerCase(Locale.ENGLISH);
		for(Player player : Bukkit.getOnlinePlayers())
		{
			if(!names.contains(player.getName()) && !sender.getName().equals(player.getName()) && player.getName().toLowerCase(Locale.ENGLISH).startsWith(arg))
			{
				names.add(player.getName());
			}
		}
		if(names.isEmpty())
		{
			names = null;
		}
	}
	return names;
}
 
Example 3
Source File: SoundEffect.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
public void apply() {
    Object target = getTarget();
    Location location = null;
    if (target instanceof LivingEntity) {
        LivingEntity livingEntity = (LivingEntity) target;
        location = livingEntity.getLocation();
    } else if (target instanceof Block) {
        Block block = (Block) target;
        location = block.getLocation();
    } else {
        return;
    }
    Sound sound = Sound.valueOf(this.soundName);

    if (sound == null) {
        return;
    }
    for (Player player : Bukkit.getOnlinePlayers()) {
        if (player.getLocation().getWorld().equals(location.getWorld()) && player.getLocation().distanceSquared(location) < 400) {
            player.playSound(location, sound, volume, pitch);
        }
    }
}
 
Example 4
Source File: Game.java    From Survival-Games with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void removeSpectator(Player p) {
	ArrayList < Player > players = new ArrayList < Player > ();
	players.addAll(activePlayers);
	players.addAll(inactivePlayers);

	if(p.isOnline()){
		for (Player pl: Bukkit.getOnlinePlayers()) {
			pl.showPlayer(p);
		}
	}
	restoreInv(p);
	p.setAllowFlight(false);
	p.setFlying(false);
	p.setFallDistance(0);
	p.setHealth(p.getMaxHealth());
	p.setFoodLevel(20);
	p.setSaturation(20);
	p.teleport(SettingsManager.getInstance().getLobbySpawn());
	// Bukkit.getServer().broadcastPrefixType("Removing Spec "+p.getName()+" "+spectators.size()+" left");
	spectators.remove(p.getName());
	// Bukkit.getServer().broadcastPrefixType("Removed");

	nextspec.remove(p);
}
 
Example 5
Source File: UCChannel.java    From UltimateChat with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Send a message from a channel as console.
 *
 * @param sender  {@code ConsoleCommandSender} - Console sender.
 * @param message {@code FancyMessage} - Message to send.
 */
@Deprecated
public void sendMessage(ConsoleCommandSender sender, String message) {
    if (UChat.get().getUCConfig().getBoolean("api.format-console-messages")) {
        UCMessages.sendFancyMessage(new String[0], message, this, sender, null);
    } else {
        UltimateFancy fmsg = new UltimateFancy(message);
        for (Player p : Bukkit.getOnlinePlayers()) {
            UCChannel chp = UChat.get().getPlayerChannel(p);
            if (UCPerms.channelReadPerm(p, this) && !this.isIgnoring(p.getName()) && (!this.neeFocus() || chp.equals(this))) {
                UChat.get().getUCLogger().timings(timingType.START, "UCChannel#sendMessage()|Fire AsyncPlayerChatEvent");
                fmsg.send(p);
            }
        }
        fmsg.send(sender);
    }
}
 
Example 6
Source File: StatsCommand.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void completeTab(List<String> completion, CommandSender sender, List<String> args) {
    if (args.size() == 1 && Main.isPlayerStatisticsEnabled()
            && (sender.hasPermission(OTHER_STATS_PERMISSION) || sender.hasPermission(ADMIN_PERMISSION))) {
        for (Player p : Bukkit.getOnlinePlayers()) {
            completion.add(p.getName());
        }
    }
}
 
Example 7
Source File: Notifier.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDisable() {
    BossBarManager bossBarManager = getBossBarManager();
    ActionBarManager actionBarManager = getActionBarManager();
    ScoreBoardManager scoreBoardManager = getScoreBoardManager();

    Collection<? extends Player> onlinePlayerList = Bukkit.getOnlinePlayers();
    for(Player player : onlinePlayerList) {
        actionBarManager.removeActionBar(player);
        bossBarManager.removeBossBar(player, true);
        scoreBoardManager.removeScoreboard(player);
    }
}
 
Example 8
Source File: DisplayAutoDespawnWatcher.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    int range = plugin.getConfig().getInt("shop.display-despawn-range");

    for (Shop shop : plugin.getShopManager().getLoadedShops()) {
        if (shop.getDisplay() != null) {
            // Check the range has player?
            boolean anyPlayerInRegion = false;
            for (Player player : Bukkit.getOnlinePlayers()) {
                if (player.getWorld() == shop.getLocation().getWorld()) {
                    if (player.getLocation().distance(shop.getLocation()) < range) {
                        anyPlayerInRegion = true;
                        break;
                    }
                }
            }
            if (anyPlayerInRegion) {
                if (!shop.getDisplay().isSpawned()) {
                    Util.debugLog(
                            "Respawning the shop "
                                    + shop
                                    + " the display, cause it was despawned and a player close it");
                    Bukkit.getScheduler().runTask(plugin, shop::checkDisplay);
                }
            } else if (shop.getDisplay().isSpawned()) {
                removeDisplayItemDelayed(shop);
            }
        }
    }
}
 
Example 9
Source File: ParticlesTask.java    From WorldEditSelectionVisualizer with MIT License 5 votes vote down vote up
@Override
public void run() {
    boolean needWand = plugin.getConfig().getBoolean("need-we-wand");
    double maxDistanceSquared = NumberConversions.square(config.getViewDistance());
    ParticleData particleData = config.getParticleData();

    for (Player player : Bukkit.getOnlinePlayers()) {
        PlayerVisualizerInfos visualizerInfo = plugin.getPlayerInfos(player);

        PlayerSelection playerSelection = visualizerInfo.getSelection(type).orElse(null);

        if (playerSelection == null) {
            continue;
        }

        playerSelection.checkExpireTime();
        SelectionPoints selectionPoints = playerSelection.getSelectionPoints();

        if (selectionPoints == null || (needWand && !visualizerInfo.isHoldingSelectionItem())) {
            continue;
        }

        Collection<Vector3d> vectors = primary ? selectionPoints.primary() : selectionPoints.secondary();

        Vector3d location = new Vector3d(player.getLocation().toVector());
        Vector3d origin = (type != SelectionType.CLIPBOARD) ? Vector3d.ZERO : location.subtract(selectionPoints.origin()).floor();

        for (Vector3d vector : vectors) {
            double x = vector.getX() + origin.getX();
            double y = vector.getY() + origin.getY();
            double z = vector.getZ() + origin.getZ();

            if (location.distanceSquared(x, y, z) > maxDistanceSquared) {
                continue;
            }

            FastParticle.spawnParticle(player, particleData.getType(), x, y, z, 1, 0, 0, 0, 0, particleData.getData());
        }
    }
}
 
Example 10
Source File: WorldUtils.java    From Transport-Pipes with MIT License 5 votes vote down vote up
/**
 * THREAD-SAFE
 */
public static List<Player> getPlayerList(World world) {
    // Bukkit.getOnlinePlayers is the only thread safe playerlist getter
    List<Player> playerList = new ArrayList<>();
    for (Player p : Bukkit.getOnlinePlayers()) {
        if (p.getLocation().getWorld().equals(world)) {
            playerList.add(p);
        }
    }
    return playerList;
}
 
Example 11
Source File: Broadcast.java    From SuperVanish with Mozilla Public License 2.0 5 votes vote down vote up
public static void announceSilentQuit(Player p, SuperVanish plugin) {
    if (plugin.getSettings().getBoolean("MessageOptions.AnnounceRealJoinQuitToAdmins", true)) {
        for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
            if (p == onlinePlayer)
                continue;
            if (plugin.canSee(onlinePlayer, p)) {
                plugin.sendMessage(onlinePlayer, "SilentQuitMessageForAdmins", p, onlinePlayer);
            }
        }
    }
}
 
Example 12
Source File: BroadcastLogin.java    From SuperVanish with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void execute(Command cmd, CommandSender p, String[] args, String label) {
    if (canDo(p, CommandAction.BROADCAST_LOGIN, true)) {
        for (Player onlinePlayer : Bukkit.getOnlinePlayers())
            plugin.sendMessage(onlinePlayer, "ReappearMessage", p, onlinePlayer);
    }
}
 
Example 13
Source File: PacketPlayOutActionBar.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public void broadcast()
{
    for(Player player : Bukkit.getOnlinePlayers())
    {
        send(player);
    }
}
 
Example 14
Source File: Protocol_v1_8_R2.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
private void sendGlobalPacket(Packet<?> packet)
{
	for(Player player : Bukkit.getOnlinePlayers())
	{
		((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
	}
}
 
Example 15
Source File: Protocol_v1_9_R1.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
private void sendGlobalPacket(Packet<?> packet)
{
	for(Player player : Bukkit.getOnlinePlayers())
	{
		((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
	}
}
 
Example 16
Source File: EndModule.java    From UHC with MIT License 5 votes vote down vote up
@Override
public void onDisable() {
    final Set<OfflinePlayer> players = Sets.newHashSet();
    final Set<String> worlds = Sets.newHashSet();

    for (final World world : Bukkit.getWorlds()) {
        if (world.getEnvironment() == World.Environment.THE_END) {
            worlds.add(world.getName());
            players.addAll(world.getPlayers());
        }
    }

    if (players.size() == 0) return;

    final Joiner joiner = Joiner.on(", ");
    final String playerNames = joiner.join(Iterables.transform(players, FunctionalUtil.PLAYER_NAME_FETCHER));
    final String worldNames = joiner.join(worlds);

    final String message = messages.evalTemplate(
            "notification",
            ImmutableMap.of("players", playerNames, "worlds", worldNames)
    );
    Bukkit.getConsoleSender().sendMessage(message);

    for (final Player player : Bukkit.getOnlinePlayers()) {
        if (player.hasPermission("uhc.broadcast.enddisable")) {
            player.sendMessage(message);
        }
    }
}
 
Example 17
Source File: AsyncPlayerChat.java    From StaffPlus with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onChat(AsyncPlayerChatEvent event)
{
	Player player = event.getPlayer();
	String message = event.getMessage();
	
	if(shouldCancel(player, message))
	{
		event.setCancelled(true);
		return;
	}
	
	List<User> mentioned = getMentioned(message);
	
	if(!mentioned.isEmpty())
	{
		for(User user : mentioned)
		{
			alertCoordinator.onMention(user, player.getName());
		}
	}
	
	if(options.chatBlacklistEnabled && options.chatEnabled)
	{
		BlacklistFactory blacklistFactory = new BlacklistFactory(message);
		
		if(blacklistFactory.runCheck().hasChanged()&& !permission.has(player, options.permissionBlacklist))
		{
			event.setMessage(blacklistFactory.getResult());
			
			if(options.chatBlacklistHoverable)
			{
				Set<Player> staffPlayers = new HashSet<Player>();
				
				for(Player p : Bukkit.getOnlinePlayers())
				{
					if(permission.has(p, options.permissionBlacklist))
					{
						event.getRecipients().remove(p);
						staffPlayers.add(p);
					}
				}
				
				versionProtocol.sendHoverableJsonMessage(staffPlayers, messages.blacklistChatFormat.replace("%player%", player.getName()).replace("%message%", blacklistFactory.getResult()), message);
			}
		}
	}
}
 
Example 18
Source File: SlimefunPlugin.java    From Slimefun4 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onDisable() {
    // Slimefun never loaded successfully, so we don't even bother doing stuff here
    if (instance == null || minecraftVersion == MinecraftVersion.UNIT_TEST) {
        return;
    }

    // Cancel all tasks from this plugin immediately
    Bukkit.getScheduler().cancelTasks(this);

    // Finishes all started movements/removals of block data
    ticker.halt();
    ticker.run();

    // Save all Player Profiles that are still in memory
    PlayerProfile.iterator().forEachRemaining(profile -> {
        if (profile.isDirty()) {
            profile.save();
        }
    });

    // Save all registered Worlds
    for (Map.Entry<String, BlockStorage> entry : getRegistry().getWorlds().entrySet()) {
        try {
            entry.getValue().save(true);
        }
        catch (Exception x) {
            getLogger().log(Level.SEVERE, x, () -> "An Error occurred while saving Slimefun-Blocks in World '" + entry.getKey() + "' for Slimefun " + getVersion());
        }
    }

    for (UniversalBlockMenu menu : registry.getUniversalInventories().values()) {
        menu.save();
    }

    // Create a new backup zip
    backupService.run();

    // Prevent Memory Leaks
    // These static Maps should be removed at some point...
    AContainer.processing = null;
    AContainer.progress = null;

    AGenerator.processing = null;
    AGenerator.progress = null;

    Reactor.processing = null;
    Reactor.progress = null;

    instance = null;

    // Close all inventories on the server to prevent item dupes
    // (Incase some idiot uses /reload)
    for (Player p : Bukkit.getOnlinePlayers()) {
        p.closeInventory();
    }
}
 
Example 19
Source File: HorsesModule.java    From UHC with MIT License 4 votes vote down vote up
@Override
public void onDisable() {
    for (final Player player : Bukkit.getOnlinePlayers()) {
        kickOffHorse(player);
    }
}
 
Example 20
Source File: UtilityBukkit.java    From LunaChat with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * 現在接続中のプレイヤーを全て取得する
 * @return 接続中の全てのプレイヤー
 */
public static Collection<? extends Player> getOnlinePlayers() {
    return Bukkit.getOnlinePlayers();
}