Java Code Examples for com.sk89q.minecraft.util.commands.CommandContext#hasFlag()

The following examples show how to use com.sk89q.minecraft.util.commands.CommandContext#hasFlag() . 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: AdminCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
    aliases = {"restart"},
    desc = "Queues a server restart after a certain amount of time",
    usage = "[seconds] - defaults to 30 seconds",
    flags = "f",
    min = 0,
    max = 1
)
@CommandPermissions("server.restart")
public void restart(CommandContext args, CommandSender sender) throws CommandException {
    // Countdown defers automatic restart, so don't allow excessively long times
    Duration countdown = TimeUtils.min(
        tc.oc.commons.bukkit.commands.CommandUtils.getDuration(args, 0, Duration.ofSeconds(30)),
        Duration.ofMinutes(5)
    );

    final Match match = CommandUtils.getMatch(sender);
    if(!match.canAbort() && !args.hasFlag('f')) {
        throw new CommandException(PGMTranslations.get().t("command.admin.restart.matchRunning", sender));
    }

    restartListener.queueRestart(match, countdown, "/restart command");
}
 
Example 2
Source File: ListCommand.java    From CardinalPGM with MIT License 6 votes vote down vote up
@Command(aliases = {"list"}, desc = "Lists all online players.", flags = "v")
public static void list(final CommandContext args, CommandSender sender) {
    boolean version = args.hasFlag('v');
    String result = ChatColor.GRAY + ChatConstant.MISC_ONLINE.asMessage().getMessage(ChatUtil.getLocale(sender)) +
            " (" + Bukkit.getOnlinePlayers().size() + "/" + Bukkit.getMaxPlayers() + "): " + ChatColor.RESET;
    for (Player player : Bukkit.getOnlinePlayers()) {
        result += player.getDisplayName();
        if (version) {
            result += ChatColor.GRAY + " (" + Protocols.getName(player.getProtocolVersion()) + ")";
        }
        result += ChatColor.RESET + ", ";
    }
    if (result.endsWith(", ")) {
        result = result.substring(0, result.length() - 2);
    }
    sender.sendMessage(result);
}
 
Example 3
Source File: MapSelectionCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"beginvote", "startvote"},
        desc = "Begins a map selection vote.",
        min = 0,
        max = 0,
        flags = "ct:"
)
@Console
@CommandPermissions("tourney.map.beginvote")
public void beginVote(CommandContext args, CommandSender sender) throws CommandException {
    if (!tourney.getState().equals(TourneyState.ENABLED_WAITING_FOR_READY)) {
        throw new CommandException("This match is not in a state that is eligible for map selection.");
    } else if (voteContext.voteInProgress()) {
        throw new CommandException("There is already a map selection vote in progress.");
    } else if (!args.hasFlag('c')) {
        throw new CommandException("Re-run command with -c to confirm. Map selection may not be ended pre-maturely.");
    }

    if (args.hasFlag('t')) {
        MapClassification classification = classificationManager.classificationFromSearch(args.getFlag('t'));
        if (classification == null) throw new CommandException("No classification matched query.");
        voteContext.startVote(Collections.singleton(classification));
    } else {
        voteContext.startVote(classificationManager.getClassifications());
    }
}
 
Example 4
Source File: TourneyCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"invalidate", "nosave", "norecord"},
        desc = "Indicates that the current match should not be saved to the database.",
        min = 0,
        max = 0,
        flags = "c"
)
@Console
@CommandPermissions("tourney.invalidate")
public static void invalidate(final CommandContext args, final CommandSender sender) throws CommandException {
    Tourney plugin = Tourney.get();
    if (!Arrays.asList(TourneyState.ENABLED_RUNNING, TourneyState.ENABLED_FINISHED).contains(plugin.getState())) {
        throw new CommandException("This match may not be invalidated at this time.");
    }

    if (plugin.isRecordQueued()) {
        if (args.hasFlag('c')) {
            plugin.setRecordQueued(false);
            sender.sendMessage(ChatColor.YELLOW + "Match successfully invalidated.");
        } else {
            throw new CommandException("Match is eligible for invalidation. Re-run command with -c to confirm. Invalidation may not be reversed.");
        }
    } else {
        throw new CommandException("This match is not queued to be recorded.");
    }
}
 
