Search in sources :

Example 16 with CommandException

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

the class BukkitStringMatcher method matchPlayers.

@Override
public Iterable<? extends LocalPlayer> matchPlayers(Actor source, String filter) throws CommandException {
    if (Bukkit.getServer().getOnlinePlayers().isEmpty()) {
        throw new CommandException("No players matched query.");
    }
    List<LocalPlayer> wgPlayers = Bukkit.getServer().getOnlinePlayers().stream().map(player -> WorldGuardPlugin.inst().wrapPlayer(player)).collect(Collectors.toList());
    if (filter.equals("*")) {
        return checkPlayerMatch(wgPlayers);
    }
    // Handle special hash tag groups
    if (filter.charAt(0) == '#') {
        // calling source
        if (filter.equalsIgnoreCase("#world")) {
            List<LocalPlayer> players = new ArrayList<>();
            LocalPlayer sourcePlayer = WorldGuard.getInstance().checkPlayer(source);
            World sourceWorld = sourcePlayer.getWorld();
            for (LocalPlayer player : wgPlayers) {
                if (player.getWorld().equals(sourceWorld)) {
                    players.add(player);
                }
            }
            return checkPlayerMatch(players);
        // Handle #near, which is for nearby players.
        } else if (filter.equalsIgnoreCase("#near")) {
            List<LocalPlayer> players = new ArrayList<>();
            LocalPlayer sourcePlayer = WorldGuard.getInstance().checkPlayer(source);
            World sourceWorld = sourcePlayer.getWorld();
            Vector3 sourceVector = sourcePlayer.getLocation().toVector();
            for (LocalPlayer player : wgPlayers) {
                if (player.getWorld().equals(sourceWorld) && player.getLocation().toVector().distanceSq(sourceVector) < 900) {
                    players.add(player);
                }
            }
            return checkPlayerMatch(players);
        } else {
            throw new CommandException("Invalid group '" + filter + "'.");
        }
    }
    List<LocalPlayer> players = matchPlayerNames(filter);
    return checkPlayerMatch(players);
}
Also used : StringMatcher(com.sk89q.worldguard.internal.platform.StringMatcher) Collection(java.util.Collection) World(com.sk89q.worldedit.world.World) LocalPlayer(com.sk89q.worldguard.LocalPlayer) Player(org.bukkit.entity.Player) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) CommandException(com.sk89q.minecraft.util.commands.CommandException) Actor(com.sk89q.worldedit.extension.platform.Actor) List(java.util.List) BukkitAdapter(com.sk89q.worldedit.bukkit.BukkitAdapter) Capability(com.sk89q.worldedit.extension.platform.Capability) Vector3(com.sk89q.worldedit.math.Vector3) WorldGuard(com.sk89q.worldguard.WorldGuard) WorldEdit(com.sk89q.worldedit.WorldEdit) Bukkit(org.bukkit.Bukkit) LocalPlayer(com.sk89q.worldguard.LocalPlayer) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Vector3(com.sk89q.worldedit.math.Vector3) CommandException(com.sk89q.minecraft.util.commands.CommandException) World(com.sk89q.worldedit.world.World)

Example 17 with CommandException

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

the class WorldGuardCommands method report.

