Search in sources :

Example 21 with CommandException

use of com.sk89q.minecraft.util.commands.CommandException in project WorldGuard by EngineHub.

the class RegionCommands method claim.

/**
 * Claiming command for users.
 *
 * <p>This command is a joke and it needs to be rewritten. It was contributed
 * code :(</p>
 *
 * @param args the arguments
 * @param sender the sender
 * @throws CommandException any error
 */
@Command(aliases = { "claim" }, usage = "<id>", desc = "Claim a region", min = 1, max = 1)
public void claim(CommandContext args, Actor sender) throws CommandException {
    warnAboutSaveFailures(sender);
    LocalPlayer player = worldGuard.checkPlayer(sender);
    RegionPermissionModel permModel = getPermissionModel(player);
    // Check permissions
    if (!permModel.mayClaim()) {
        throw new CommandPermissionsException();
    }
    String id = checkRegionId(args.getString(0), false);
    RegionManager manager = checkRegionManager(player.getWorld());
    checkRegionDoesNotExist(manager, id, false);
    ProtectedRegion region = checkRegionFromSelection(player, id);
    WorldConfiguration wcfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(player.getWorld());
    // Check whether the player has created too many regions
    if (!permModel.mayClaimRegionsUnbounded()) {
        int maxRegionCount = wcfg.getMaxRegionCount(player);
        if (maxRegionCount >= 0 && manager.getRegionCountOfPlayer(player) >= maxRegionCount) {
            throw new CommandException("You own too many regions, delete one first to claim a new one.");
        }
    }
    ProtectedRegion existing = manager.getRegion(id);
    // Check for an existing region
    if (existing != null) {
        if (!existing.getOwners().contains(player)) {
            throw new CommandException("This region already exists and you don't own it.");
        }
    }
    // We have to check whether this region violates the space of any other region
    ApplicableRegionSet regions = manager.getApplicableRegions(region);
    // Check if this region overlaps any other region
    if (regions.size() > 0) {
        if (!regions.isOwnerOfAll(player)) {
            throw new CommandException("This region overlaps with someone else's region.");
        }
    } else {
        if (wcfg.claimOnlyInsideExistingRegions) {
            throw new CommandException("You may only claim regions inside " + "existing regions that you or your group own.");
        }
    }
    if (wcfg.maxClaimVolume >= Integer.MAX_VALUE) {
        throw new CommandException("The maximum claim volume get in the configuration is higher than is supported. " + "Currently, it must be " + Integer.MAX_VALUE + " or smaller. Please contact a server administrator.");
    }
    // Check claim volume
    if (!permModel.mayClaimRegionsUnbounded()) {
        if (region instanceof ProtectedPolygonalRegion) {
            throw new CommandException("Polygons are currently not supported for /rg claim.");
        }
        if (region.volume() > wcfg.maxClaimVolume) {
            player.printError("This region is too large to claim.");
            player.printError("Max. volume: " + wcfg.maxClaimVolume + ", your volume: " + region.volume());
            return;
        }
    }
    // Inherit from a template region
    if (!Strings.isNullOrEmpty(wcfg.setParentOnClaim)) {
        ProtectedRegion templateRegion = manager.getRegion(wcfg.setParentOnClaim);
        if (templateRegion != null) {
            try {
                region.setParent(templateRegion);
            } catch (CircularInheritanceException e) {
                throw new CommandException(e.getMessage());
            }
        }
    }
    RegionAdder task = new RegionAdder(manager, region);
    task.setLocatorPolicy(UserLocatorPolicy.UUID_ONLY);
    task.setOwnersInput(new String[] { player.getName() });
    final String description = String.format("Claiming region '%s'", id);
    AsyncCommandBuilder.wrap(task, sender).registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), description).sendMessageAfterDelay("(Please wait... " + description + ")").onSuccess(TextComponent.of(String.format("A new region has been claimed named '%s'.", id)), null).onFailure("Failed to claim region", WorldGuard.getInstance().getExceptionConverter()).buildAndExec(WorldGuard.getInstance().getExecutorService());
}
Also used : CommandPermissionsException(com.sk89q.minecraft.util.commands.CommandPermissionsException) LocalPlayer(com.sk89q.worldguard.LocalPlayer) CommandException(com.sk89q.minecraft.util.commands.CommandException) CircularInheritanceException(com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException) RegionAdder(com.sk89q.worldguard.commands.task.RegionAdder) WorldConfiguration(com.sk89q.worldguard.config.WorldConfiguration) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) RegionManager(com.sk89q.worldguard.protection.managers.RegionManager) ProtectedPolygonalRegion(com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion) RegionPermissionModel(com.sk89q.worldguard.internal.permission.RegionPermissionModel) ApplicableRegionSet(com.sk89q.worldguard.protection.ApplicableRegionSet) Command(com.sk89q.minecraft.util.commands.Command)

