Skip to content

Real World Examples

TehBrian edited this page Feb 28, 2019 · 7 revisions

Real Examples

For a complete example Bukkit Plugin that demonstrates most ACF Features, see ACFExample

But a rough overview of the style/syntax in a realistic use case (this is EMC code):

Ignore ResidenceBaseCommand/EmpireBaseCommand - it extends BaseCommand with some additional stuff.

ResidenceCommand

@CommandAlias("res|residence|resadmin")
public class ResidenceCommand extends ResidenceBaseCommand {

    @Default
    @Subcommand("list")
    @Syntax("<+tag> [page] or [page]")
    @CommandCompletion("@residencelist")
    @Description("Lists all of your or another players residences.")
    public static void onList(Player player, String[] args) {
        if (args.length == 0) {
            EmpireUser user = EmpireUser.getUser(player);

            Util.sendMsg(player, "&bYou currently have &a" + user.numRes +
                "&b/&a" + user.maxRes + "&b Residences.");

            Residences.listGlobalResidences(player);
        } else {
            if (args[0].startsWith("+")) {
                int page = (args.length == 2 && NumUtil.isInteger(args[1])) ? Integer.parseInt(args[1]) : 1;
                TagManager.listTaggedResidences(player, args[0].substring(1), page);
            } else {
                Residences.listGlobalResidences(player, args[0]);
            }
        }
    }

    @HelpCommand
    public static void onHelp(CommandSender sender, CommandHelp help) {
        sendMsg(sender, heading("Residences Help"));
        help.showHelp();
    }

    @Subcommand("reset")
    @Description("DANGER: Destroys all buildings on a residence and resets permissions.")
    public static void onReset(Player player, @Flags("owner,top,town") Residence res) {
        if (!"town".equals(res.getWorld().getName()) || res.getAddress() < 100) {
            Log.severe(player.getName() + " Tried to reset " + res.getName());
            Util.sendMsg(player, ResidenceLang.HORRIBLE_ERROR);
            return;
        }

        Residences.residenceReset(player, res);
    }

    @Subcommand("alias add")
    @CommandPermission("residence.admin")
    public static void onAliasAdd(Player player, Residence res, String alias) {
        alias = alias.toLowerCase();
        if (res.getAliases().contains(alias)) {
            Util.sendMsg(player, "&cThis residence already has the alias " + alias);
            return;
        }
        Residence testRes = Residences.getResidence(alias);
        if (testRes != null) {
            Util.sendMsg(player, "&cThere is already a residence with this name/alias: " + testRes.getFullName());
            return;
        }
        res.getAliases().add(alias);
        ResidenceStore.aliasMap.put(alias, res);
        Util.sendMsg(player, "&aAdded the alias &f" + alias + " &ato the residence: &f" + res.getFullName());
    }

    @Subcommand("alias remove")
    @CommandPermission("residence.admin")
    public static void onFeatureRemove(Player player, Residence res, String alias) {
        alias = alias.toLowerCase();
        if (!res.getAliases().contains(alias)) {
            Util.sendMsg(player, "&cThis residence does not have the alias " + alias);
            return;
        }
        res.getAliases().remove(alias);
        ResidenceStore.aliasMap.remove(alias);
        Util.sendMsg(player, "&aRemoved the alias " + alias + " from the residence: " + res.getFullName());
    }


    @Subcommand("info")
    @Description("Displays information about a residence")
    public static void onResInfo(Player player, Residence res) {
        res.printAreaInfo(player);
    }

ResidencePermissionCommand

@CommandAlias("res|residence|resadmin")
public class ResidencePermissionCommand extends ResidenceBaseCommand {

    @Subcommand("set")
    @CommandCompletion("@flags @flagstates")
    @Description("Sets residence wide permissions. Use with caution with dangerous permissions")
    public void onResFlagSet(Player player, @Flags("admin") Residence res, String flag, @Values("@flagstates") String state) {
        res.getPermissions().setFlag(player, flag, state, resadmin);
    }

    @Subcommand("cset|set")
    @Description("Sets residence wide permissions, using a chest style interface. Use with caution with dangerous permissions")
    public void onResChestFlagSet(Player player, @Flags("admin") Residence res) {
        InventoryUI.open(player, new AreaPermsManageInterface(res, resadmin));
    }

