Java Code Examples for org.spongepowered.api.command.CommandSource#hasPermission()

The following examples show how to use org.spongepowered.api.command.CommandSource#hasPermission() . 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: VirtualBalanceCommand.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void run(CommandSource src, CommandContext args) {
    Currency currency = currencyService.getCurrentCurrency();
    if (args.getOne("account").isPresent()) {
        if (src.hasPermission("economylite.admin.virtualbalance")) {
            String target = args.<String>getOne("account").get();
            Optional<Account> aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target);
            if (aOpt.isPresent()) {
                BigDecimal bal = aOpt.get().getBalance(currency);
                Text label = currency.getPluralDisplayName();
                if (bal.equals(BigDecimal.ONE)) {
                    label = currency.getDisplayName();
                }
                src.sendMessage(messageStorage.getMessage("command.balanceother", "player", aOpt.get().getDisplayName().toPlain(), "balance",
                        String.format(Locale.ENGLISH, "%,.2f", bal), "label", label.toPlain()));
            } else {
                src.sendMessage(messageStorage.getMessage("command.error"));
            }
        } else {
            src.sendMessage(messageStorage.getMessage("command.noperm"));
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example 2
Source File: GeyserSpongeCommandExecutor.java    From Geyser with MIT License 6 votes vote down vote up
@Override
public CommandResult process(CommandSource source, String arguments) throws CommandException {
    String[] args = arguments.split(" ");
    if (args.length > 0) {
        if (getCommand(args[0]) != null) {
            if (!source.hasPermission(getCommand(args[0]).getPermission())) {
                source.sendMessage(Text.of(ChatColor.RED + "You do not have permission to execute this command!"));
                return CommandResult.success();
            }
            getCommand(args[0]).execute(new SpongeCommandSender(source), args);
        }
    } else {
        getCommand("help").execute(new SpongeCommandSender(source), args);
    }
    return CommandResult.success();
}
 
Example 3
Source File: SethomeCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, HomePermissions.UC_HOME_SETHOME_BASE);
    Player p = (Player) sender;
    String homename = args.<String>getOne("home").get();

    String shomecount = HomePermissions.UC_HOME_HOMECOUNT.getFor(sender);
    if (!ArgumentUtil.isInteger(shomecount)) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "home.command.sethome.invalidhomecount", "%homecount%", shomecount));
    }
    Integer homecount = Integer.parseInt(shomecount);
    UltimateUser user = UltimateCore.get().getUserService().getUser((Player) sender);
    List<Home> homes = user.get(HomeKeys.HOMES).orElse(new ArrayList<>());
    boolean replace = homes.stream().filter(home -> home.getName().equalsIgnoreCase(homename)).count() >= 1;
    //If amount of homes (+1 if not replace) is higher than max amount of homes
    if ((homes.size() + (replace ? 0 : 1)) > homecount && !sender.hasPermission(HomePermissions.UC_HOME_SETHOME_UNLIMITED.get())) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "home.command.sethome.maxhomes"));
    }
    //Remove home with matching name
    homes = homes.stream().filter(home -> !home.getName().equalsIgnoreCase(homename)).collect(Collectors.toList());
    homes.add(new Home(homename.toLowerCase(), new Transform<>(p.getLocation(), p.getRotation(), p.getScale())));
    user.offer(HomeKeys.HOMES, homes);

    if (replace) {
        Messages.send(sender, "home.command.sethome.success.replace", "%home%", homename.toLowerCase());
    } else {
        Messages.send(sender, "home.command.sethome.success.set", "%home%", homename.toLowerCase());
    }
    return CommandResult.success();
}
 
Example 4
Source File: NationPermExecutor.java    From Nations with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		if (!nation.isStaff(player.getUniqueId()))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PERM_NATIONSTAFF));
			return CommandResult.success();
		}
		String type = ctx.<String>getOne("type").get();
		String perm = ctx.<String>getOne("perm").get();
		if (!player.hasPermission("nations.command.nation.perm." + type + "." + perm))
		{
			player.sendMessage(t("You do not have permission to use this command!"));
			return CommandResult.success();
		}
		boolean bool = (ctx.<Boolean>getOne("bool").isPresent()) ? ctx.<Boolean>getOne("bool").get() : !nation.getPerm(type, perm);
		nation.setPerm(type, perm, bool);
		DataHandler.saveNation(nation.getUUID());
		int clicker = Utils.CLICKER_DEFAULT;
		if (src.hasPermission("nations.command.nationadmin"))
		{
			clicker = Utils.CLICKER_ADMIN;
		}
		src.sendMessage(Utils.formatNationDescription(nation, clicker));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 5