Example 5
Source File: ServerCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"gqueuerestart", "gqr"},
        usage = "[-c]",
        desc = "Shutdown the next time the server is inactive and empty",
        flags = "c",
        help = "The -c flag cancels a previously queued restart"
)
@CommandPermissions("bungeecord.command.restart")
public void queueRestart(final CommandContext args, final CommandSender sender) throws CommandException {
    if(restartManager == null) {
        throw new CommandException("Scheduled restarts are not enabled");
    } else {
        if(args.hasFlag('c')) {
            sender.sendMessage(new TextComponent("Restart cancelled"));
            restartManager.cancelRestart();
        } else {
            sender.sendMessage(new TextComponent("Restart queued"));
            restartManager.requestRestart("/gqr command by " + sender.getName());
        }
    }
}
 
Example 6
Source File: StartAndEndCommand.java    From CardinalPGM with MIT License 6 votes vote down vote up
@Command(aliases = {"end", "finish"}, desc = "Ends the match.", usage = "[team]", flags = "n")
@CommandPermissions("cardinal.match.end")
public static void end(CommandContext cmd, CommandSender sender) throws CommandException {
    if (!GameHandler.getGameHandler().getMatch().isRunning()) {
        throw new CommandException(ChatConstant.ERROR_NO_END.getMessage(ChatUtil.getLocale(sender)));
    }
    if (cmd.argsLength() > 0) {
        Optional<TeamModule> team = Teams.getTeamByName(cmd.getString(0));
        GameHandler.getGameHandler().getMatch().end(team.orNull());
    } else {
        if (cmd.hasFlag('n')) {
            GameHandler.getGameHandler().getMatch().end();
        } else {
            GameHandler.getGameHandler().getMatch().end(TimeLimit.getMatchWinner());
        }
    }
}
 
Example 7
Source File: SelectionCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
private Vector[] getChangesForEachDir(CommandContext args) {
    List<Vector> changes = new ArrayList<Vector>(6);
    int change = args.getInteger(0);

    if (!args.hasFlag('h')) {
        changes.add((new Vector(0, 1, 0)).multiply(change));
        changes.add((new Vector(0, -1, 0)).multiply(change));
    }

    if (!args.hasFlag('v')) {
        changes.add((new Vector(1, 0, 0)).multiply(change));
        changes.add((new Vector(-1, 0, 0)).multiply(change));
        changes.add((new Vector(0, 0, 1)).multiply(change));
        changes.add((new Vector(0, 0, -1)).multiply(change));
    }

    return changes.toArray(new Vector[0]);
}
 
Example 8
Source File: MapCommands.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Command(aliases = {"map", "mapinfo"}, flags = "lm:", desc = "Shows information about the currently playing map.")
public static void map(final CommandContext args, CommandSender sender) throws CommandException {
    LoadedMap mapInfo = args.hasFlag('m') ? RepositoryManager.get().getMap(args.getFlagInteger('m')) :
                    args.argsLength() == 0 ? GameHandler.getGameHandler().getMatch().getLoadedMap() :
                            CycleCommand.getMap(sender, args.getJoinedStrings(0));
    if (mapInfo == null) 
        throw new CommandException(ChatConstant.ERROR_NO_MAP_MATCH.getMessage(ChatUtil.getLocale(sender)));
    sender.sendMessage(Align.padMessage(mapInfo.toShortMessage(ChatColor.DARK_AQUA, args.hasFlag('l'), true), ChatColor.RED));
    sender.sendMessage(TITLE_FORM + ChatConstant.UI_MAP_OBJECTIVE.getMessage(ChatUtil.getLocale(sender)) + ": "
            + CONT_FORM + mapInfo.getObjective());
    sendContributors(sender, ChatConstant.UI_MAP_AUTHOR, ChatConstant.UI_MAP_AUTHORS, mapInfo.getAuthors());
    sendContributors(sender, ChatConstant.UI_MAP_CONTRIBUTORS, ChatConstant.UI_MAP_CONTRIBUTORS, mapInfo.getContributors());
    if (mapInfo.getRules().size() > 0) {
        sender.sendMessage(TITLE_FORM + ChatConstant.UI_MAP_RULES.getMessage(ChatUtil.getLocale(sender)) + ":");
        for (int i = 1; i <= mapInfo.getRules().size(); i++)
            sender.sendMessage(ChatColor.WHITE + "" + i + ") " + CONT_FORM + mapInfo.getRules().get(i - 1));
    }
    sender.sendMessage(TITLE_FORM + ChatConstant.UI_MAP_MAX.getMessage(ChatUtil.getLocale(sender)) + ": "
            + CONT_FORM + mapInfo.getMaxPlayers());
    if (args.hasFlag('l')) {
        Repository repo = GameHandler.getGameHandler().getRepositoryManager().getRepo(mapInfo);
        if (repo != null) {
            sender.sendMessage(TITLE_FORM + "Source: " + repo.toChatMessage(sender.isOp()));
            sender.sendMessage(TITLE_FORM + "Folder: " + CONT_FORM +
                    repo.getRoot().toURI().relativize(mapInfo.getFolder().toURI()).getPath());
        } else {
            sender.sendMessage(TITLE_FORM + "Source: " + CONT_FORM + "Unknown");
        }
    }
}
 