    @Subcommand("cgset|gset")
    @Description("Sets residence permissions for a residence group (all players in the group get the permissions), using a chest style interface")
    public void onResChestGFlagSet(Player player, @Flags("admin") Residence res, ResidenceFlagGroup group) {
        InventoryUI.open(player, new GroupPermManageInterface(group, res, resadmin));
    }

    @Subcommand("gset")
    @Description("Sets residence permissions for a residence group (all players in the group get the permissions)")
    public void onResFlagGSet(Player player, @Flags("admin") Residence res, ResidenceFlagGroup group, String flag, @Values("@flagstates") String state) {
        res.getPermissions().setPlayerFlag(player, group.getName(), flag, state, resadmin, false);
    }

    @Subcommand("cpset|pset")
    @CommandCompletion("@allplayers:30")
    @Description("Sets an individual players permissions on a residence, using a chest style interface")
    public void onResChestPFlagSet(Player player, @Flags("admin") Residence res, EmpireUser user) {
        InventoryUI.open(player, new PlayerPermsManageInterface(user.name, user.userId, res, resadmin));
    }

    @Subcommand("pset")
    @CommandCompletion("@allplayers:30 @flags @flagstates")
    @Description("Sets an individual players permissions on a residence")
    public void onResFlagPSet(Player player, @Flags("admin") Residence res, EmpireUser[] users, String flag, @Values("@flagstates") String state) {
        res.getPermissions().setPlayerFlag(player, Stream.of(users).map(EmpireUser::getName).collect(Collectors.joining(",")), flag, state, resadmin, true);
    }

    @Subcommand("mirror")
    @Description("Mirrors permissions from one residence to another")
    public static void onResFlagMirror(Player player, @Flags("admin,verbose") Residence dest, @Flags("admin,verbose") Residence src) {
        if (src.equals(dest)) {
            SneakyThrow.sneaky(new InvalidCommandArgument("Source and destination residence can not be the same"));
        }
        Residences.mirrorPerms(player, src, dest);
    }
}

ResidenceAdminCommand

@CommandAlias("res|residence|resadmin")
@CommandPermission("residence.admin")
public class ResidenceAdminCommand extends ResidenceBaseCommand {

    @Subcommand("list server")
    @Syntax("[player] [page]")
    public static void onServerList(Player player, String[] args) {
        if (args.length == 0) {
            Residences.listResidences(player);
        } else if (args.length == 1) {
            if (NumUtil.isInteger(args[0])) {
                int page = Integer.parseInt(args[0]);
                Residences.listResidences(player, page);
            } else {
                Residences.listResidences(player, args[0]);
            }
        } else if (args.length == 2) {
            int page = NumUtil.isInteger(args[1]) ? Integer.parseInt(args[1]) : 1;
            Residences.listResidences(player, args[0], page);
        }
    }

    @Subcommand("list all")
    public static void onListAll(Player player, @Default("1") Integer page) {
        Residences.listAllResidences(player, page);
    }

    @Subcommand("save")
    public static void onResSave(@Optional String worldName) {
        if (worldName == null) {
            ResidenceManager.save();
        } else {
            World world = Bukkit.getWorld(worldName);
            if (world == null) {
                return;
            }
            ResidenceManager.saveWorld(world);
        }
    }

    @Subcommand("create")
    public void onResCreate(Player player, CuboidSelection selection, @Single String name) {
        ResidenceManager.addResidence(player, name,
            WorldEditHelper.getMinLoc(selection),
            WorldEditHelper.getMaxLoc(selection));
    }
}

GroupCommand

@CommandAlias("group|gr")
public class GroupCommand extends EmpireBaseCommand {
    @HelpCommand
    public void doHelp(CommandSender sender, CommandHelp help) {
        sendMsg(sender, heading("Groups Help"));
        help.showHelp();
    }

    @PreCommand
    public boolean preCommand(CommandSender sender, String[] args) {
        if (Games.isGames() && sender instanceof Player) {
            Player player = (Player) sender;
            if (!UserUtil.isSrStaff(player) && Games.checkDisabledCommand(player)) {
                return true;
            }
        }
        return false;
    }
    