Source File: UCJedisLoader.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
public void sendTellMessage(CommandSource sender, String tellReceiver, Text msg) {
    Builder text = Text.builder();
    text.append(UCUtil.toText(this.thisId));

    //send spy
    if (!sender.hasPermission("uchat.chat-spy.bypass")) {
        for (Player receiver : Sponge.getServer().getOnlinePlayers()) {
            if (!receiver.getName().equals(tellReceiver) && !receiver.equals(sender) &&
                    UChat.get().isSpy.contains(receiver.getName()) && UChat.get().getPerms().hasSpyPerm(receiver, "private")) {
                String spyformat = UChat.get().getConfig().root().general.spy_format;

                spyformat = spyformat.replace("{output}", UCUtil.stripColor('&', UCMessages.sendMessage(sender, tellReceiver, msg, new UCChannel("tell")).toPlain()));
                receiver.sendMessage(UCUtil.toText(spyformat));
            }
        }
    }

    text.append(UCMessages.sendMessage(sender, tellReceiver, msg, new UCChannel("tell")));
    tellPlayers.put(tellReceiver, sender.getName());

    if (Arrays.asList(channels).contains("tellsend")) {
        Sponge.getScheduler().createAsyncExecutor(UChat.get()).execute(() -> {
            Jedis jedis = pool.getResource();
            try {
                //string 0 1 2
                jedis.publish("tellsend", this.thisId + "$" + tellReceiver + "$" + TextSerializers.JSON.serialize(text.build()));
            } catch (JedisConnectionException e) {
                e.printStackTrace();
            }
        });
    }
}
 
Example 6
Source File: KillExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	Optional<Player> p = ctx.<Player> getOne("player");

	if (p.isPresent() && src.hasPermission("essentialcmds.kill.others"))
	{
		p.get().offer(Keys.HEALTH, 0d);
		Utils.setLastTeleportOrDeathLocation(p.get().getUniqueId(), p.get().getLocation());
		src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Killed player " + p.get().getName()));
		p.get().sendMessage(Text.of(TextColors.RED, "You have been killed by " + src.getName()));
	}
	else if (!p.isPresent())
	{
		if (src instanceof Player)
		{
			Player player = (Player) src;
			player.offer(Keys.HEALTH, 0d);
			Utils.setLastTeleportOrDeathLocation(player.getUniqueId(), player.getLocation());
			src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Killed yourself."));
		}
		else
		{
			src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You cannot kill yourself, you are not a player!"));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You do not have permission to kill other players!"));
	}

	return CommandResult.success();
}
 
Example 7
Source File: NationFlagExecutor.java    From Nations with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		if (!nation.isStaff(player.getUniqueId()))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PERM_NATIONSTAFF));
			return CommandResult.success();
		}
		String flag = ctx.<String>getOne("flag").get();
		if (!player.hasPermission("nations.command.nation.flag." + flag))
		{
			player.sendMessage(t("You do not have permission to use this command!"));
			return CommandResult.success();
		}
		boolean bool = (ctx.<Boolean>getOne("bool").isPresent()) ? ctx.<Boolean>getOne("bool").get() : !nation.getFlag(flag);
		nation.setFlag(flag, bool);
		DataHandler.saveNation(nation.getUUID());
		int clicker = Utils.CLICKER_DEFAULT;
		if (src.hasPermission("nations.command.nationadmin"))
		{
			clicker = Utils.CLICKER_ADMIN;
		}
		src.sendMessage(Utils.formatNationDescription(nation, clicker));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 8
Source File: UCPerms8.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
private static boolean isAdmin(CommandSource p) {
    return (p instanceof ConsoleSource) || p.hasPermission("uchat.admin");
}
 
Example 9
Source File: HighCommand.java    From UltimateCore with MIT License 4 votes vote down vote up
default void checkPermission(CommandSource sender, Permission permission) throws CommandException {
    if (!sender.hasPermission(permission.get())) {
        throw new CommandPermissionException();
    }
}
 