Example 9
Source File: RankCommands.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Command(aliases = {"info"}, desc = "View info about a certain rank.", min = 1, usage = "[rank]", flags = "a")
public static void info(final CommandContext args, CommandSender sender) throws CommandException {
    Rank rank = Rank.getRank(args.getString(0));
    if (rank == null)
        throw new CommandException(ChatConstant.ERROR_NO_RANK_MATCH.getMessage(ChatUtil.getLocale(sender)));
    sender.sendMessage(ChatColor.GOLD + ChatConstant.GENERIC_RANK_INFO.asMessage().getMessage(ChatUtil.getLocale(sender)) + ": ");
    sender.sendMessage(ChatColor.GRAY + " " + ChatConstant.MISC_NAME.asMessage().getMessage(ChatUtil.getLocale(sender)) + ": " + (rank.getFlair().equals("") ? "" : rank.getFlair() + " ") + ChatColor.GRAY + rank.getName());
    sender.sendMessage(ChatColor.GRAY + " " + ChatConstant.MISC_STAFF.asMessage().getMessage(ChatUtil.getLocale(sender)) + ": " + rank.isStaffRank());
    if (rank.isDefaultRank())
        sender.sendMessage(ChatColor.GRAY + " " + ChatConstant.MISC_DEFAULT.asMessage().getMessage(ChatUtil.getLocale(sender)) + ": " + rank.isDefaultRank());
    if (rank.getParent() != null)
        sender.sendMessage(ChatColor.GRAY + " " + ChatConstant.MISC_PARENT.asMessage().getMessage(ChatUtil.getLocale(sender)) + ": " + rank.getParent());
    StringBuilder members = new StringBuilder();
    for (Player player : Bukkit.getOnlinePlayers()) {
        if (rank.contains(player.getUniqueId()))
            members.append(Players.getName(player))
                    .append(ChatColor.RESET)
                    .append(", ");
    }
    if (members.length() > 2) sender.sendMessage(ChatColor.GRAY + " " + ChatConstant.UI_ONLINE.asMessage().getMessage(ChatUtil.getLocale(sender)) + " " + members.substring(0, members.length() - 2));
    if (args.hasFlag('a') && rank.getPermissions().size() > 0) {
        sender.sendMessage(ChatColor.GRAY + " " + ChatConstant.MISC_PERMISSIONS.asMessage().getMessage(ChatUtil.getLocale(sender)) + ":");
        for (String permission : rank.getPermissions()) {
            sender.sendMessage(ChatColor.GRAY + "  - " + permission);
        }
    }
}
 
Example 10
Source File: CycleCommand.java    From CardinalPGM with MIT License 5 votes vote down vote up
private static void processCycle(CommandContext cmd, CommandSender sender) throws CommandException {
    Match match = GameHandler.getGameHandler().getMatch();
    if ((match.isRunning() || match.isStarting()) && !cmd.hasFlag('f')) {
        throw new CommandException(ChatConstant.ERROR_CYCLE_DURING_MATCH.getMessage(ChatUtil.getLocale(sender)));
    } else if (match.isStarting()) {
        Countdown.stopCountdowns(match);
    } else if (match.isRunning()) {
        if (cmd.hasFlag('n')) GameHandler.getGameHandler().getMatch().end();
        else GameHandler.getGameHandler().getMatch().end(TimeLimit.getMatchWinner());
    }
}
 
