Search in sources :

Example 1 with ConditionFailedException

use of co.aikar.commands.ConditionFailedException in project commands by aikar.

the class ACFExample method registerCommands.

private void registerCommands() {
    // 1: Create Command Manager for your respective platform
    commandManager = new PaperCommandManager(this);
    // enable brigadier integration for paper servers
    commandManager.enableUnstableAPI("brigadier");
    // optional: enable unstable api to use help
    commandManager.enableUnstableAPI("help");
    // 2: Setup some replacement values that may be used inside of the annotations dynamically.
    commandManager.getCommandReplacements().addReplacements(// key - value
    "test", "foobar", // key - demonstrate that % is ignored  - value
    "%foo", "barbaz");
    // Another replacement for piped values
    commandManager.getCommandReplacements().addReplacement("testcmd", "test4|foobar|barbaz");
    // 3: Register Custom Command Contexts
    commandManager.getCommandContexts().registerContext(/* The class of the object to resolve*/
    SomeObject.class, /* A resolver method - Placed the resolver in its own class for organizational purposes */
    SomeObject.getContextResolver());
    // 4: Register Command Completions - this will be accessible with @CommandCompletion("@test")
    commandManager.getCommandCompletions().registerAsyncCompletion("test", c -> Arrays.asList("foo123", "bar123", "baz123"));
    // 5: Register Command Conditions
    commandManager.getCommandConditions().addCondition(SomeObject.class, "limits", (c, exec, value) -> {
        if (value == null) {
            return;
        }
        if (c.hasConfig("min") && c.getConfigValue("min", 0) > value.getValue()) {
            throw new ConditionFailedException("Min value must be " + c.getConfigValue("min", 0));
        }
        if (c.hasConfig("max") && c.getConfigValue("max", 3) < value.getValue()) {
            throw new ConditionFailedException("Max value must be " + c.getConfigValue("max", 3));
        }
    });
    // 6: (Optionally) Register dependencies - Dependencies can be injected into fields of command classes by
    // marking them with @Dependency. Some classes, like your Plugin, are already registered by default.
    SomeHandler someHandler = new SomeHandler();
    someHandler.setSomeField("Secret");
    commandManager.registerDependency(SomeHandler.class, someHandler);
    commandManager.registerDependency(String.class, "Test3");
    commandManager.registerDependency(String.class, "test", "Test");
    commandManager.registerDependency(String.class, "test2", "Test2");
    // 7: Register your commands - This first command demonstrates adding an exception handler to that command
    commandManager.registerCommand(new SomeCommand().setExceptionHandler((command, registeredCommand, sender, args, t) -> {
        sender.sendMessage(MessageType.ERROR, MessageKeys.ERROR_GENERIC_LOGGED);
        // mark as handeled, default message will not be send to sender
        return true;
    }));
    // 8: Register an additional command. This one happens to share the same CommandAlias as the previous command
    // This means it simply registers additional sub commands under the same command, but organized into separate
    // Classes (Maybe different permission sets)
    commandManager.registerCommand(new SomeCommand_ExtraSubs());
    commandManager.registerCommand(new SomeOtherCommand());
    // 9: Register default exception handler for any command that doesn't supply its own
    commandManager.setDefaultExceptionHandler((command, registeredCommand, sender, args, t) -> {
        getLogger().warning("Error occurred while executing command " + command.getName());
        // mark as unhandeled, sender will see default message
        return false;
    });
    // test command for brigadier
    commandManager.getCommandCompletions().registerAsyncCompletion("someobject", c -> Arrays.asList("1", "2", "3", "4", "5"));
    commandManager.registerCommand(new BrigadierTest());
}
Also used : PaperCommandManager(co.aikar.commands.PaperCommandManager) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) Arrays(java.util.Arrays) MessageKeys(co.aikar.commands.MessageKeys) ConditionFailedException(co.aikar.commands.ConditionFailedException) PaperBrigadierManager(co.aikar.commands.PaperBrigadierManager) MessageType(co.aikar.commands.MessageType) ConditionFailedException(co.aikar.commands.ConditionFailedException) PaperCommandManager(co.aikar.commands.PaperCommandManager)

Example 2 with ConditionFailedException

use of co.aikar.commands.ConditionFailedException in project RoseStacker by Rosewood-Development.

the class CommandManager method reload.