@Command(aliases = { "report" }, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({ "worldguard.report" })
public void report(CommandContext args, final Actor sender) throws CommandException, AuthorizationException {
    ReportList report = new ReportList("Report");
    worldGuard.getPlatform().addPlatformReports(report);
    report.add(new SystemInfoReport());
    report.add(new ConfigReport());
    if (sender instanceof LocalPlayer) {
        report.add(new ApplicableRegionsReport((LocalPlayer) sender));
    }
    String result = report.toString();
    try {
        File dest = new File(worldGuard.getPlatform().getConfigDir().toFile(), "report.txt");
        Files.write(result, dest, StandardCharsets.UTF_8);
        sender.print("WorldGuard report written to " + dest.getAbsolutePath());
    } catch (IOException e) {
        throw new CommandException("Failed to write report: " + e.getMessage());
    }
    if (args.hasFlag('p')) {
        sender.checkPermission("worldguard.report.pastebin");
        ActorCallbackPaste.pastebin(worldGuard.getSupervisor(), sender, result, "WorldGuard report: %s.report");
    }
}
Also used : LocalPlayer(com.sk89q.worldguard.LocalPlayer) IOException(java.io.IOException) CommandException(com.sk89q.minecraft.util.commands.CommandException) SystemInfoReport(com.sk89q.worldedit.util.report.SystemInfoReport) File(java.io.File) ReportList(com.sk89q.worldedit.util.report.ReportList) ApplicableRegionsReport(com.sk89q.worldguard.util.report.ApplicableRegionsReport) ConfigReport(com.sk89q.worldguard.util.report.ConfigReport) NestedCommand(com.sk89q.minecraft.util.commands.NestedCommand) Command(com.sk89q.minecraft.util.commands.Command) CommandPermissions(com.sk89q.minecraft.util.commands.CommandPermissions)

Example 18 with CommandException

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

the class WorldGuardCommands method profile.

@Command(aliases = { "profile" }, usage = "[-p] [-i <interval>] [-t <thread filter>] [<minutes>]", desc = "Profile the CPU usage of the server", min = 0, max = 1, flags = "t:i:p")
@CommandPermissions("worldguard.profile")
public void profile(final CommandContext args, final Actor sender) throws CommandException, AuthorizationException {
    Predicate<ThreadInfo> threadFilter;
    String threadName = args.getFlag('t');
    final boolean pastebin;
    if (args.hasFlag('p')) {
        sender.checkPermission("worldguard.report.pastebin");
        pastebin = true;
    } else {
        pastebin = false;
    }
    if (threadName == null) {
        threadFilter = new ThreadIdFilter(Thread.currentThread().getId());
    } else if (threadName.equals("*")) {
        threadFilter = thread -> true;
    } else {
        threadFilter = new ThreadNameFilter(threadName);
    }
    int minutes;
    if (args.argsLength() == 0) {
        minutes = 5;
    } else {
        minutes = args.getInteger(0);
        if (minutes < 1) {
            throw new CommandException("You must run the profile for at least 1 minute.");
        } else if (minutes > 10) {
            throw new CommandException("You can profile for, at maximum, 10 minutes.");
        }
    }
    int interval = 20;
    if (args.hasFlag('i')) {
        interval = args.getFlagInteger('i');
        if (interval < 1 || interval > 100) {
            throw new CommandException("Interval must be between 1 and 100 (in milliseconds)");
        }
        if (interval < 10) {
            sender.printDebug("Note: A low interval may cause additional slowdown during profiling.");
        }
    }
    Sampler sampler;
    synchronized (this) {
        if (activeSampler != null) {
            throw new CommandException("A profile is currently in progress! Please use /wg stopprofile to cancel the current profile.");
        }
        SamplerBuilder builder = new SamplerBuilder();
        builder.setThreadFilter(threadFilter);
        builder.setRunTime(minutes, TimeUnit.MINUTES);
        builder.setInterval(interval);
        sampler = activeSampler = builder.start();
    }
    sender.print(TextComponent.of("Starting CPU profiling. Results will be available in " + minutes + " minutes.", TextColor.LIGHT_PURPLE).append(TextComponent.newline()).append(TextComponent.of("Use ", TextColor.GRAY)).append(TextComponent.of("/wg stopprofile", TextColor.AQUA).clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, "/wg stopprofile"))).append(TextComponent.of(" at any time to cancel CPU profiling.", TextColor.GRAY)));
    worldGuard.getSupervisor().monitor(FutureForwardingTask.create(sampler.getFuture(), "CPU profiling for " + minutes + " minutes", sender));
    sampler.getFuture().addListener(() -> {
        synchronized (WorldGuardCommands.this) {
            activeSampler = null;
        }
    }, MoreExecutors.directExecutor());
    Futures.addCallback(sampler.getFuture(), new FutureCallback<>() {

        @Override
        public void onSuccess(Sampler result) {
            String output = result.toString();
            try {
                File dest = new File(worldGuard.getPlatform().getConfigDir().toFile(), "profile.txt");
                Files.write(output, dest, StandardCharsets.UTF_8);
                sender.print("CPU profiling data written to " + dest.getAbsolutePath());
            } catch (IOException e) {
                sender.printError("Failed to write CPU profiling data: " + e.getMessage());
            }
            if (pastebin) {
                ActorCallbackPaste.pastebin(worldGuard.getSupervisor(), sender, output, "Profile result: %s.profile");
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
        }
    }, MoreExecutors.directExecutor());
}
Also used : Sampler(com.sk89q.worldguard.util.profiler.SamplerBuilder.Sampler) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) CommandPermissions(com.sk89q.minecraft.util.commands.CommandPermissions) FutureForwardingTask(com.sk89q.worldedit.util.task.FutureForwardingTask) SystemInfoReport(com.sk89q.worldedit.util.report.SystemInfoReport) World(com.sk89q.worldedit.world.World) ActorCallbackPaste(com.sk89q.worldedit.util.paste.ActorCallbackPaste) SamplerBuilder(com.sk89q.worldguard.util.profiler.SamplerBuilder) Level(java.util.logging.Level) CommandException(com.sk89q.minecraft.util.commands.CommandException) Task(com.sk89q.worldedit.util.task.Task) ApplicableRegionsReport(com.sk89q.worldguard.util.report.ApplicableRegionsReport) ThreadInfo(java.lang.management.ThreadInfo) AuthorizationException(com.sk89q.worldedit.util.auth.AuthorizationException) Files(com.google.common.io.Files) TextColor(com.sk89q.worldedit.util.formatting.text.format.TextColor) ClickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent) WorldGuard(com.sk89q.worldguard.WorldGuard) NestedCommand(com.sk89q.minecraft.util.commands.NestedCommand) ConfigReport(com.sk89q.worldguard.util.report.ConfigReport) WorldEdit(com.sk89q.worldedit.WorldEdit) ReportList(com.sk89q.worldedit.util.report.ReportList) Nullable(javax.annotation.Nullable) TaskStateComparator(com.sk89q.worldedit.util.task.TaskStateComparator) ThreadNameFilter(com.sk89q.worldguard.util.profiler.ThreadNameFilter) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Predicate(java.util.function.Predicate) LoggerToChatHandler(com.sk89q.worldguard.util.logging.LoggerToChatHandler) ThreadIdFilter(com.sk89q.worldguard.util.profiler.ThreadIdFilter) LocalPlayer(com.sk89q.worldguard.LocalPlayer) IOException(java.io.IOException) MessageBox(com.sk89q.worldedit.util.formatting.component.MessageBox) Logger(java.util.logging.Logger) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Actor(com.sk89q.worldedit.extension.platform.Actor) TimeUnit(java.util.concurrent.TimeUnit) TextComponentProducer(com.sk89q.worldedit.util.formatting.component.TextComponentProducer) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) ConfigurationManager(com.sk89q.worldguard.config.ConfigurationManager) Capability(com.sk89q.worldedit.extension.platform.Capability) CommandContext(com.sk89q.minecraft.util.commands.CommandContext) Command(com.sk89q.minecraft.util.commands.Command) ThreadNameFilter(com.sk89q.worldguard.util.profiler.ThreadNameFilter) ThreadIdFilter(com.sk89q.worldguard.util.profiler.ThreadIdFilter) CommandException(com.sk89q.minecraft.util.commands.CommandException) IOException(java.io.IOException) SamplerBuilder(com.sk89q.worldguard.util.profiler.SamplerBuilder) ThreadInfo(java.lang.management.ThreadInfo) Sampler(com.sk89q.worldguard.util.profiler.SamplerBuilder.Sampler) File(java.io.File) NestedCommand(com.sk89q.minecraft.util.commands.NestedCommand) Command(com.sk89q.minecraft.util.commands.Command) CommandPermissions(com.sk89q.minecraft.util.commands.CommandPermissions)