Example 22 with CommandException

use of com.sk89q.minecraft.util.commands.CommandException in project WorldGuard by EngineHub.

the class RegionCommands method migrateUuid.

/**
 * Migrate the region databases to use UUIDs rather than name.
 *
 * @param args the arguments
 * @param sender the sender
 * @throws CommandException any error
 */
@Command(aliases = { "migrateuuid" }, desc = "Migrate loaded databases to use UUIDs", max = 0)
public void migrateUuid(CommandContext args, Actor sender) throws CommandException {
    // Check permissions
    if (!getPermissionModel(sender).mayMigrateRegionNames()) {
        throw new CommandPermissionsException();
    }
    LoggerToChatHandler handler = null;
    Logger minecraftLogger = null;
    if (sender instanceof LocalPlayer) {
        handler = new LoggerToChatHandler(sender);
        handler.setLevel(Level.ALL);
        minecraftLogger = Logger.getLogger("com.sk89q.worldguard");
        minecraftLogger.addHandler(handler);
    }
    try {
        ConfigurationManager config = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
        RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
        RegionDriver driver = container.getDriver();
        UUIDMigration migration = new UUIDMigration(driver, WorldGuard.getInstance().getProfileService(), WorldGuard.getInstance().getFlagRegistry());
        migration.setKeepUnresolvedNames(config.keepUnresolvedNames);
        sender.print("Now performing migration... this may take a while.");
        container.migrate(migration);
        sender.print("Migration complete!");
    } catch (MigrationException e) {
        log.log(Level.WARNING, "Failed to migrate", e);
        throw new CommandException("Error encountered while migrating: " + e.getMessage());
    } finally {
        if (minecraftLogger != null) {
            minecraftLogger.removeHandler(handler);
        }
    }
}
Also used : MigrationException(com.sk89q.worldguard.protection.managers.migration.MigrationException) LoggerToChatHandler(com.sk89q.worldguard.util.logging.LoggerToChatHandler) CommandPermissionsException(com.sk89q.minecraft.util.commands.CommandPermissionsException) RegionContainer(com.sk89q.worldguard.protection.regions.RegionContainer) LocalPlayer(com.sk89q.worldguard.LocalPlayer) CommandException(com.sk89q.minecraft.util.commands.CommandException) Logger(java.util.logging.Logger) RegionDriver(com.sk89q.worldguard.protection.managers.storage.RegionDriver) ConfigurationManager(com.sk89q.worldguard.config.ConfigurationManager) UUIDMigration(com.sk89q.worldguard.protection.managers.migration.UUIDMigration) Command(com.sk89q.minecraft.util.commands.Command)

Example 23 with CommandException

use of com.sk89q.minecraft.util.commands.CommandException in project WorldGuard by EngineHub.

the class RegionCommands method flag.

/**
 * Set a flag.
 *
 * @param args the arguments
 * @param sender the sender
 * @throws CommandException any error
 */