    @Subcommand("join|j")
    @CommandAlias("join")
    public void onJoin(Player player) {
        Groups.acceptInvite(player);
    }

    @CommandPermission("empire.staff.srstaff")
    @Subcommand("forceleave")
    @CommandCompletion("@players")
    public void onForceLeave(CommandSender player, OnlinePlayer leaver, @Flags("arg=leaver") Group group) {
        group.removePlayer(leaver.getPlayer());
    }

    @CommandPermission("empire.staff.srstaff")
    @Subcommand("forcejoin")
    @CommandCompletion("@players @players")
    public void onForceJoin(CommandSender sender, OnlinePlayer toJoin, @Flags("create,arg=toJoin") Group group, @Optional OnlinePlayer joiner) {
        Player player = joiner != null ? joiner.getPlayer() : sender instanceof Player ? (Player) sender : null;
        if (player != null) {
            group.addPlayer(player);
        }
    }

    @CommandPermission("empire.staff.srstaff")
    @Subcommand("forcejoinnear")
    public void onForceJoinNear(Player player, Integer radius, @Optional OnlinePlayer toJoin) {
        Player inviter = toJoin != null ? toJoin.getPlayer() : player;
        final Group group = Groups.getOrCreateGroup(inviter);
        final int[] count = {0};
        player.getNearbyEntities(radius, radius, radius).forEach((e) -> {
            if (e instanceof Player && !e.equals(player) && !group.hasMember((Player) e)) {
                count[0]++;
                Util.sendMsg(e, "&aYou've been forced to join a group by staff.");
                group.addPlayer((Player) e);
            }
        });
        Util.sendMsg(player, "&aForced " + count[0] + " people to join.");
    }

    @Subcommand("pvp")
    public void onPvP(Player player, @Flags("leader") Group group) {
        group.togglePvP();
    }

    @Subcommand("blockbreak|bb")
    public void onBlockBreak(Player player, @Flags("leader") Group group) {
        group.toggleBlockBreak();
    }

    @Subcommand("buildmode|bm")
    @CommandCompletion("@allplayers:90")
    public void onBuildMode(Player player, @Flags("leader") Group group, @Optional EmpireUser owner) {
        group.toggleBuildMode();
    }

    @Subcommand("leaderloot")
    @CommandPermission("empire.staff.mod")
    public void onLeaderLoot(Player player, @Flags("leader") Group group) {
        group.toggleLeaderLoot();
    }

    @Subcommand("invitenear|invnear")
    @CommandAlias("invitenear|invnear|ginvnear")
    @Syntax("[radius=32] &e- Invite Nearby Players to the group.")
    public void onInviteNear(Player player, @Default("32") Integer radius) {
        int maxRadius = UserUtil.isModerator(player) ? 256 : 64;
        radius = !UserUtil.isSrStaff(player) ? Math.min(maxRadius, radius) : radius;
        List<String> names = player.getNearbyEntities(radius, Math.min(128, radius), radius)
            .stream().filter((e) -> e instanceof Player && !UserUtil.isVanished((Player) e))
            .map(CommandSender::getName)
            .collect(Collectors.toList());
        Groups.invitePlayers(player, names);
    }

    @Subcommand("invite|inv")
    @CommandAlias("invite|inv|ginv")
    @CommandCompletion("@players")
    @Syntax("<name> [name2] [name3] &e- Invite Players to the group.")
    public void onInvite(Player player, String[] names) {
        Groups.invitePlayers(player, names);
    }

    @Subcommand("kick|gkick")
    @CommandAlias("gkick")
    @CommandCompletion("@groupmembers")
    @Syntax("<player> &e- Kick Player from the group.")
    public void onKick(Player player, @Flags("leader") Group group, OnlinePlayer toKick) {
        group.kickPlayer(player, toKick.getPlayer());
    }
}

Empires (Completions/Context)

public class Empires {