@Override
public void reload() {
    LocaleManager localeManager = this.rosePlugin.getManager(LocaleManager.class);
    ConversionManager conversionManager = this.rosePlugin.getManager(ConversionManager.class);
    StackSettingManager stackSettingManager = this.rosePlugin.getManager(StackSettingManager.class);
    // Load custom message strings
    Map<String, String> acfCoreMessages = localeManager.getAcfCoreMessages();
    Map<String, String> acfMinecraftMessages = localeManager.getAcfMinecraftMessages();
    for (Entry<String, String> entry : acfCoreMessages.entrySet()) this.commandManager.getLocales().addMessage(Locale.ENGLISH, MessageKey.of("acf-core." + entry.getKey()), HexUtils.colorify(localeManager.getLocaleMessage("prefix") + entry.getValue()));
    for (Entry<String, String> entry : acfMinecraftMessages.entrySet()) this.commandManager.getLocales().addMessage(Locale.ENGLISH, MessageKey.of("acf-minecraft." + entry.getKey()), HexUtils.colorify(localeManager.getLocaleMessage("prefix") + entry.getValue()));
    CommandCompletions<BukkitCommandCompletionContext> completions = this.commandManager.getCommandCompletions();
    completions.registerStaticCompletion("stackableBlockMaterial", () -> stackSettingManager.getStackableBlockTypes().stream().map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("spawnableSpawnerEntityType", () -> stackSettingManager.getStackableSpawnerTypes().stream().map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("spawnableEggEntityType", () -> stackSettingManager.getStackableEntityTypes().stream().filter(x -> {
        EntityStackSettings stackSettings = stackSettingManager.getEntityStackSettings(x);
        return stackSettings.getEntityTypeData().getSpawnEggMaterial() != null;
    }).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("blockStackAmounts", ctx -> {
        Material blockType = ctx.getContextValue(Material.class);
        if (blockType == null)
            return Collections.emptyList();
        BlockStackSettings blockStackSettings = stackSettingManager.getBlockStackSettings(blockType);
        int maxStackAmount = blockStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerAsyncCompletion("spawnerStackAmounts", ctx -> {
        EntityType entityType = ctx.getContextValue(EntityType.class);
        if (entityType == null)
            return Collections.emptySet();
        SpawnerStackSettings spawnerStackSettings = stackSettingManager.getSpawnerStackSettings(entityType);
        int maxStackAmount = spawnerStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerAsyncCompletion("entityStackAmounts", ctx -> {
        EntityType entityType = ctx.getContextValue(EntityType.class);
        if (entityType == null)
            return Collections.emptySet();
        EntityStackSettings entityStackSettings = stackSettingManager.getEntityStackSettings(entityType);
        int maxStackAmount = entityStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerStaticCompletion("giveAmounts", () -> IntStream.rangeClosed(1, 5).mapToObj(String::valueOf).collect(Collectors.toList()));
    completions.registerStaticCompletion("clearallType", () -> Stream.of(ClearallType.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("stackType", () -> Stream.of(StackType.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("conversionType", ctx -> conversionManager.getEnabledConverters().stream().map(Enum::name).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("conversionEnabledType", ctx -> conversionManager.getEnabledHandlers().stream().map(ConversionHandler::getRequiredDataStackType).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("translationLocales", ctx -> localeManager.getPossibleTranslationLocales());
    this.commandManager.getCommandConditions().addCondition(int.class, "limits", (c, exec, value) -> {
        if (value == null)
            return;
        if (c.hasConfig("min") && c.getConfigValue("min", 0) > value)
            throw new ConditionFailedException(MessageKeys.PLEASE_SPECIFY_AT_LEAST, "{min}", String.valueOf(c.getConfigValue("min", 0)));
        if (c.hasConfig("max") && c.getConfigValue("max", Integer.MAX_VALUE) < value)
            throw new ConditionFailedException(MessageKeys.PLEASE_SPECIFY_AT_MOST, "{max}", String.valueOf(c.getConfigValue("max", Integer.MAX_VALUE)));
    });
}
Also used : EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) ConversionHandler(dev.rosewood.rosestacker.conversion.handler.ConversionHandler) Material(org.bukkit.Material) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) EntityType(org.bukkit.entity.EntityType) ConditionFailedException(co.aikar.commands.ConditionFailedException) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext)

Example 3 with ConditionFailedException

use of co.aikar.commands.ConditionFailedException in project buildinggame by stefvanschie.

the class Main method loadPlugin.

/**
 * Loads the entire plugin
 *
 * @since 2.1.0
 */
public void loadPlugin(boolean reload) {
    long start = System.currentTimeMillis();
    // this has to be done quite early
    if (!reload) {
        Gui.registerProperty("particle-type", Particle::valueOf);
        Gui.registerProperty("biome", Biome::valueOf);
        Gui.registerProperty("dye-color", DyeColor::valueOf);
        Gui.registerProperty("material", Material::valueOf);
    }
    getLogger().info("Loading files");
    SettingsManager.getInstance().setup(this, false);
    getLogger().info("Loading arenas");
    ArenaManager.getInstance().setup();
    ArenaModeManager.getInstance().setup();
    BuildTimerManager.getInstance().setup();
    LobbyManager.getInstance().setup();
    LobbyTimerManager.getInstance().setup();
    MinPlayersManager.getInstance().setup();
    MatchesManager.getInstance().setup();
    VoteTimerManager.getInstance().setup();
    WinTimerManager.getInstance().setup();
    getLogger().info("Loading plots");
    PlotManager.getInstance().setup();
    // has to be down here for some config stuff
    MaxPlayersManager.getInstance().setup();
    LocationManager.getInstance().setup();
    BoundaryManager.getInstance().setup();
    FloorManager.getInstance().setup();
    getLogger().info("Loading main spawn");
    MainSpawnManager.getInstance().setup();
    PluginManager pm = Bukkit.getPluginManager();
    getLogger().info("Loading soft dependencies");
    if (pm.isPluginEnabled("Vault"))
        SDVault.getInstance().setup();
    if (pm.isPluginEnabled("PlaceholderAPI")) {
        try {
            String version = pm.getPlugin("PlaceholderAPI").getDescription().getVersion();
            var number = Integer.parseInt(version.replace(".", ""));
            // This ensures the versions don't get mixed up (e.g. 2.7.5 being bigger than 2.9).
            for (var i = version.split("\\.").length; i < 3; i++) number *= 10;
            // 290 is the first version with offline player support
            if (number >= 290) {
                if (!new PlaceholderAPIPlaceholders().register())
                    getLogger().warning("Unable to register placeholders for PlaceholderAPI");
            } else
                getLogger().warning("PlaceholderAPI is outdated, update to a later version to keep BuildingGame compatible with PlaceholderAPI.");
        } catch (NumberFormatException e) {
            getLogger().warning("Unable to get PlaceholderAPI version, contact the plugin author about this.");
            e.printStackTrace();
        }
    }
    if (pm.isPluginEnabled("MVdWPlaceholderAPI")) {
        PlaceholderSupplier.getPlaceholderReplacements().forEach((placeholder, biFunction) -> PlaceholderAPI.registerPlaceholder(this, placeholder, event -> biFunction.apply(event.getOfflinePlayer(), event.getPlaceholder())));
    }
    getLogger().info("Loading commands");
    if (!reload) {
        var manager = new BukkitCommandManager(this);
        // noinspection deprecation
        manager.enableUnstableAPI("help");
        // register contexts
        manager.getCommandContexts().registerContext(Arena.class, context -> {
            var arena = ArenaManager.getInstance().getArena(context.popFirstArg());
            if (arena == null)
                throw new InvalidCommandArgument("This arena doesn't exist");
            return arena;
        });
        manager.getCommandContexts().registerContext(ArenaMode.class, context -> {
            var mode = ArenaMode.valueOf(context.popFirstArg().toUpperCase(Locale.getDefault()));
            if (mode == null)
                throw new InvalidCommandArgument("This game mode doesn't exist");
            return mode;
        });
        manager.getCommandContexts().registerContext(StatType.class, context -> {
            var type = StatType.valueOf(context.popFirstArg().toUpperCase(Locale.getDefault()));
            if (type == null)
                throw new InvalidCommandArgument("This statistic type doesn't exist");
            return type;
        });
        // register completions
        manager.getCommandCompletions().registerCompletion("arenas", context -> ArenaManager.getInstance().getArenas().stream().map(Arena::getName).collect(Collectors.toList()));
        manager.getCommandCompletions().registerCompletion("arenamodes", context -> Stream.of(ArenaMode.values()).map(mode -> mode.toString().toUpperCase(Locale.getDefault())).collect(Collectors.toList()));
        manager.getCommandCompletions().registerCompletion("stattypes", context -> Stream.of(StatType.values()).map(Enum::toString).collect(Collectors.toList()));
        manager.getCommandCompletions().registerCompletion("holograms", context -> TopStatHologram.getHolograms().stream().map(TopStatHologram::getName).collect(Collectors.toList()));
        // register conditions
        manager.getCommandConditions().addCondition(String.class, "arenanotexist", (context, executionContext, string) -> {
            if (ArenaManager.getInstance().getArena(string) != null || string.equals("main-spawn"))
                throw new ConditionFailedException("Arena already exists");
        });
        // hd stands for Holographic Displays, but it's shorten to hd since the full name is a bit long
        manager.getCommandConditions().addCondition("hdenabled", context -> pm.isPluginEnabled("HolographicDisplays"));
        manager.registerCommand(new CommandManager());
    }
    getLogger().info("Loading stats");
    StatManager.getInstance().setup();
    // loading achievements should happen after the statistics have been loaded
    Achievement.loadAchievements();
    getLogger().info("Loading listeners");
    if (!reload) {
        pm.registerEvents(new BlockDispenseItem(), this);
        pm.registerEvents(new BlockEdit(), this);
        pm.registerEvents(new JoinSignCreate(), this);
        pm.registerEvents(new LeaveSignCreate(), this);
        pm.registerEvents(new StatSignCreate(), this);
        pm.registerEvents(new UpdateLoadedSigns(), this);
        pm.registerEvents(new SpectateSignCreate(), this);
        pm.registerEvents(new SignBreak(), this);
        pm.registerEvents(new LiquidFlow(), this);
        pm.registerEvents(new PistonBlockMove(), this);
        // starts the connection to bungeecord
        if (SettingsManager.getInstance().getConfig().getBoolean("bungeecord.enable"))
            BungeeCordHandler.getInstance();
        // per world inventory compatibility fix
        if (pm.isPluginEnabled("PerWorldInventory")) {
            try {
                String version = pm.getPlugin("PerWorldInventory").getDescription().getVersion();
                var number = Integer.parseInt(version.replace(".", ""));
                // This ensures the versions don't get mixed up (e.g. 1.7.5 being bigger than 1.11).
                for (var i = version.split("\\.").length; i < 3; i++) number *= 10;
                // 200 is the first version with the new package name
                if (number >= 200)
                    pm.registerEvents(new PerWorldInventoryCancel(), this);
                else
                    getLogger().warning("PerWorldInventory is outdated, update to a later version to keep BuildingGame compatible with PerWorldInventory.");
            } catch (NumberFormatException e) {
                getLogger().warning("Unable to get PerWorldInventory version, contact the plugin author about this.");
                e.printStackTrace();
            }
        }
        if (pm.isPluginEnabled("WorldEdit"))
            WorldEdit.getInstance().getEventBus().register(new WorldEditBoundaryAssertion());
        if (pm.isPluginEnabled("Citizens")) {
            pm.registerEvents(new NPCCreate(), this);
            TraitInfo traitInfo = TraitInfo.create(NPCFloorChangeTrait.class).withName("buildinggame:floorchange");
            CitizensAPI.getTraitFactory().registerTrait(traitInfo);
        }
        pm.registerEvents(new ClickJoinSign(), this);
        pm.registerEvents(new ClickLeaveSign(), this);
        pm.registerEvents(new ClickSpectateSign(), this);
        pm.registerEvents(new Drop(), this);
        pm.registerEvents(new Interact(), this);
        pm.registerEvents(new Leave(), this);
        pm.registerEvents(new Move(), this);
        pm.registerEvents(new PlaceBucket(), this);
        pm.registerEvents(new PlaceIgnoreSpectators(), this);
        if (SettingsManager.getInstance().getConfig().getBoolean("chat.adjust"))
            pm.registerEvents(new Chat(), this);
        pm.registerEvents(new CommandBlocker(), this);
        pm.registerEvents(new EntityDamage(), this);
        pm.registerEvents(new TakeDamage(), this);
        pm.registerEvents(new LoseFood(), this);
        // entity events
        pm.registerEvents(new ChickenSpawnByEgg(), this);
        pm.registerEvents(new EntityExplode(), this);
        pm.registerEvents(new EntityOptionsMenu(), this);
        pm.registerEvents(new EntitySpawn(), this);
        // scoreboards
        pm.registerEvents(new MainScoreboardJoinShow(), this);
        pm.registerEvents(new MainScoreboardWorldChange(), this);
        // stats
        // saved
        pm.registerEvents(new BreakStat(), this);
        pm.registerEvents(new FirstStat(), this);
        pm.registerEvents(new PlaceStat(), this);
        pm.registerEvents(new PlaysStat(), this);
        pm.registerEvents(new SecondStat(), this);
        pm.registerEvents(new ThirdStat(), this);
        // unsaved
        pm.registerEvents(new UnsavedStatsPlace(), this);
        // structure
        pm.registerEvents(new TreeGrow(), this);
        if (StatManager.getInstance().getMySQLDatabase() != null) {
            pm.registerEvents(new JoinPlayerStats(), this);
            pm.registerEvents(new QuitPlayerStats(), this);
        }
    }
    getLogger().info("Loading signs");
    SignManager.getInstance().setup();
    getLogger().info("Loading timer");
    new ParticleRender().runTaskTimer(this, 0L, 10L);
    new ScoreboardUpdater().runTaskTimer(this, 0L, SettingsManager.getInstance().getConfig().getLong("scoreboard-update-delay"));
    new StatSaveTimer().runTaskTimerAsynchronously(this, 0L, SettingsManager.getInstance().getConfig().getLong("stats.save-delay"));
    new EntityTimer().runTaskTimer(this, 0L, 20L);
    new StatSignUpdater().runTaskTimerAsynchronously(this, 0L, 1L);
    long end = System.currentTimeMillis();
    long duration = end - start;
    String time;
    if (duration < 1000) {
        time = duration + " milliseconds";
    } else if (duration < 60000) {
        time = duration / 1000.0 + " seconds";
    } else {
        time = (duration / 60000) + ":" + (duration % 60000) / 1000.0 + " minutes";
    }
    getLogger().info("BuildingGame has been enabled in " + time + '!');
}
Also used : CommandManager(com.gmail.stefvanschiedev.buildinggame.managers.commands.CommandManager) LocationManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.LocationManager) EntityExplode(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityExplode) Biome(org.bukkit.block.Biome) UnsavedStatsPlace(com.gmail.stefvanschiedev.buildinggame.events.stats.unsaved.UnsavedStatsPlace) CitizensAPI(net.citizensnpcs.api.CitizensAPI) PerWorldInventoryCancel(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.PerWorldInventoryCancel) EntitySpawn(com.gmail.stefvanschiedev.buildinggame.events.entity.EntitySpawn) LiquidFlow(com.gmail.stefvanschiedev.buildinggame.events.block.LiquidFlow) PlotManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.PlotManager) TopStatHologram(com.gmail.stefvanschiedev.buildinggame.utils.TopStatHologram) NPCFloorChangeTrait(com.gmail.stefvanschiedev.buildinggame.utils.NPCFloorChangeTrait) ClickSpectateSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickSpectateSign) Gui(com.github.stefvanschie.inventoryframework.gui.type.util.Gui) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) JoinPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.JoinPlayerStats) EntityOptionsMenu(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityOptionsMenu) ArenaMode(com.gmail.stefvanschiedev.buildinggame.utils.arena.ArenaMode) com.gmail.stefvanschiedev.buildinggame.events.block.signs(com.gmail.stefvanschiedev.buildinggame.events.block.signs) FirstStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.FirstStat) SettingsManager(com.gmail.stefvanschiedev.buildinggame.managers.files.SettingsManager) Collectors(java.util.stream.Collectors) MainScoreboardJoinShow(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardJoinShow) ThirdStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.ThirdStat) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) Contract(org.jetbrains.annotations.Contract) Stream(java.util.stream.Stream) com.gmail.stefvanschiedev.buildinggame.managers.arenas(com.gmail.stefvanschiedev.buildinggame.managers.arenas) TreeGrow(com.gmail.stefvanschiedev.buildinggame.events.structure.TreeGrow) FloorManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.FloorManager) Achievement(com.gmail.stefvanschiedev.buildinggame.utils.Achievement) NotNull(org.jetbrains.annotations.NotNull) StatType(com.gmail.stefvanschiedev.buildinggame.utils.stats.StatType) QuitPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.QuitPlayerStats) PlaysStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaysStat) java.util(java.util) BreakStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.BreakStat) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) com.gmail.stefvanschiedev.buildinggame.events.player(com.gmail.stefvanschiedev.buildinggame.events.player) PlaceholderAPIPlaceholders(com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.PlaceholderAPIPlaceholders) MetricsLite(org.bstats.bukkit.MetricsLite) BlockDispenseItem(com.gmail.stefvanschiedev.buildinggame.events.block.BlockDispenseItem) ChickenSpawnByEgg(com.gmail.stefvanschiedev.buildinggame.events.entity.ChickenSpawnByEgg) WorldEditBoundaryAssertion(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.WorldEditBoundaryAssertion) BungeeCordHandler(com.gmail.stefvanschiedev.buildinggame.utils.bungeecord.BungeeCordHandler) Interact(com.gmail.stefvanschiedev.buildinggame.events.player.voting.Interact) NPCCreate(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.NPCCreate) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) PistonBlockMove(com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove) ConditionFailedException(co.aikar.commands.ConditionFailedException) WorldEdit(com.sk89q.worldedit.WorldEdit) SDVault(com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.SDVault) BoundaryManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.BoundaryManager) BlockEdit(com.gmail.stefvanschiedev.buildinggame.events.block.BlockEdit) PlaceholderAPI(be.maximvdw.placeholderapi.PlaceholderAPI) Particle(org.bukkit.Particle) TraitInfo(net.citizensnpcs.api.trait.TraitInfo) ClickJoinSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickJoinSign) MainScoreboardWorldChange(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardWorldChange) PlaceholderSupplier(com.gmail.stefvanschiedev.buildinggame.utils.PlaceholderSupplier) StatManager(com.gmail.stefvanschiedev.buildinggame.managers.stats.StatManager) com.gmail.stefvanschiedev.buildinggame.timers(com.gmail.stefvanschiedev.buildinggame.timers) PlaceStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaceStat) Arena(com.gmail.stefvanschiedev.buildinggame.utils.arena.Arena) DyeColor(org.bukkit.DyeColor) ClickLeaveSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickLeaveSign) SecondStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.SecondStat) MainSpawnManager(com.gmail.stefvanschiedev.buildinggame.managers.mainspawn.MainSpawnManager) PluginManager(org.bukkit.plugin.PluginManager) BlockDispenseItem(com.gmail.stefvanschiedev.buildinggame.events.block.BlockDispenseItem) BreakStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.BreakStat) TreeGrow(com.gmail.stefvanschiedev.buildinggame.events.structure.TreeGrow) PlaysStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaysStat) JoinPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.JoinPlayerStats) Interact(com.gmail.stefvanschiedev.buildinggame.events.player.voting.Interact) Particle(org.bukkit.Particle) PluginManager(org.bukkit.plugin.PluginManager) CommandManager(com.gmail.stefvanschiedev.buildinggame.managers.commands.CommandManager) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) TraitInfo(net.citizensnpcs.api.trait.TraitInfo) EntitySpawn(com.gmail.stefvanschiedev.buildinggame.events.entity.EntitySpawn) SecondStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.SecondStat) PlaceStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaceStat) TopStatHologram(com.gmail.stefvanschiedev.buildinggame.utils.TopStatHologram) ChickenSpawnByEgg(com.gmail.stefvanschiedev.buildinggame.events.entity.ChickenSpawnByEgg) DyeColor(org.bukkit.DyeColor) Arena(com.gmail.stefvanschiedev.buildinggame.utils.arena.Arena) ClickSpectateSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickSpectateSign) QuitPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.QuitPlayerStats) ThirdStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.ThirdStat) WorldEditBoundaryAssertion(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.WorldEditBoundaryAssertion) MainScoreboardWorldChange(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardWorldChange) PerWorldInventoryCancel(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.PerWorldInventoryCancel) ClickLeaveSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickLeaveSign) PlaceholderAPIPlaceholders(com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.PlaceholderAPIPlaceholders) Biome(org.bukkit.block.Biome) ConditionFailedException(co.aikar.commands.ConditionFailedException) PistonBlockMove(com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove) ClickJoinSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickJoinSign) EntityExplode(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityExplode) FirstStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.FirstStat) NPCFloorChangeTrait(com.gmail.stefvanschiedev.buildinggame.utils.NPCFloorChangeTrait) NPCCreate(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.NPCCreate) EntityOptionsMenu(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityOptionsMenu) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) LiquidFlow(com.gmail.stefvanschiedev.buildinggame.events.block.LiquidFlow) Material(org.bukkit.Material) PistonBlockMove(com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove) UnsavedStatsPlace(com.gmail.stefvanschiedev.buildinggame.events.stats.unsaved.UnsavedStatsPlace) BlockEdit(com.gmail.stefvanschiedev.buildinggame.events.block.BlockEdit) MainScoreboardJoinShow(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardJoinShow)