Example 10
Source File: SubCommand.java    From SubServers-2 with Apache License 2.0 4 votes vote down vote up
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    if (canRun(sender)) {
        if (plugin.gui != null) {
            Optional<String> menu = args.getOne(Text.of("MenuID"));
            String[] menuopts = args.<String>getAll(Text.of("Args")).toArray(new String[0]);
            if (sender.hasPermission("subservers.interface")) {
                try {
                    plugin.gui.getRenderer((Player) sender).clearHistory();
                    switch (menu.get().toLowerCase()) {
                        case "host":
                            if (menuopts.length > 0) plugin.gui.getRenderer((Player) sender).hostMenu(Integer.parseInt(menuopts[0]));
                            else plugin.gui.getRenderer((Player) sender).hostMenu(1);
                            break;
                        case "host/":
                            plugin.gui.getRenderer((Player) sender).hostAdmin(menuopts[0]);
                            break;
                        case "host/creator":
                            if (sender.hasPermission("subservers.host.*.*") || sender.hasPermission("subservers.host.*.create") || sender.hasPermission("subservers.host." + menuopts[0].toLowerCase() + ".*") || sender.hasPermission("subservers.host." + menuopts[0].toLowerCase() + ".create"))
                                plugin.gui.getRenderer((Player) sender).hostCreator(new UIRenderer.CreatorOptions(menuopts[0]));
                            else throw new IllegalStateException("Player does not meet the requirements to render this page");
                            break;
                        case "host/plugin":
                            if (menuopts.length > 1) plugin.gui.getRenderer((Player) sender).hostPlugin(Integer.parseInt(menuopts[1]), menuopts[0]);
                            else plugin.gui.getRenderer((Player) sender).hostPlugin(1, menuopts[0]);
                            break;
                        case "group":
                            if (menuopts.length > 0) plugin.gui.getRenderer((Player) sender).groupMenu(Integer.parseInt(menuopts[0]));
                            else plugin.gui.getRenderer((Player) sender).groupMenu(1);
                            break;
                        case "server":
                        case "subserver":
                            if (menuopts.length > 2) plugin.gui.getRenderer((Player) sender).serverMenu(Integer.parseInt(menuopts[0]), menuopts[2], null);
                            else if (menuopts.length > 1) plugin.gui.getRenderer((Player) sender).serverMenu(Integer.parseInt(menuopts[0]), null, menuopts[1]);
                            else if (menuopts.length > 0) plugin.gui.getRenderer((Player) sender).serverMenu(Integer.parseInt(menuopts[0]), null, null);
                            else plugin.gui.getRenderer((Player) sender).serverMenu(1, null, null);
                            break;
                        case "subserver/":
                            plugin.gui.getRenderer((Player) sender).subserverAdmin(menuopts[0]);
                            break;
                        case "subserver/plugin":
                            if (menuopts.length > 1) plugin.gui.getRenderer((Player) sender).subserverPlugin(Integer.parseInt(menuopts[1]), menuopts[0]);
                            else plugin.gui.getRenderer((Player) sender).subserverPlugin(1, menuopts[0]);
                            break;
                    }
                    return CommandResult.builder().successCount(1).build();
                } catch (Throwable e) { /*
                    List<String> list = new LinkedList<String>();
                    list.addAll(Arrays.asList(menuopts));
                    list.remove(0);
                    new InvocationTargetException(e, "Could not render page with arguments: " + list.toString()).printStackTrace(); */
                    return CommandResult.builder().successCount(0).build();
                }
            } else {
                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Generic.Invalid-Permission").replace("$str$", "subservers.interface")));
                return CommandResult.builder().successCount(0).build();
            }
        } else return CommandResult.builder().successCount(0).build();
    } else {
        sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Generic.Invalid-Permission").replace("$str$", "subservers.command")));
        return CommandResult.builder().successCount(0).build();
    }
}
 
Example 11
Source File: UCPerms7.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
public boolean hasPerm(CommandSource p, String perm) {
    return (p instanceof ConsoleSource) || p.hasPermission("uchat." + perm) || p.hasPermission("uchat.admin");
}
 