    public static void initialize() {
        registerCommandContexts();
        registerCommandCompletions();
        EmpirePlugin.commandManager.getCommandReplacements().addReplacement("empirecommand", "empire|empires|emp|guild|clan|e|towny");
        new EmpireCommand();
        new EmpireRoleManagementCommand();
        new EmpireBankCommand();
    }
    private static void registerCommandCompletions() {
        CommandCompletions<BukkitCommandCompletionContext> commandCompletions = EmpirePlugin.commandManager.getCommandCompletions();
        commandCompletions.registerAsyncCompletion("invitedempires", c -> {
            CommandSender sender = c.getSender();
            if (sender instanceof Player) {
                Player player = (Player) sender;
                EmpireUser user = player.getUser();
                return getInvitesTags(user, false);
            }
            return null;
        });
        commandCompletions.registerAsyncCompletion("empires", c -> {
            CommandSender sender = c.getSender();
            if (sender instanceof Player) {
                Player player = (Player) sender;
                EmpireUser user = player.getUser();

                return user
                    .extended()
                    .getEmpires()
                    .stream()
                    .map(Empire::getTag)
                    .collect(Collectors.toList());
            }
            return null;
        });

        commandCompletions.registerCompletion("empiremembers", c -> {
            CommandSender sender = c.getSender();
            if (sender instanceof Player) {
                Empire contextValue = c.getContextValue(Empire.class);
                if (contextValue != null) {
                    return contextValue.getMembers().values().stream().map(EmpireMember::getName).collect(Collectors.toList());
                }
            }
            return null;
        });

        commandCompletions.registerCompletion("empireroles", c -> {
            CommandSender sender = c.getSender();
            if (sender instanceof Player) {
                Empire contextValue = c.getContextValue(Empire.class);
                if (contextValue != null) {
                    return contextValue.getRoles().values().stream().map(EmpireRole::getName).collect(Collectors.toList());
                }
            }
            return null;
        });
        commandCompletions.registerAsyncCompletion("empireroleperms", c -> Util.enumNames(EmpireRolePerm.values()));
    }

    private static void registerCommandContexts() {
        CommandContexts<BukkitCommandExecutionContext> commandContexts = EmpirePlugin.commandManager.getCommandContexts();
        commandContexts.registerContext(Empire.class, c -> {
            String tag = c.popFirstArg();
            CommandSender sender = c.getSender();

            Empire empire = Empires.getByNameOrTag(tag);
            if (empire == null) {
                throw new InvalidCommandArgument("Could not find an empire with that name or tag.");
            }
            if (sender instanceof Player) {
                Player player = (Player) sender;
                EmpireUser user = player.getUser();
                if (!c.hasFlag("any") && !empire.hasMember(user)) {
                    throw new InvalidCommandArgument("You are not a member of that Empire");
                }
                String perm = c.getFlagValue("perm", (String) null);
                if (perm != null) {
                    EmpireRolePerm rolePerm = Util.getEnumFromName(EmpireRolePerm.values(), perm);
                    if (rolePerm == null) {
                        Log.exception("Command requires an invalid Empire permission name: " + perm);
                        throw new InvalidCommandArgument("Alert Dev Team that this command requires an invalid permission.");
                    }
                    if (!empire.doesPlayerHavePerm(player, rolePerm)) {
                        throw new InvalidCommandArgument("You do not have permission to execute this command for this Empire. You need the " + perm + " permission.");
                    }
                }
            }
            return empire;
        });

        commandContexts.registerContext(EmpireMember.class, c -> {
            String who = c.popFirstArg();
            Empire empire = (Empire) c.getResolvedArg(Empire.class);
            if (empire == null) {
                Log.severe("Could not get Empire from resolved context for " + who);
                throw new InvalidCommandArgument("Unexpected error happened resolving Empire, staff have been notified.", false);
            }
            EmpireUser user = EmpireUser.getUser(who);
            if (user == null) {
                throw new InvalidCommandArgument("Could not find a user by the name " + who);
            }
            EmpireMember member = empire.getMember(user);
            if (member == null) {
                throw new InvalidCommandArgument("That player is not a member of this Empire.");
            }

            return member;
        });

        commandContexts.registerContext(EmpireRole.class, c -> {
            String roleName = c.popFirstArg();
            Empire empire = (Empire) c.getResolvedArg(Empire.class);
            if (empire == null) {
                Log.severe("Could not get Empire from resolved context for " + roleName);
                throw new InvalidCommandArgument("Unexpected error happened resolving Empire, staff have been notified.", false);
            }

            for (EmpireRole role : empire.getRoles().values()) {
                if (role.getName().equalsIgnoreCase(roleName)) {
                    return role;
                }
            }
            throw new InvalidCommandArgument(EmpireLang.CAN_NOT_FIND_ROLE, false);
        });
    }
}

EmpireRoleManagementCommand

@CommandAlias("%empirecommand")
@Subcommand("roles|role|r")
public class EmpireRoleManagementCommand extends EmpireBaseCommand {