Example 4 with ConditionFailedException

use of co.aikar.commands.ConditionFailedException in project EmployMe by DavidTheExplorer.

the class EmployMe method registerCommands.

@SuppressWarnings("deprecation")
private void registerCommands() {
    BukkitCommandManager commandManager = new BukkitCommandManager(this);
    commandManager.enableUnstableAPI("help");
    // register conditions
    commandManager.getCommandConditions().addCondition(Player.class, "Not Conversing", (handler, context, payment) -> {
        if (context.getPlayer().isConversing())
            throw new InvalidCommandArgument(this.messageService.getMessage(MUST_NOT_BE_CONVERSING).first(), false);
    });
    commandManager.getCommandConditions().addCondition(Material.class, "Subscribed To Goal", (handler, context, material) -> {
        if (!this.jobSubscriptionService.isSubscribedTo(context.getPlayer().getUniqueId(), material))
            throw new InvalidCommandArgument(this.messageService.getMessage(MUST_BE_SUBSCRIBED_TO_GOAL).first(), false);
    });
    commandManager.getCommandConditions().addCondition("Global Jobs Board Not Full", context -> {
        if (this.globalJobBoard.getOfferedJobs().size() == ((6 * 9) - 26))
            throw new ConditionFailedException(this.messageService.getMessage(GLOBAL_JOB_BOARD_IS_FULL).first());
    });
    commandManager.getCommandConditions().addCondition(Player.class, "Can Offer More Jobs", (handler, context, player) -> {
        String jobPermission = PermissionUtils.findPermission(player, permission -> permission.startsWith("employme.jobs.allowed.")).orElse("employme.jobs.allowed.3");
        int allowedJobs = Integer.parseInt(jobPermission.split("\\.")[jobPermission.split("\\.").length - 1]);
        if (this.globalJobBoard.getJobsOfferedBy(player.getUniqueId()).size() >= allowedJobs)
            throw new ConditionFailedException(this.messageService.getMessage(YOU_OFFERED_TOO_MANY_JOBS).first());
    });
    // register contexts
    commandManager.getCommandContexts().registerContext(Material.class, context -> {
        Material material = Material.matchMaterial(context.popFirstArg());
        if (material == null)
            throw new InvalidCommandArgument(this.messageService.getMessage(MATERIAL_NOT_FOUND).first(), false);
        return material;
    });
    commandManager.getCommandContexts().registerContext(JobAddedNotifier.class, context -> {
        String notifierName = context.joinArgs();
        JobAddedNotifier notifier = this.jobAddedNotifierService.getByName(notifierName);
        if (notifier == null)
            throw new InvalidCommandArgument(this.messageService.getMessage(JOB_ADDED_NOTIFIER_NOT_FOUND).inject(Placeholders.JOB_ADDED_NOTIFIER, notifierName).first(), false);
        return notifier;
    });
    commandManager.getCommandContexts().registerIssuerOnlyContext(List.class, context -> {
        if (!context.hasFlag("Jobs Able To Delete"))
            return null;
        Player player = context.getPlayer();
        return player.hasPermission("employme.admin.delete") ? this.globalJobBoard.getOfferedJobs() : this.globalJobBoard.getJobsOfferedBy(player.getUniqueId());
    });
    // register commands
    InventoryBoardDisplayer inventoryBoardDisplayer = new InventoryBoardDisplayer(Job.ORDER_BY_GOAL_NAME, this.jobService, this.messageService, this.jobIconFactory);
    commandManager.registerCommand(new EmploymentCommand(this.globalJobBoard, this.playerContainerService, this.jobSubscriptionService, this.jobAddedNotifierService, this.messageService, inventoryBoardDisplayer, this.economy, this.jobIconFactory, this.rewardService, this.reloadables));
}
Also used : PermissionUtils(dte.employme.utils.PermissionUtils) MaterialSubscriptionNotifier(dte.employme.job.addnotifiers.MaterialSubscriptionNotifier) SimpleJobSubscriptionService(dte.employme.job.subscription.SimpleJobSubscriptionService) RewardService(dte.employme.job.rewards.service.RewardService) Player(org.bukkit.entity.Player) ModernJavaPlugin(dte.modernjavaplugin.ModernJavaPlugin) ConfigFileFactory(dte.employme.config.ConfigFileFactory) PlayerContainerService(dte.employme.containers.service.PlayerContainerService) SimpleJobAddedNotifierService(dte.employme.job.addnotifiers.service.SimpleJobAddedNotifierService) SimpleRewardService(dte.employme.job.rewards.service.SimpleRewardService) PlayerContainerAbuseListener(dte.employme.listeners.PlayerContainerAbuseListener) MUST_BE_SUBSCRIBED_TO_GOAL(dte.employme.messages.MessageKey.MUST_BE_SUBSCRIBED_TO_GOAL) JobRewardGiveListener(dte.employme.board.listenable.JobRewardGiveListener) EmployerNotificationListener(dte.employme.board.listenable.EmployerNotificationListener) GLOBAL_JOB_BOARD_IS_FULL(dte.employme.messages.MessageKey.GLOBAL_JOB_BOARD_IS_FULL) ColoredMessageService(dte.employme.messages.service.ColoredMessageService) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) JobCompletedMessagesListener(dte.employme.board.listenable.JobCompletedMessagesListener) AutoUpdateListeners(dte.employme.listeners.AutoUpdateListeners) Metrics(org.bstats.bukkit.Metrics) JobAddedNotifierService(dte.employme.job.addnotifiers.service.JobAddedNotifierService) SimplePlayerContainerService(dte.employme.containers.service.SimplePlayerContainerService) JobAddedNotifier(dte.employme.job.addnotifiers.JobAddedNotifier) JOB_ADDED_NOTIFIER_NOT_FOUND(dte.employme.messages.MessageKey.JOB_ADDED_NOTIFIER_NOT_FOUND) EmploymentCommand(dte.employme.commands.EmploymentCommand) JobService(dte.employme.job.service.JobService) MessageService(dte.employme.messages.service.MessageService) List(java.util.List) Stream(java.util.stream.Stream) MUST_NOT_BE_CONVERSING(dte.employme.messages.MessageKey.MUST_NOT_BE_CONVERSING) SimpleListenableJobBoard(dte.employme.board.listenable.SimpleListenableJobBoard) TranslatedMessageService(dte.employme.messages.service.TranslatedMessageService) SimpleJobBoard(dte.employme.board.SimpleJobBoard) ConfigurationSerialization(org.bukkit.configuration.serialization.ConfigurationSerialization) SimpleJob(dte.employme.job.SimpleJob) RED(org.bukkit.ChatColor.RED) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) Job(dte.employme.job.Job) YOU_OFFERED_TOO_MANY_JOBS(dte.employme.messages.MessageKey.YOU_OFFERED_TOO_MANY_JOBS) ArrayList(java.util.ArrayList) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) InventoryBoardDisplayer(dte.employme.board.displayers.InventoryBoardDisplayer) AllJobsNotifier(dte.employme.job.addnotifiers.AllJobsNotifier) ConditionFailedException(co.aikar.commands.ConditionFailedException) ListenableJobBoard(dte.employme.board.listenable.ListenableJobBoard) ConfigFile(dte.employme.config.ConfigFile) Economy(net.milkbowl.vault.economy.Economy) Messages(dte.employme.config.Messages) MoneyReward(dte.employme.job.rewards.MoneyReward) JobAddNotificationListener(dte.employme.board.listenable.JobAddNotificationListener) ServiceLocator(dte.employme.utils.java.ServiceLocator) JobIconFactory(dte.employme.items.JobIconFactory) MATERIAL_NOT_FOUND(dte.employme.messages.MessageKey.MATERIAL_NOT_FOUND) JobGoalTransferListener(dte.employme.board.listenable.JobGoalTransferListener) JobSubscriptionService(dte.employme.job.subscription.JobSubscriptionService) SimpleJobService(dte.employme.job.service.SimpleJobService) ItemsReward(dte.employme.job.rewards.ItemsReward) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) Placeholders(dte.employme.messages.Placeholders) Reloadable(dte.employme.reloadable.Reloadable) DoNotNotify(dte.employme.job.addnotifiers.DoNotNotify) AutoUpdater(dte.employme.utils.AutoUpdater) Player(org.bukkit.entity.Player) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) ConditionFailedException(co.aikar.commands.ConditionFailedException) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) InventoryBoardDisplayer(dte.employme.board.displayers.InventoryBoardDisplayer) JobAddedNotifier(dte.employme.job.addnotifiers.JobAddedNotifier) Material(org.bukkit.Material) EmploymentCommand(dte.employme.commands.EmploymentCommand)