Example 12
Source File: SubCommand.java    From SubServers-2 with Apache License 2.0 4 votes vote down vote up
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    if (canRun(sender)) {
        Optional<String> name = args.getOne(Text.of("Name"));
        Optional<String> host = args.getOne(Text.of("Host"));
        Optional<String> template = args.getOne(Text.of("Template"));
        Optional<String> version = args.getOne(Text.of("Version"));
        Optional<String> port = args.getOne(Text.of("Port"));
        if (name.isPresent() && host.isPresent() && template.isPresent()) {
            if (sender.hasPermission("subservers.host.*.*") || sender.hasPermission("subservers.host.*.create") || sender.hasPermission("subservers.host." + host.get().toLowerCase() + ".*") || sender.hasPermission("subservers.host." + host.get().toLowerCase() + ".create")) {
                if (port.isPresent() && Util.isException(() -> Integer.parseInt(port.get()))) {
                    sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Invalid-Port")));
                    return CommandResult.builder().successCount(0).build();
                } else {
                    ((SubDataClient) SubAPI.getInstance().getSubDataNetwork()[0]).sendPacket(new PacketCreateServer((sender instanceof Player)?((Player) sender).getUniqueId():null, name.get(), host.get(), template.get(), (version.isPresent() && version.get().length() > 0)?new Version(version.get()):null, (port.isPresent())?Integer.parseInt(port.get()):null, data -> {
                        switch (data.getInt(0x0001)) {
                            case 3:
                            case 4:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Exists")));
                                break;
                            case 5:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Unknown-Host")));
                                break;
                            case 6:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Start.Host-Unavailable")));
                                break;
                            case 7:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Start.Host-Disabled")));
                                break;
                            case 8:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Unknown-Template")));
                                break;
                            case 9:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Template-Disabled")));
                                break;
                            case 10:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Version-Required")));
                                break;
                            case 11:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator.Invalid-Port")));
                                break;
                            case 0:
                            case 1:
                                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Creator")));
                                break;
                        }
                    }));
                    return CommandResult.builder().successCount(1).build();
                }
            } else {
                sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Generic.Invalid-Permission").replace("$str$", "subservers.host." + host.get().toLowerCase() + ".create")));
                return CommandResult.builder().successCount(0).build();
            }
        } else {
            sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Generic.Usage").replace("$str$", "/sub create <Name> <Host> <Template> [Version] [Port]")));
            return CommandResult.builder().successCount(0).build();
        }
    } else {
        sender.sendMessage(ChatColor.convertColor(plugin.api.getLang("SubServers","Command.Generic.Invalid-Permission").replace("$str$", "subservers.command")));
        return CommandResult.builder().successCount(0).build();
    }
}
 
Example 13
Source File: UCPerms7.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
private static boolean isAdmin(CommandSource p) {
    return (p instanceof ConsoleSource) || p.hasPermission("uchat.admin");
}
 
Example 14
Source File: UCPerms8.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
public boolean hasPerm(CommandSource p, String perm) {
    return (p instanceof ConsoleSource) || p.hasPermission("uchat." + perm) || p.hasPermission("uchat.admin");
}
 
Example 15
Source File: UCPerms8.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
public boolean canIgnore(CommandSource sender, Object toignore) {
    return !(toignore instanceof CommandSource) || !sender.hasPermission("uchat.cant-ignore." + (toignore instanceof Player ? ((Player) toignore).getName() : ((UCChannel) toignore).getName()));
}
 
Example 16
Source File: CommandClaimInfo.java    From GriefPrevention with MIT License 4 votes vote down vote up
private static Consumer<CommandSource> createClaimInfoConsumer(CommandSource src, Claim claim, String title) {
    GPClaim gpClaim = (GPClaim) claim;
    return info -> {
        switch (title) {
            case INHERIT_PARENT : 
                if (!claim.getParent().isPresent() || !src.hasPermission(GPPermissions.COMMAND_CLAIM_INHERIT)) {
                    return;
                }

                gpClaim.getInternalClaimData().setInheritParent(!gpClaim.getInternalClaimData().doesInheritParent());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                claim.getData().save();
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;
            case CLAIM_EXPIRATION :
                gpClaim.getInternalClaimData().setExpiration(!gpClaim.getInternalClaimData().allowExpiration());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case DENY_MESSAGES :
                gpClaim.getInternalClaimData().setDenyMessages(!gpClaim.getInternalClaimData().allowDenyMessages());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case FLAG_OVERRIDES :
                gpClaim.getInternalClaimData().setFlagOverrides(!gpClaim.getInternalClaimData().allowFlagOverrides());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case PVP_OVERRIDE :
                Tristate value = gpClaim.getInternalClaimData().getPvpOverride();
                if (value == Tristate.UNDEFINED) {
                    gpClaim.getInternalClaimData().setPvpOverride(Tristate.TRUE);
                } else if (value == Tristate.TRUE) {
                    gpClaim.getInternalClaimData().setPvpOverride(Tristate.FALSE);
                } else {
                    gpClaim.getInternalClaimData().setPvpOverride(Tristate.UNDEFINED);
                }
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case RESIZABLE :
                boolean resizable = gpClaim.getInternalClaimData().isResizable();
                gpClaim.getInternalClaimData().setResizable(!resizable);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case REQUIRES_CLAIM_BLOCKS :
                boolean requiresClaimBlocks = gpClaim.getInternalClaimData().requiresClaimBlocks();
                gpClaim.getInternalClaimData().setRequiresClaimBlocks(!requiresClaimBlocks);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case SIZE_RESTRICTIONS :
                boolean sizeRestrictions = gpClaim.getInternalClaimData().hasSizeRestrictions();
                gpClaim.getInternalClaimData().setSizeRestrictions(!sizeRestrictions);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case FOR_SALE :
                boolean forSale = gpClaim.getEconomyData().isForSale();
                gpClaim.getEconomyData().setForSale(!forSale);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;
            default:
        }
        executeAdminSettings(src, gpClaim);
    };
}
 