@Command(aliases = { "flag", "f" }, usage = "<id> <flag> [-w world] [-g group] [value]", flags = "g:w:eh:", desc = "Set flags", min = 2)
public void flag(CommandContext args, Actor sender) throws CommandException {
    warnAboutSaveFailures(sender);
    // Get the world
    World world = checkWorld(args, sender, 'w');
    String flagName = args.getString(1);
    String value = args.argsLength() >= 3 ? args.getJoinedStrings(2) : null;
    RegionGroup groupValue = null;
    FlagRegistry flagRegistry = WorldGuard.getInstance().getFlagRegistry();
    RegionPermissionModel permModel = getPermissionModel(sender);
    if (args.hasFlag('e')) {
        if (value != null) {
            throw new CommandException("You cannot use -e(mpty) with a flag value.");
        }
        value = "";
    }
    // Lookup the existing region
    RegionManager manager = checkRegionManager(world);
    ProtectedRegion existing = checkExistingRegion(manager, args.getString(0), true);
    // Check permissions
    if (!permModel.maySetFlag(existing)) {
        throw new CommandPermissionsException();
    }
    String regionId = existing.getId();
    Flag<?> foundFlag = Flags.fuzzyMatchFlag(flagRegistry, flagName);
    // can use, and do nothing afterwards
    if (foundFlag == null) {
        AsyncCommandBuilder.wrap(new FlagListBuilder(flagRegistry, permModel, existing, world, regionId, sender, flagName), sender).registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), "Flag list for invalid flag command.").onSuccess((Component) null, sender::print).onFailure((Component) null, WorldGuard.getInstance().getExceptionConverter()).buildAndExec(WorldGuard.getInstance().getExecutorService());
        return;
    } else if (value != null) {
        if (foundFlag == Flags.BUILD || foundFlag == Flags.BLOCK_BREAK || foundFlag == Flags.BLOCK_PLACE) {
            sender.print(buildFlagWarning);
            if (!sender.isPlayer()) {
                sender.printRaw("https://worldguard.enginehub.org/en/latest/regions/flags/#protection-related");
            }
        } else if (foundFlag == Flags.PASSTHROUGH) {
            sender.print(passthroughFlagWarning);
            if (!sender.isPlayer()) {
                sender.printRaw("https://worldguard.enginehub.org/en/latest/regions/flags/#overrides");
            }
        }
    }
    // but not here -- in the model
    if (!permModel.maySetFlag(existing, foundFlag, value)) {
        throw new CommandPermissionsException();
    }
    // -g for group flag
    if (args.hasFlag('g')) {
        String group = args.getFlag('g');
        RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
        if (groupFlag == null) {
            throw new CommandException("Region flag '" + foundFlag.getName() + "' does not have a group flag!");
        }
        // the [value] part throws an error.
        try {
            groupValue = groupFlag.parseInput(FlagContext.create().setSender(sender).setInput(group).setObject("region", existing).build());
        } catch (InvalidFlagFormat e) {
            throw new CommandException(e.getMessage());
        }
    }
    // Set the flag value if a value was set
    if (value != null) {
        // Set the flag if [value] was given even if [-g group] was given as well
        try {
            value = setFlag(existing, foundFlag, sender, value).toString();
        } catch (InvalidFlagFormat e) {
            throw new CommandException(e.getMessage());
        }
        if (!args.hasFlag('h')) {
            sender.print("Region flag " + foundFlag.getName() + " set on '" + regionId + "' to '" + value + "'.");
        }
    // No value? Clear the flag, if -g isn't specified
    } else if (!args.hasFlag('g')) {
        // Clear the flag only if neither [value] nor [-g group] was given
        existing.setFlag(foundFlag, null);
        // Also clear the associated group flag if one exists
        RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
        if (groupFlag != null) {
            existing.setFlag(groupFlag, null);
        }
        if (!args.hasFlag('h')) {
            sender.print("Region flag " + foundFlag.getName() + " removed from '" + regionId + "'. (Any -g(roups) were also removed.)");
        }
    }
    // Now set the group
    if (groupValue != null) {
        RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
        // If group set to the default, then clear the group flag
        if (groupValue == groupFlag.getDefault()) {
            existing.setFlag(groupFlag, null);
            sender.print("Region group flag for '" + foundFlag.getName() + "' reset to default.");
        } else {
            existing.setFlag(groupFlag, groupValue);
            sender.print("Region group flag for '" + foundFlag.getName() + "' set.");
        }
    }
    // Print region information
    if (args.hasFlag('h')) {
        int page = args.getFlagInteger('h');
        sendFlagHelper(sender, world, existing, permModel, page);
    } else {
        RegionPrintoutBuilder printout = new RegionPrintoutBuilder(world.getName(), existing, null, sender);
        printout.append(SubtleFormat.wrap("(Current flags: "));
        printout.appendFlagsList(false);
        printout.append(SubtleFormat.wrap(")"));
        printout.send(sender);
        checkSpawnOverlap(sender, world, existing);
    }
}
Also used : CommandPermissionsException(com.sk89q.minecraft.util.commands.CommandPermissionsException) FlagRegistry(com.sk89q.worldguard.protection.flags.registry.FlagRegistry) CommandException(com.sk89q.minecraft.util.commands.CommandException) RegionGroupFlag(com.sk89q.worldguard.protection.flags.RegionGroupFlag) World(com.sk89q.worldedit.world.World) RegionGroup(com.sk89q.worldguard.protection.flags.RegionGroup) InvalidFlagFormat(com.sk89q.worldguard.protection.flags.InvalidFlagFormat) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) RegionManager(com.sk89q.worldguard.protection.managers.RegionManager) RegionPermissionModel(com.sk89q.worldguard.internal.permission.RegionPermissionModel) Component(com.sk89q.worldedit.util.formatting.text.Component) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Command(com.sk89q.minecraft.util.commands.Command)

Example 24 with CommandException

use of com.sk89q.minecraft.util.commands.CommandException in project WorldGuard by EngineHub.

the class RegionCommands method remove.

/**
 * Remove a region.
 *
 * @param args the arguments
 * @param sender the sender
 * @throws CommandException any error
 */