Aggregations

ConditionFailedException (co.aikar.commands.ConditionFailedException)4 Material (org.bukkit.Material)3 BukkitCommandManager (co.aikar.commands.BukkitCommandManager)2 InvalidCommandArgument (co.aikar.commands.InvalidCommandArgument)2 Stream (java.util.stream.Stream)2 Bukkit (org.bukkit.Bukkit)2 PlaceholderAPI (be.maximvdw.placeholderapi.PlaceholderAPI)1 BukkitCommandCompletionContext (co.aikar.commands.BukkitCommandCompletionContext)1 MessageKeys (co.aikar.commands.MessageKeys)1 MessageType (co.aikar.commands.MessageType)1 PaperBrigadierManager (co.aikar.commands.PaperBrigadierManager)1 PaperCommandManager (co.aikar.commands.PaperCommandManager)1 Gui (com.github.stefvanschie.inventoryframework.gui.type.util.Gui)1 BlockDispenseItem (com.gmail.stefvanschiedev.buildinggame.events.block.BlockDispenseItem)1 BlockEdit (com.gmail.stefvanschiedev.buildinggame.events.block.BlockEdit)1 LiquidFlow (com.gmail.stefvanschiedev.buildinggame.events.block.LiquidFlow)1 PistonBlockMove (com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove)1 com.gmail.stefvanschiedev.buildinggame.events.block.signs (com.gmail.stefvanschiedev.buildinggame.events.block.signs)1 ChickenSpawnByEgg (com.gmail.stefvanschiedev.buildinggame.events.entity.ChickenSpawnByEgg)1 EntityExplode (com.gmail.stefvanschiedev.buildinggame.events.entity.EntityExplode)1