Example 11
Source File: CycleCommand.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Command(aliases = {"setnext", "sn"}, desc = "Sets the next map.", usage = "[map]", flags = "m:")
@CommandPermissions("cardinal.match.setnext")
public static void setNext(final CommandContext cmd, CommandSender sender) throws CommandException {
    LoadedMap nextMap = cmd.hasFlag('m') ? RepositoryManager.get().getMap(cmd.getFlagInteger('m')) :
                    cmd.argsLength() > 0 ? getMap(sender, cmd.getJoinedStrings(0)) : null;
    if (nextMap == null) {
        throw new CommandException(ChatConstant.ERROR_NO_MAP_MATCH.getMessage(ChatUtil.getLocale(sender)));
    }
    setCycleMap(nextMap);
    sender.sendMessage(ChatColor.DARK_PURPLE + new LocalizedChatMessage(ChatConstant.GENERIC_MAP_SET, ChatColor.GOLD + nextMap.getName() + ChatColor.DARK_PURPLE).getMessage(ChatUtil.getLocale(sender)));
}
 
Example 12
Source File: CycleCommand.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Command(aliases = {"cycle"}, desc = "Cycles the world and loads a new world.", usage = "[time] [map]", flags = "fnm:")
@CommandPermissions("cardinal.match.cycle")
public static void cycle(final CommandContext cmd, CommandSender sender) throws CommandException {
    processCycle(cmd, sender);
    LoadedMap map = cmd.hasFlag('m') ? RepositoryManager.get().getMap(cmd.getFlagInteger('m')) :
            cmd.argsLength() > 1 ? getMap(sender, cmd.getJoinedStrings(1).replace(" -f", "").replace("-f ", "")) :
                    GameHandler.getGameHandler().getCycle().getMap();
    if (map == null)
        throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_NO_MAP_MATCH).getMessage(ChatUtil.getLocale(sender)));
    else setCycleMap(map);
    GameHandler.getGameHandler().getMatch().getModules().getModule(CycleTimer.class).startCountdown(cmd.getInteger(0, Config.cycleDefault));
}
 
Example 13
Source File: NavigationCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Helper function for /up and /ceil.
 *
 * @param args The {@link CommandContext} to extract the flags from.
 * @return true, if glass should always be put under the player
 */
private boolean getAlwaysGlass(CommandContext args) {
    final LocalConfiguration config = worldEdit.getConfiguration();

    final boolean forceFlight = args.hasFlag('f');
    final boolean forceGlass = args.hasFlag('g');

    return forceGlass || (config.navigationUseGlass && !forceFlight);
}
 
Example 14
Source File: NavigationCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"jumpto", "j"},
        usage = "[world,x,y,z]",
        desc = "Teleport to a location" +
        		"Flags:\n" + 
        		"  -f forces the specified position to be used",
        flags = "f",
        min = 0,
        max = 1
)
@CommandPermissions("worldedit.navigation.jumpto.command")
public void jumpTo(Player player, LocalSession session, CommandContext args) throws WorldEditException {
    WorldVector pos;
    if (args.argsLength() == 1) {
        String arg = args.getString(0);
        String[] split = arg.split(",");
        World world = FaweAPI.getWorld(split[0]);
        if (world != null && split.length == 4 && MathMan.isInteger(split[1]) && MathMan.isInteger(split[2]) && MathMan.isInteger(split[3])) {
            pos = new WorldVector((LocalWorld) world, Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]));
        } else {
            BBC.SELECTOR_INVALID_COORDINATES.send(player, args.getString(0));
            return;
        }
    } else {
        pos = player.getSolidBlockTrace(300);
    }
    if (pos != null) {
        if(args.hasFlag('f')) player.setPosition(pos); else player.findFreePosition(pos);
        BBC.POOF.send(player);
    } else {
        BBC.NO_BLOCK.send(player);
    }
}
 
