Search in sources :

Example 11 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method loadMapFromFile.

private CommandResult loadMapFromFile(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final ItemStack map = player.itemInHand(HandTypes.MAIN_HAND);
    if (map.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    final File file = new File("map.png");
    if (!file.isFile()) {
        try {
            if (!file.createNewFile()) {
                throw new IOException("failed to create new file :(");
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    final BufferedImage image;
    try {
        image = ImageIO.read(file);
    } catch (final IOException e) {
        throw new CommandException(Component.text(e.getMessage()), e);
    }
    final MapCanvas canvas = MapCanvas.builder().fromImage(image).build();
    final MapInfo mapInfo = map.require(Keys.MAP_INFO);
    mapInfo.offer(Keys.MAP_TRACKS_PLAYERS, false);
    mapInfo.offer(Keys.MAP_DECORATIONS, Collections.emptySet());
    mapInfo.offer(Keys.MAP_LOCKED, true);
    mapInfo.offer(Keys.MAP_CANVAS, canvas);
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) MapCanvas(org.spongepowered.api.map.MapCanvas) MapInfo(org.spongepowered.api.map.MapInfo) CommandException(org.spongepowered.api.command.exception.CommandException) IOException(java.io.IOException) ItemStack(org.spongepowered.api.item.inventory.ItemStack) File(java.io.File) BufferedImage(java.awt.image.BufferedImage)

Example 12 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method enableUnlimitedTracking.

private CommandResult enableUnlimitedTracking(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final ItemStack heldMap = player.itemInHand(HandTypes.MAIN_HAND);
    if (heldMap.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    heldMap.require(Keys.MAP_INFO).offer(Keys.MAP_UNLIMITED_TRACKING, true);
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 13 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method randomDecorations.

private CommandResult randomDecorations(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final ItemStack heldMap = player.itemInHand(HandTypes.MAIN_HAND);
    if (heldMap.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    player.sendMessage(Component.text("Getting mapInfo"));
    final MapInfo mapInfo = heldMap.require(Keys.MAP_INFO);
    mapInfo.offer(Keys.MAP_TRACKS_PLAYERS, true);
    final Set<MapDecoration> decorations = new HashSet<>();
    int x = Byte.MIN_VALUE;
    int y = Byte.MIN_VALUE;
    final List<MapDecorationType> types = RegistryTypes.MAP_DECORATION_TYPE.get().stream().collect(Collectors.toList());
    final Collection<MapDecorationOrientation> orientations = Sponge.game().registry(RegistryTypes.MAP_DECORATION_ORIENTATION).stream().collect(Collectors.toList());
    player.sendMessage(Component.text("Number of orientations: " + orientations.size()));
    player.sendMessage(Component.text("EAST: " + MapDecorationOrientations.EAST.get().key(RegistryTypes.MAP_DECORATION_ORIENTATION).toString()));
    for (final MapDecorationOrientation dir : orientations) {
        decorations.add(MapDecoration.builder().type(types.get(player.random().nextInt(types.size()))).rotation(dir).position(Vector2i.from(x, y)).build());
        player.sendMessage(Component.text(dir.key(RegistryTypes.MAP_DECORATION_ORIENTATION).value()).append(Component.text("x: " + x)).append(Component.text("y: " + y)));
        x += 16;
        if (x > Byte.MAX_VALUE) {
            y += 16;
            x = Byte.MIN_VALUE;
            if (y > Byte.MAX_VALUE) {
                player.sendMessage(Component.text("out of room, stopping"));
                mapInfo.offer(Keys.MAP_DECORATIONS, decorations);
                return CommandResult.success();
            }
        }
    }
    mapInfo.offer(Keys.MAP_DECORATIONS, decorations);
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) MapDecorationOrientation(org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation) MapInfo(org.spongepowered.api.map.MapInfo) MapDecoration(org.spongepowered.api.map.decoration.MapDecoration) MapDecorationType(org.spongepowered.api.map.decoration.MapDecorationType) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack) HashSet(java.util.HashSet)

Example 14 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class SpongeCommandDispatcher method execute.

@Override
public int execute(final StringReader input, final CommandSourceStack source) throws CommandSyntaxException {
    try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
        final CommandSourceStackBridge sourceBridge = (CommandSourceStackBridge) source;
        frame.addContext(EventContextKeys.COMMAND, input.getString());
        sourceBridge.bridge$updateFrameFromCommandSource(frame);
        return this.commandManager.process(sourceBridge.bridge$withCurrentCause(), input.getRemaining()).result();
    } catch (final CommandException e) {
        throw new net.minecraft.commands.CommandRuntimeException(SpongeAdventure.asVanilla(e.componentMessage()));
    }
}
Also used : CauseStackManager(org.spongepowered.api.event.CauseStackManager) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) CommandException(org.spongepowered.api.command.exception.CommandException)

Example 15 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class SpongeCommandManager method process.

public CommandResult process(final CommandCause cause, final String arguments) throws CommandException, CommandSyntaxException {
    final String[] splitArg = arguments.split(" ", 2);
    final String originalCommand = splitArg[0];
    final String originalArgs = splitArg.length == 2 ? splitArg[1] : "";
    final String command;
    final String args;
    final ExecuteCommandEvent.Pre preEvent = SpongeEventFactory.createExecuteCommandEventPre(cause.cause(), originalArgs, originalArgs, originalCommand, originalCommand, cause, Optional.empty(), false);
    if (this.game.eventManager().post(preEvent)) {
        return preEvent.result().orElse(SpongeCommandManager.UNKNOWN_ERROR);
    }
    command = preEvent.command();
    args = preEvent.arguments();
    final SpongeCommandMapping mapping = this.commandMappings.get(command.toLowerCase());
    if (mapping == null) {
        throw new CommandException(Component.text("Unknown command. Type /help for a list of commands."));
    }
    final Object source = cause.cause().root();
    final CommandResult result;
    try (final CommandPhaseContext context = GeneralPhase.State.COMMAND.createPhaseContext(PhaseTracker.getInstance()).source(source).command(args).commandMapping(mapping)) {
        if (source instanceof ServerPlayer) {
            final ServerPlayer serverPlayer = (ServerPlayer) source;
            context.creator(serverPlayer.uniqueId());
            context.notifier(serverPlayer.uniqueId());
        }
        context.buildAndSwitch();
        try {
            result = this.processCommand(cause, mapping, arguments, command, args);
        } catch (final CommandException exception) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(exception.componentMessage()).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(exception, command, args, cause);
            }
            throw exception;
        } catch (final CommandSyntaxException cse) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(SpongeAdventure.asAdventure(cse.getRawMessage())).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(cse, command, args, cause);
            }
            throw cse;
        } catch (final net.minecraft.commands.CommandRuntimeException ex) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(SpongeAdventure.asAdventure(ex.getComponent())).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(ex, command, args, cause);
            }
            throw ex;
        } catch (final Throwable thr) {
            this.prettyPrintThrowableError(thr, command, args, cause);
            Component excBuilder;
            if (thr instanceof ComponentMessageThrowable) {
                final Component text = ((ComponentMessageThrowable) thr).componentMessage();
                excBuilder = text == null ? Component.text("null") : text;
            } else {
                excBuilder = Component.text(String.valueOf(thr.getMessage()));
            }
            if (cause.hasPermission(Constants.Permissions.DEBUG_HOVER_STACKTRACE)) {
                final StringWriter writer = new StringWriter();
                thr.printStackTrace(new PrintWriter(writer));
                excBuilder = excBuilder.hoverEvent(HoverEvent.showText(Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
                "\n"))));
            }
            final Component error = Component.text().content("Unexpected error occurred while executing command: ").append(excBuilder).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, CommandResult.error(error));
            throw new CommandException(error, thr);
        }
        this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, result);
        if (!result.isSuccess()) {
            cause.sendMessage(Identity.nil(), result.errorMessage().map(x -> x.colorIfAbsent(NamedTextColor.RED)).orElseGet(() -> Component.text().content(String.format("An empty error result was returned while executing the command \"%s\"", arguments)).color(NamedTextColor.RED).build()));
        }
        return result;
    }
}
Also used : ExecuteCommandEvent(org.spongepowered.api.event.command.ExecuteCommandEvent) CommandException(org.spongepowered.api.command.exception.CommandException) SpongeCommandResult(org.spongepowered.common.command.result.SpongeCommandResult) CommandResult(org.spongepowered.api.command.CommandResult) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) StringWriter(java.io.StringWriter) CommandPhaseContext(org.spongepowered.common.event.tracking.phase.general.CommandPhaseContext) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) Component(net.kyori.adventure.text.Component) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) PrintWriter(java.io.PrintWriter)

Aggregations

CommandException (org.spongepowered.api.command.exception.CommandException)26 Player (org.spongepowered.api.entity.living.player.Player)19 ItemStack (org.spongepowered.api.item.inventory.ItemStack)17 MapInfo (org.spongepowered.api.map.MapInfo)10 Component (net.kyori.adventure.text.Component)8 Audience (net.kyori.adventure.audience.Audience)6 CommandResult (org.spongepowered.api.command.CommandResult)5 ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)5 Inject (com.google.inject.Inject)4 UUID (java.util.UUID)4 Identity (net.kyori.adventure.identity.Identity)4 NamedTextColor (net.kyori.adventure.text.format.NamedTextColor)4 Sponge (org.spongepowered.api.Sponge)4 Command (org.spongepowered.api.command.Command)4 Listener (org.spongepowered.api.event.Listener)4 RegisterCommandEvent (org.spongepowered.api.event.lifecycle.RegisterCommandEvent)4 PluginContainer (org.spongepowered.plugin.PluginContainer)4 Plugin (org.spongepowered.plugin.builtin.jvm.Plugin)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3