Example 19 with CommandException

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

the class MemberCommands method removeOwner.

@Command(aliases = { "removeowner", "remowner", "ro" }, usage = "<id> <owners...>", flags = "naw:", desc = "Remove an owner to a region", min = 1)
public void removeOwner(CommandContext args, Actor sender) throws CommandException {
    warnAboutSaveFailures(sender);
    // Get the world
    World world = checkWorld(args, sender, 'w');
    String id = args.getString(0);
    RegionManager manager = checkRegionManager(world);
    ProtectedRegion region = checkExistingRegion(manager, id, true);
    // Check permissions
    if (!getPermissionModel(sender).mayRemoveOwners(region)) {
        throw new CommandPermissionsException();
    }
    Callable<DefaultDomain> callable;
    if (args.hasFlag('a')) {
        callable = region::getOwners;
    } else {
        if (args.argsLength() < 2) {
            throw new CommandException("List some names to remove, or use -a to remove all.");
        }
        // Resolve owners asynchronously
        DomainInputResolver resolver = new DomainInputResolver(WorldGuard.getInstance().getProfileService(), args.getParsedPaddedSlice(1, 0));
        resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_AND_NAME);
        callable = resolver;
    }
    final String description = String.format("Removing owners from the region '%s' on '%s'", region.getId(), world.getName());
    AsyncCommandBuilder.wrap(callable, sender).registerWithSupervisor(worldGuard.getSupervisor(), description).sendMessageAfterDelay("(Please wait... querying player names...)").onSuccess(String.format("Region '%s' updated with owners removed.", region.getId()), region.getOwners()::removeAll).onFailure("Failed to remove owners", worldGuard.getExceptionConverter()).buildAndExec(worldGuard.getExecutorService());
}
Also used : DomainInputResolver(com.sk89q.worldguard.protection.util.DomainInputResolver) CommandPermissionsException(com.sk89q.minecraft.util.commands.CommandPermissionsException) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) RegionManager(com.sk89q.worldguard.protection.managers.RegionManager) CommandException(com.sk89q.minecraft.util.commands.CommandException) World(com.sk89q.worldedit.world.World) DefaultDomain(com.sk89q.worldguard.domains.DefaultDomain) Command(com.sk89q.minecraft.util.commands.Command)