    @Default
    @CommandCompletion("@empires")
    @Description("Show the current role assignments for an Empire")
    public static void onRoles(Player player, @Flags("perm=ADMIN") Empire empire) {
        EmpirePlugin
            .newChain()
            .async(() -> {
                Util.sendMsg(player, Formatting.heading(empire.getTag() + "'s Roles"));
                empire.getRoles().values().forEach(role -> {
                    Util.sendMsg(player, "&b  - &a" + role.getName() + (role.getDesc() != null ? " &6[" + role.getDesc() + "]" : ""));
                    Util.sendMsg(player, "&b      # Perms: &a"
                        + role.getEffectivePermission()
                              .stream()
                              .map(perm -> "&e" + perm.name())
                              .collect(Collectors.joining("&a,"))
                    );
                });
            })
            .execute();
    }

    @Subcommand("list|l")
    @CommandCompletion("@empires")
    @Description("Show the current role assignments for an Empire")
    public void onRolesList(Player player, @Flags("perm=ADMIN") Empire empire) {
        onRoles(player, empire);
    }

    @Subcommand("add|new")
    @CommandCompletion("@empires")
    @Description("Adds a new role to give a different set of permissions")
    public void onRoleAdd(Player player, @Flags("perm=ADMIN") Empire empire, String roleName, String roleDesc) {
        empire.addRole(player, roleName, roleDesc);
    }

    @Subcommand("del|delete|rm|remove")
    @CommandCompletion("@empires @empireroles")
    @Description("Deletes a role, removing it from everyone")
    public void onRoleDel(Player player, @Flags("perm=ADMIN") Empire empire, EmpireRole role) {
        empire.deleteRole(player, role);
    }

    @Subcommand("addperm|permadd|addp")
    @CommandCompletion("@empires @empireroles @empireroleperms")
    @Description("Adds a permission to a role")
    public void onRolePermAdd(Player player, @Flags("perm=ADMIN") Empire empire, EmpireRole role, EmpireRolePerm perm) {
        empire.addRolePermission(player, role, perm);
    }

    @Subcommand("delperm|rmperm|permdel|permrm|delp|rmp")
    @CommandCompletion("@empires @empireroles @empireroleperms")
    @Description("Removes a permission from a role")
    public void onRolePermDel(Player player, @Flags("perm=ADMIN") Empire empire, EmpireRole role, EmpireRolePerm perm) {
        empire.removeRolePermission(player, role, perm);
    }

    @Subcommand("rename|ren")
    @CommandCompletion("@empires @empireroles")
    @Description("Renames a role")
    public void onRoleRename(Player player, @Flags("perm=ADMIN") Empire empire, EmpireRole role, String newName) {
        empire.renameRole(player, role, newName, true);
    }

    @Subcommand("desc|description")
    @CommandCompletion("@empires @empireroles")
    @Description("Changes the description of what a role is for")
    public void onRoleDescription(Player player, @Flags("perm=ADMIN") Empire empire, EmpireRole role, String desc) {
        empire.renameRole(player, role, desc, true);
    }

    @Subcommand("assign|ass|a")
    @CommandCompletion("@empires @empiremembers @empireroles")
    @Description("Assigns a player a new role. Does not remove previous roles")
    public void onRoleAssign(Player player, @Flags("perm=ADMIN") Empire empire, EmpireMember member, EmpireRole role) {
        empire.assignRole(player, member, role);
    }

    @Subcommand("unassign|unass|ua")
    @CommandCompletion("@empires @empiremembers @empireroles")
    @Description("Removes a role from a player, removing any permissions it was giving them unless another role also gives it.")
    public void onRoleUnassign(Player player, @Flags("perm=ADMIN") Empire empire, EmpireMember member, EmpireRole role) {
        empire.unassignRole(player, member, role);
    }
}