Example 15
Source File: CardinalCommand.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Command(aliases = "cardinal", flags = "vru", desc = "Various functions related to Cardinal.", min = 0, max = 0)
public static void cardinal(final CommandContext cmd, CommandSender sender) throws CommandPermissionsException {
    if (cmd.hasFlag('v')) {
        sender.sendMessage(ChatColor.GOLD + ChatConstant.UI_VERSION.asMessage(new UnlocalizedChatMessage(Cardinal.getInstance().getDescription().getVersion())).getMessage(ChatUtil.getLocale(sender)));
        sender.sendMessage(ChatColor.GOLD + ChatConstant.UI_JAVA_VERSION.asMessage(new UnlocalizedChatMessage(System.getProperty("java.version"))).getMessage(ChatUtil.getLocale(sender)));
        if (System.getProperty("java.version").startsWith("1.7")) {
            sender.sendMessage(ChatColor.DARK_RED + ChatConstant.UI_JAVA_UPDATE.getMessage(ChatUtil.getLocale(sender)));
        }
        Bukkit.getScheduler().runTaskAsynchronously(Cardinal.getInstance(), UpdateHandler.getUpdateHandler().getNotificationTask(sender));
    }
    if (cmd.hasFlag('r')) {
        if (sender.hasPermission("cardinal.reload")) {
            Cardinal.getInstance().reloadConfig();
            sender.sendMessage(new UnlocalizedChatMessage(ChatColor.GREEN + "{0}", new LocalizedChatMessage(ChatConstant.GENERIC_CONFIG_RELOAD)).getMessage(sender instanceof Player ? ((Player) sender).getLocale() : Locale.getDefault().toString()));
            Cardinal.getInstance().registerRanks();
            sender.sendMessage(new UnlocalizedChatMessage(ChatColor.GREEN + "{0}", new LocalizedChatMessage(ChatConstant.GENERIC_RANKS_RELOAD)).getMessage(sender instanceof Player ? ((Player) sender).getLocale() : Locale.getDefault().toString()));
        } else {
            throw new CommandPermissionsException();
        }
    }
    if (cmd.hasFlag('u')) {
        if (sender.hasPermission("cardinal.update")) {
            Bukkit.getScheduler().runTaskAsynchronously(Cardinal.getInstance(), UpdateHandler.getUpdateHandler().getUpdateTask(sender));
        } else {
            throw new CommandPermissionsException();
        }
    }
}
 
Example 16
Source File: QueueCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"ping"},
    desc = "Send a Ping message to the direct exchange, -r to wait for a reply",
    usage = "<routing key> [-s | -f | -e]",
    flags = "sfe",
    min = 1,
    max = 1
)
public void ping(CommandContext args, CommandSender sender) throws CommandException {
    final String routingKey = args.getString(0);
    final Audience audience = audiences.get(sender);

    audience.sendMessage("ping " + routingKey);

    final Ping.ReplyWith replyWith;
    if(args.hasFlag('s')) {
        replyWith = Ping.ReplyWith.success;
    } else if(args.hasFlag('f')) {
        replyWith = Ping.ReplyWith.failure;
    } else if(args.hasFlag('e')) {
        replyWith = Ping.ReplyWith.exception;
    } else {
        replyWith = null;
    }

    if(replyWith == null) {
        exchange.publishAsync(new Ping(), routingKey);
    } else {
        final Transaction<Reply> transaction = transactions.request(new Ping(replyWith), routingKey);
        syncExecutor.callback(
            transaction,
            CommandFutureCallback.onSuccess(sender, args, reply -> {
                audience.sendMessage(reply.getClass().getSimpleName() + String.format(" (%.3fms)", transaction.elapsedTimeMillis()));
            })
        );
    }
}
 
Example 17
Source File: JoinCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = { "join" },
    desc = "Joins the current match",
    usage = "[team] - defaults to random",
    flags = "f",
    min = 0,
    max = -1
)
@CommandPermissions(JoinMatchModule.JOIN_PERMISSION)
public void join(CommandContext args, CommandSender sender) throws CommandException {
    MatchPlayer player = CommandUtils.senderToMatchPlayer(sender);
    Match match = player.getMatch();
    JoinMatchModule jmm = match.needMatchModule(JoinMatchModule.class);
    TeamMatchModule tmm = match.getMatchModule(TeamMatchModule.class);

    boolean force = sender.hasPermission("pgm.join.force") && args.hasFlag('f');
    Competitor chosenParty = null;

    if(args.argsLength() > 0) {
        if(args.getJoinedStrings(0).trim().toLowerCase().startsWith("obs")) {
            observe(args, sender);
            return;
        } else if(tmm != null) {
            // player wants to join a specific team
            chosenParty = tmm.bestFuzzyMatch(args.getJoinedStrings(0));
            if(chosenParty == null) throw new CommandException(PGMTranslations.get().t("command.teamNotFound", sender));
        }
    }

    jmm.requestJoin(player, force ? JoinMethod.FORCE : JoinMethod.USER, chosenParty);
}
 