Example 20 with CommandException

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

the class RegionCommands method teleport.

/**
 * Teleport to a region
 *
 * @param args the arguments
 * @param sender the sender
 * @throws CommandException any error
 */
@Command(aliases = { "teleport", "tp" }, usage = "[-w world] [-c|s] <id>", flags = "csw:", desc = "Teleports you to the location associated with the region.", min = 1, max = 1)
public void teleport(CommandContext args, Actor sender) throws CommandException {
    LocalPlayer player = worldGuard.checkPlayer(sender);
    Location teleportLocation;
    // Lookup the existing region
    World world = checkWorld(args, player, 'w');
    RegionManager regionManager = checkRegionManager(world);
    ProtectedRegion existing = checkExistingRegion(regionManager, args.getString(0), true);
    // Check permissions
    if (!getPermissionModel(player).mayTeleportTo(existing)) {
        throw new CommandPermissionsException();
    }
    // -s for spawn location
    if (args.hasFlag('s')) {
        teleportLocation = FlagValueCalculator.getEffectiveFlagOf(existing, Flags.SPAWN_LOC, player);
        if (teleportLocation == null) {
            throw new CommandException("The region has no spawn point associated.");
        }
    } else if (args.hasFlag('c')) {
        // Check permissions
        if (!getPermissionModel(player).mayTeleportToCenter(existing)) {
            throw new CommandPermissionsException();
        }
        Region region = WorldEditRegionConverter.convertToRegion(existing);
        if (region == null || region.getCenter() == null) {
            throw new CommandException("The region has no center point.");
        }
        if (player.getGameMode() == GameModes.SPECTATOR) {
            teleportLocation = new Location(world, region.getCenter(), 0, 0);
        } else {
            // It doesn't return the found location and it can't be checked if the location is inside the region.
            throw new CommandException("Center teleport is only availible in Spectator gamemode.");
        }
    } else {
        teleportLocation = FlagValueCalculator.getEffectiveFlagOf(existing, Flags.TELE_LOC, player);
        if (teleportLocation == null) {
            throw new CommandException("The region has no teleport point associated.");
        }
    }
    String message = FlagValueCalculator.getEffectiveFlagOf(existing, Flags.TELE_MESSAGE, player);
    // If message.isEmpty(), no message is sent by LocalPlayer#teleport(...)
    if (message == null) {
        message = Flags.TELE_MESSAGE.getDefault();
    }
    player.teleport(teleportLocation, message.replace("%id%", existing.getId()), "Unable to teleport to region '" + existing.getId() + "'.");
}
Also used : CommandPermissionsException(com.sk89q.minecraft.util.commands.CommandPermissionsException) LocalPlayer(com.sk89q.worldguard.LocalPlayer) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) RegionManager(com.sk89q.worldguard.protection.managers.RegionManager) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GlobalProtectedRegion(com.sk89q.worldguard.protection.regions.GlobalProtectedRegion) ProtectedPolygonalRegion(com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion) Region(com.sk89q.worldedit.regions.Region) CommandException(com.sk89q.minecraft.util.commands.CommandException) World(com.sk89q.worldedit.world.World) Location(com.sk89q.worldedit.util.Location) Command(com.sk89q.minecraft.util.commands.Command)

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