Example 17
Source File: PermissionWrapper.java    From UltimateCore with MIT License 4 votes vote down vote up
private void checkPermission(CommandSource source, CommandArgs args) throws ArgumentParseException {
    if (!source.hasPermission(this.permission)) {
        throw args.createError(Messages.getFormatted("core.nopermissions.subcommand"));
    }
}
 
Example 18
Source File: CommandHandlers.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public static void handleAddLeader(CommandSource src, String sVictim, Region r) {
    if (src instanceof Player) {
        Player p = (Player) src;
        r = RedProtect.get().rm.getTopRegion(p.getLocation(), CommandHandlers.class.getName());
        if (r == null) {
            RedProtect.get().lang.sendMessage(p, "cmdmanager.region.todo.that");
            return;
        }
    }

    if (RedProtect.get().ph.hasRegionPermLeader(src, "addleader", r)) {

        Player pVictim = null;
        if (RedProtect.get().getServer().getPlayer(sVictim).isPresent()) {
            pVictim = RedProtect.get().getServer().getPlayer(sVictim).get();
        }

        if ((pVictim == null || !pVictim.isOnline()) && !src.hasPermission("redprotect.command.admin.addleader")) {
            RedProtect.get().lang.sendMessage(src, RedProtect.get().lang.get("cmdmanager.noplayer.online").replace("{player}", sVictim));
            return;
        }

        if (!src.hasPermission("redprotect.command.admin.addleader")) {
            int claimLimit = RedProtect.get().ph.getPlayerClaimLimit(pVictim);
            int claimused = RedProtect.get().rm.getPlayerRegions(pVictim.getName(), pVictim.getWorld().getName());
            boolean claimUnlimited = RedProtect.get().ph.hasPerm(src, "redprotect.limits.claim.unlimited");
            if (claimused >= claimLimit && claimLimit >= 0 && !claimUnlimited) {
                RedProtect.get().lang.sendMessage(src, RedProtect.get().lang.get("cmdmanager.region.addleader.limit").replace("{player}", pVictim.getName()));
                return;
            }
        }

        if (!r.isLeader(sVictim)) {
            if (src.hasPermission("redprotect.command.admin.addleader")) {
                r.addLeader(sVictim);
                RedProtect.get().logger.addLog("(World " + r.getWorld() + ") Player " + src.getName() + " ADDED LEADER " + sVictim + " to region " + r.getName());
                RedProtect.get().lang.sendMessage(src, RedProtect.get().lang.get("general.color") + sVictim + " " + RedProtect.get().lang.get("cmdmanager.region.leader.added") + " " + r.getName());
                if (pVictim != null && pVictim.isOnline() && !pVictim.equals(src)) {
                    RedProtect.get().lang.sendMessage(pVictim, RedProtect.get().lang.get("cmdmanager.region.leader.youadded").replace("{region}", r.getName()) + " " + src.getName());
                }
                return;
            }

            RedProtect.get().lang.sendMessage(src, RedProtect.get().lang.get("cmdmanager.region.leader.yousendrequest").replace("{player}", pVictim.getName()));
            RedProtect.get().lang.sendMessage(pVictim, RedProtect.get().lang.get("cmdmanager.region.leader.sendrequestto").replace("{region}", r.getName()).replace("{player}", src.getName()));

            RedProtect.get().alWait.put(pVictim, r.getID() + "@" + src.getName());
            final Player pVictimf = pVictim;
            Sponge.getScheduler().createSyncExecutor(RedProtect.get().container).schedule(() -> {
                if (RedProtect.get().alWait.containsKey(pVictimf)) {
                    RedProtect.get().alWait.remove(pVictimf);
                    if (src instanceof Player && ((Player) src).isOnline()) {
                        RedProtect.get().lang.sendMessage(src, RedProtect.get().lang.get("cmdmanager.region.leader.requestexpired").replace("{player}", pVictimf.getName()));
                    }
                }
            }, RedProtect.get().config.configRoot().region_settings.leadership_request_time, TimeUnit.SECONDS);
        } else {
            RedProtect.get().lang.sendMessage(src, "&c" + sVictim + " " + RedProtect.get().lang.get("cmdmanager.region.leader.already"));
        }
    } else if (src instanceof Player) {
        RedProtect.get().lang.sendMessage(src, "no.permission");
    }
}
 