Example 18
Source File: AdminCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"setnext", "sn"},
    desc = "Sets the next map.  Note that the rotation will go to this map then resume as normal.",
    usage = "[map name]",
    flags = "f",
    min = 1,
    max = -1
)
@CommandPermissions("pgm.next.set")
public List<String> setnext(CommandContext args, CommandSender sender) throws CommandException {
    final String mapName = args.argsLength() > 0 ? args.getJoinedStrings(0) : "";
    if(args.getSuggestionContext() != null) {
        return CommandUtils.completeMapName(mapName);
    }

    MatchManager mm = PGM.getMatchManager();
    boolean restartQueued = restartManager.isRestartRequested(ServerDoc.Restart.Priority.NORMAL);

    if (restartQueued && !args.hasFlag('f')) {
        throw new CommandException(PGMTranslations.get().t("command.admin.setNext.restartQueued", sender));
    }

    mm.setNextMap(CommandUtils.getMap(mapName, sender));
    if (restartQueued) {
        restartManager.cancelRestart();
        sender.sendMessage(ChatColor.GREEN + PGMTranslations.get().t("command.admin.cancelRestart.restartUnqueued", sender));
    }
    sender.sendMessage(ChatColor.DARK_PURPLE + PGMTranslations.get().t("command.admin.set.success", sender, ChatColor.GOLD + mm.getNextMap().getInfo().name + ChatColor.DARK_PURPLE));
    return null;
}
 
Example 19
Source File: NicknameCommands.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Command(aliases = {"nick" },
         usage = "list | show [player] | set <nickname> [player] | clear [player] | <nickname> [player]",
         desc = "Show, set, or clear a nickname for yourself or another player. " +
                "Changes will take effect the next time the player " +
                "connects to the server. The -i option makes the change " +
                "visible immediately.",
         flags = "i",
         min = 0,
         max = 3)
@CommandPermissions(PERMISSION)
public void nick(final CommandContext args, final CommandSender sender) throws CommandException {
    if(!config.enabled()) {
        throw new CommandException(Translations.get().t("command.nick.notEnabled", sender));
    }

    final boolean immediate = args.hasFlag('i');

    if(args.argsLength() == 0) {
        show(sender, null);
    } else {
        final String arg = args.getString(0);
        switch(arg) {
            case "list":
                list(sender);
                break;

            case "show":
                show(sender, args.getString(1, null));
                break;

            case "set":
                if(args.argsLength() < 2) CommandUtils.notEnoughArguments(sender);
                set(sender, args.getString(1), args.getString(2, null), immediate);
                break;

            case "clear":
                set(sender, null, args.getString(1, null), immediate);
                break;

            default:
                set(sender, arg, args.getString(1, null), immediate);
                break;
        }
    }
}
 
Example 20
Source File: MapDevelopmentCommands.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Command(
    aliases = {"mapfeatures", "mapf"},
    desc = "Lists all map features by ID and type",
    usage = "[-a(nonymous)] [-v(erbose)] [-l(ocations)] [-t type] [-i id]",
    flags = "avlt:i:",
    min = 0,
    max = 0
)
@CommandPermissions(Permissions.MAPDEV)
public void mapFeaturesCommand(CommandContext args, CommandSender sender) throws CommandException {
    final PGMMap map = tc.oc.pgm.commands.CommandUtils.getMatch(sender).getMap();
    final boolean verbose = args.hasFlag('v');
    final boolean locate = args.hasFlag('l');
    final boolean anonymous = args.hasFlag('a');
    final Optional<String> typeFilter = CommandUtils.flag(args, 't').map(String::toLowerCase);
    final Optional<String> idFilter = CommandUtils.flag(args, 'i').map(String::toLowerCase);

    Stream<? extends FeatureDefinition> features = map.getContext().features().all();
    if(typeFilter.isPresent()) {
        features = features.filter(f -> f.inspectType().toLowerCase().contains(typeFilter.get()));
    }
    if(idFilter.isPresent()) {
        features = features.filter(f -> f instanceof FeatureProxy &&
                                        ((FeatureProxy) f).getId().toLowerCase().contains(idFilter.get()));
    } else if(!anonymous) {
        features = features.filter(f -> f instanceof FeatureProxy);
    }

    features.forEach(feature -> {
        final Component c = new Component(feature.inspectType(), ChatColor.BLUE);

        feature.inspectIdentity().ifPresent(id -> c.extra(" ").extra(new Component(id, ChatColor.YELLOW)));

        if(locate) {
            final Element element = map.getContext().features().definitionNode(feature);
            if(element != null) {
                c.extra(" ").extra(new Component(new Node(element).describeWithLocation(), ChatColor.DARK_AQUA));
            }
        }

        sender.sendMessage(c);

        if(verbose) {
            feature.inspect(new MultiLineTextInspector(), Inspection.defaults())
                   .forEach(line -> sender.sendMessage(new Component("  " + BukkitUtils.escapeColors(line), ChatColor.GOLD)));
        }
    });
}