@Command(aliases = { "remove", "delete", "del", "rem" }, usage = "<id>", flags = "fuw:", desc = "Remove a region", min = 1, max = 1)
public void remove(CommandContext args, Actor sender) throws CommandException {
    warnAboutSaveFailures(sender);
    // Get the world
    World world = checkWorld(args, sender, 'w');
    boolean removeChildren = args.hasFlag('f');
    boolean unsetParent = args.hasFlag('u');
    // Lookup the existing region
    RegionManager manager = checkRegionManager(world);
    ProtectedRegion existing = checkExistingRegion(manager, args.getString(0), true);
    // Check permissions
    if (!getPermissionModel(sender).mayDelete(existing)) {
        throw new CommandPermissionsException();
    }
    RegionRemover task = new RegionRemover(manager, existing);
    if (removeChildren && unsetParent) {
        throw new CommandException("You cannot use both -u (unset parent) and -f (remove children) together.");
    } else if (removeChildren) {
        task.setRemovalStrategy(RemovalStrategy.REMOVE_CHILDREN);
    } else if (unsetParent) {
        task.setRemovalStrategy(RemovalStrategy.UNSET_PARENT_IN_CHILDREN);
    }
    final String description = String.format("Removing region '%s' in '%s'", existing.getId(), world.getName());
    AsyncCommandBuilder.wrap(task, sender).registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), description).sendMessageAfterDelay("Please wait... removing region.").onSuccess((Component) null, removed -> sender.print(TextComponent.of("Successfully removed " + removed.stream().map(ProtectedRegion::getId).collect(Collectors.joining(", ")) + ".", TextColor.LIGHT_PURPLE))).onFailure("Failed to remove region", WorldGuard.getInstance().getExceptionConverter()).buildAndExec(WorldGuard.getInstance().getExecutorService());
}
Also used : RegionRemover(com.sk89q.worldguard.commands.task.RegionRemover) CommandPermissionsException(com.sk89q.minecraft.util.commands.CommandPermissionsException) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) RegionManager(com.sk89q.worldguard.protection.managers.RegionManager) CommandException(com.sk89q.minecraft.util.commands.CommandException) World(com.sk89q.worldedit.world.World) Command(com.sk89q.minecraft.util.commands.Command)

Example 25 with CommandException

use of com.sk89q.minecraft.util.commands.CommandException in project WorldGuard by EngineHub.

the class RegionCommandsBase method checkExistingRegion.

/**
 * Get a protected region by a given name, otherwise throw a
 * {@link CommandException}.
 *
 * <p>This also validates the region ID.</p>
 *
 * @param regionManager the region manager
 * @param id the name to search
 * @param allowGlobal true to allow selecting __global__
 * @throws CommandException thrown if no region is found by the given name
 */
protected static ProtectedRegion checkExistingRegion(RegionManager regionManager, String id, boolean allowGlobal) throws CommandException {
    // Validate the id
    checkRegionId(id, allowGlobal);
    ProtectedRegion region = regionManager.getRegion(id);
    // No region found!
    if (region == null) {
        // But we want a __global__, so let's create one
        if (id.equalsIgnoreCase("__global__")) {
            region = new GlobalProtectedRegion(id);
            regionManager.addRegion(region);
            return region;
        }
        throw new CommandException("No region could be found with the name of '" + id + "'.");
    }
    return region;
}
Also used : GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) CommandException(com.sk89q.minecraft.util.commands.CommandException)

Aggregations

CommandException (com.sk89q.minecraft.util.commands.CommandException)26 Command (com.sk89q.minecraft.util.commands.Command)18 LocalPlayer (com.sk89q.worldguard.LocalPlayer)16 CommandPermissionsException (com.sk89q.minecraft.util.commands.CommandPermissionsException)15 World (com.sk89q.worldedit.world.World)14 ProtectedRegion (com.sk89q.worldguard.protection.regions.ProtectedRegion)12 RegionManager (com.sk89q.worldguard.protection.managers.RegionManager)11 GlobalProtectedRegion (com.sk89q.worldguard.protection.regions.GlobalProtectedRegion)10 LoggerToChatHandler (com.sk89q.worldguard.util.logging.LoggerToChatHandler)5 Logger (java.util.logging.Logger)5 ConfigurationManager (com.sk89q.worldguard.config.ConfigurationManager)4 RegionPermissionModel (com.sk89q.worldguard.internal.permission.RegionPermissionModel)4 CommandPermissions (com.sk89q.minecraft.util.commands.CommandPermissions)3 NestedCommand (com.sk89q.minecraft.util.commands.NestedCommand)3 TextComponent (com.sk89q.worldedit.util.formatting.text.TextComponent)3 ProtectedPolygonalRegion (com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion)3 RegionContainer (com.sk89q.worldguard.protection.regions.RegionContainer)3 WorldEdit (com.sk89q.worldedit.WorldEdit)2 Actor (com.sk89q.worldedit.extension.platform.Actor)2 Capability (com.sk89q.worldedit.extension.platform.Capability)2