Example 19
Source File: CommandClaimInfo.java    From GriefDefender with MIT License 4 votes vote down vote up
private Consumer<CommandSource> createClaimInfoConsumer(CommandSource src, Claim claim, int titleId) {
    GDClaim gpClaim = (GDClaim) claim;
    return info -> {
        switch (titleId) {
            case INHERIT_PARENT : 
                if (!claim.getParent().isPresent() || !src.hasPermission(GDPermissions.COMMAND_CLAIM_INHERIT)) {
                    return;
                }

                gpClaim.getInternalClaimData().setInheritParent(!gpClaim.getInternalClaimData().doesInheritParent());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                claim.getData().save();
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;
            case CLAIM_EXPIRATION :
                gpClaim.getInternalClaimData().setExpiration(!gpClaim.getInternalClaimData().allowExpiration());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case DENY_MESSAGES :
                gpClaim.getInternalClaimData().setDenyMessages(!gpClaim.getInternalClaimData().allowDenyMessages());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;
            case FLAG_OVERRIDES :
                gpClaim.getInternalClaimData().setFlagOverrides(!gpClaim.getInternalClaimData().allowFlagOverrides());
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            /*case RAID_OVERRIDE :
                GDPermissionHolder holder = null;
                final GDPlayerData playerData = ((GDClaim) claim).getOwnerPlayerData();
                if (playerData == null) {
                    holder = GriefDefenderPlugin.DEFAULT_HOLDER;
                } else {
                    holder = playerData.getSubject();
                }
                final Boolean result = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Boolean.class), holder, Options.RAID, gpClaim);
                final Set<Context> contexts = new HashSet<>();
                contexts.add(claim.getContext());
                if (result) {
                    PermissionUtil.getInstance().setOptionValue(holder, Options.RAID.getPermission(), "false", contexts);
                } else {
                    PermissionUtil.getInstance().setOptionValue(holder, Options.RAID.getPermission(), "true", contexts);
                }
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;*/
            case RESIZABLE :
                boolean resizable = gpClaim.getInternalClaimData().isResizable();
                gpClaim.getInternalClaimData().setResizable(!resizable);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case REQUIRES_CLAIM_BLOCKS :
                boolean requiresClaimBlocks = gpClaim.getInternalClaimData().requiresClaimBlocks();
                gpClaim.getInternalClaimData().setRequiresClaimBlocks(!requiresClaimBlocks);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case SIZE_RESTRICTIONS :
                boolean sizeRestrictions = gpClaim.getInternalClaimData().hasSizeRestrictions();
                gpClaim.getInternalClaimData().setSizeRestrictions(!sizeRestrictions);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                break;
            case FOR_SALE :
                boolean forSale = gpClaim.getEconomyData().isForSale();
                gpClaim.getEconomyData().setForSale(!forSale);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;
            case IS_EXPIRED :
                boolean isExpired = gpClaim.getInternalClaimData().isExpired();
                gpClaim.getInternalClaimData().setExpired(!isExpired);
                gpClaim.getInternalClaimData().setRequiresSave(true);
                gpClaim.getClaimStorage().save();
                CommandHelper.executeCommand(src, "claiminfo", gpClaim.getUniqueId().toString());
                return;
            default:
        }
        executeAdminSettings(src, gpClaim);
    };
}
 
Example 20
Source File: LowCommandCallable.java    From UltimateCore with MIT License 2 votes vote down vote up
/**
 * Test whether this command can probably be executed by the given source.
 * <p>
 * If implementations are unsure if the command can be executed by
 * the source, {@code true} should be returned. Return values of this method
 * may be used to determine whether this command is listed in command
 * listings.</p>
 *
 * @param source The caller of the command
 * @return Whether permission is (probably) granted
 */
@Override
public boolean testPermission(CommandSource source) {
    return source.hasPermission(command.getPermission().get());
}