com.mojang.brigadier.exceptions.CommandSyntaxException Java Examples

The following examples show how to use com.mojang.brigadier.exceptions.CommandSyntaxException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlayerCommand.java    From fabric-carpet with MIT License 7 votes vote down vote up
private static int shadow(CommandContext<ServerCommandSource> context)
{
    ServerPlayerEntity player = getPlayer(context);
    if (player instanceof EntityPlayerMPFake)
    {
        Messenger.m(context.getSource(), "r Cannot shadow fake players");
        return 0;
    }
    ServerPlayerEntity sendingPlayer = null;
    try
    {
        sendingPlayer = context.getSource().getPlayer();
    }
    catch (CommandSyntaxException ignored) { }

    if (sendingPlayer!=player && cantManipulate(context)) return 0;
    EntityPlayerMPFake.createShadow(player.server, player);
    return 1;
}
 
Example #2
Source File: GalacticraftCommands.java    From Galacticraft-Rewoven with MIT License 6 votes vote down vote up
private static int teleportMultiple(CommandContext<ServerCommandSource> context) {
    try {
        ServerWorld serverWorld = DimensionArgumentType.getDimensionArgument(context, "dimension");
        if (serverWorld == null) {
            context.getSource().sendError(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.failure.dimension").setStyle(Style.EMPTY.withColor(Formatting.RED)));
            return -1;
        }

        Collection<? extends Entity> entities = EntityArgumentType.getEntities(context, "entities");
        entities.forEach((Consumer<Entity>) entity -> {
            entity.changeDimension(serverWorld);
            context.getSource().sendFeedback(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.success.multiple", entities.size(), serverWorld.getRegistryKey().getValue()), true);
        });
    } catch (CommandSyntaxException ignore) {
        context.getSource().sendError(new TranslatableText("commands.galacticraft-rewoven.dimensiontp.failure.entity").setStyle(Style.EMPTY.withColor(Formatting.RED)));
        return -1;
    }
    return -1;
}
 
Example #3
Source File: ForgeClientSparkPlugin.java    From spark with GNU General Public License v3.0 6 votes vote down vote up
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ISuggestionProvider> context, SuggestionsBuilder builder) throws CommandSyntaxException {
    String chat = context.getInput();
    String[] split = chat.split(" ");
    if (split.length == 0 || (!split[0].equals("/sparkc") && !split[0].equals("/sparkclient"))) {
        return Suggestions.empty();
    }

    String[] args = Arrays.copyOfRange(split, 1, split.length);

    return CompletableFuture.supplyAsync(() -> {
        for (String suggestion : this.platform.tabCompleteCommand(new ForgeCommandSender(this.minecraft.player, this), args)) {
            builder.suggest(suggestion);
        }
        return builder.build();
    });
}
 
Example #4
Source File: NBTSerializableValue.java    From fabric-carpet with MIT License 6 votes vote down vote up
private boolean modify_merge(NbtPathArgumentType.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
{
    if (!(replacement instanceof CompoundTag))
    {
        return false;
    }
    Tag ownTag = getTag();
    try
    {
        for (Tag target : nbtPath.getOrInit(ownTag, CompoundTag::new))
        {
            if (!(target instanceof CompoundTag))
            {
                continue;
            }
            ((CompoundTag) target).copyFrom((CompoundTag) replacement);
        }
    }
    catch (CommandSyntaxException ignored)
    {
        return false;
    }
    return true;
}
 
Example #5
Source File: NBTSerializableValue.java    From fabric-carpet with MIT License 6 votes vote down vote up
@Override
public Value get(Value value)
{
    NbtPathArgumentType.NbtPath path = cachePath(value.getString());
    try
    {
        List<Tag> tags = path.get(getTag());
        if (tags.size()==0)
            return Value.NULL;
        if (tags.size()==1)
            return NBTSerializableValue.decodeTag(tags.get(0));
        return ListValue.wrap(tags.stream().map(NBTSerializableValue::decodeTag).collect(Collectors.toList()));
    }
    catch (CommandSyntaxException ignored) { }
    return Value.NULL;
}
 
Example #6
Source File: EntityArgumentType_1_12_2.java    From multiconnect with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
    if (!(context.getSource() instanceof CommandSource))
        return builder.buildFuture();

    StringReader reader = new StringReader(builder.getInput());
    reader.setCursor(builder.getStart());

    CompletableFuture<Suggestions> playerCompletions;
    if ((reader.canRead() && reader.peek() == '@') || !suggestPlayerNames) {
        playerCompletions = Suggestions.empty();
    } else {
        playerCompletions = ((CommandSource) context.getSource()).getCompletions((CommandContext<CommandSource>) context, builder.restart());
    }

    EntitySelectorParser parser = new EntitySelectorParser(reader, singleTarget, playersOnly);
    try {
        parser.parse();
    } catch (CommandSyntaxException ignore) {
    }
    CompletableFuture<Suggestions> selectorCompletions = parser.suggestor.apply(builder.restart());

    return CompletableFuture.allOf(playerCompletions, selectorCompletions)
            .thenCompose(v -> UnionArgumentType.mergeSuggestions(playerCompletions.join(), selectorCompletions.join()));
}
 
Example #7
Source File: NMS_1_13.java    From 1.13-Command-API with Apache License 2.0 6 votes vote down vote up
@Override
public FunctionWrapper[] getFunction(CommandContext cmdCtx, String str) throws CommandSyntaxException {
    Collection<CustomFunction> customFuncList = ArgumentTag.a(cmdCtx, str);

    FunctionWrapper[] result = new FunctionWrapper[customFuncList.size()];

    CustomFunctionData customFunctionData = getCLW(cmdCtx).getServer().getFunctionData();
    CommandListenerWrapper commandListenerWrapper = getCLW(cmdCtx).a().b(2);

    int count = 0;
    for(CustomFunction customFunction : customFuncList) {
        @SuppressWarnings("deprecation")
        NamespacedKey minecraftKey = new NamespacedKey(customFunction.a().b(), customFunction.a().getKey());
        ToIntBiFunction<CustomFunction, CommandListenerWrapper> obj = customFunctionData::a;

        FunctionWrapper wrapper = new FunctionWrapper(minecraftKey, obj, customFunction, commandListenerWrapper, e -> {
            return getCLW(cmdCtx).a(((CraftEntity) e).getHandle());
        });

        result[count] = wrapper;
        count++;
    }

    return result;
}
 
Example #8
Source File: StringReader.java    From brigadier with MIT License 6 votes vote down vote up
public boolean readBoolean() throws CommandSyntaxException {
    final int start = cursor;
    final String value = readString();
    if (value.isEmpty()) {
        throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedBool().createWithContext(this);
    }

    if (value.equals("true")) {
        return true;
    } else if (value.equals("false")) {
        return false;
    } else {
        cursor = start;
        throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidBool().createWithContext(this, value);
    }
}
 
Example #9
Source File: NMS_1_14_4.java    From 1.13-Command-API with Apache License 2.0 6 votes vote down vote up
@Override
public FunctionWrapper[] getFunction(CommandContext cmdCtx, String str) throws CommandSyntaxException {
    Collection<CustomFunction> customFuncList = ArgumentTag.a(cmdCtx, str);

    FunctionWrapper[] result = new FunctionWrapper[customFuncList.size()];

    CustomFunctionData customFunctionData = getCLW(cmdCtx).getServer().getFunctionData();
    CommandListenerWrapper commandListenerWrapper = getCLW(cmdCtx).a().b(2);

    int count = 0;
    for(CustomFunction customFunction : customFuncList) {
        @SuppressWarnings("deprecation")
        NamespacedKey minecraftKey = new NamespacedKey(customFunction.a().getNamespace(), customFunction.a().getKey());
        ToIntBiFunction<CustomFunction, CommandListenerWrapper> obj = customFunctionData::a;

        FunctionWrapper wrapper = new FunctionWrapper(minecraftKey, obj, customFunction, commandListenerWrapper, e -> {
            return (Object) getCLW(cmdCtx).a(((CraftEntity) e).getHandle());
        });

        result[count] = wrapper;
        count++;
    }

    return result;
}
 
Example #10
Source File: ModifyCmd.java    From Wurst7 with GNU General Public License v3.0 6 votes vote down vote up
private void add(ItemStack stack, String[] args) throws CmdError
{
	String nbt = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
	nbt = nbt.replace("$", "\u00a7").replace("\u00a7\u00a7", "$");
	
	if(!stack.hasTag())
		stack.setTag(new CompoundTag());
	
	try
	{
		CompoundTag tag = StringNbtReader.parse(nbt);
		stack.getTag().copyFrom(tag);
		
	}catch(CommandSyntaxException e)
	{
		ChatUtils.message(e.getMessage());
		throw new CmdError("NBT data is invalid.");
	}
}
 
Example #11
Source File: CommandDispatcherTest.java    From brigadier with MIT License 6 votes vote down vote up
@Test
public void testExecuteAmbiguousIncorrectArgument() throws Exception {
    subject.register(
        literal("foo").executes(command)
            .then(literal("bar"))
            .then(literal("baz"))
    );

    try {
        subject.execute("foo unknown", source);
        fail();
    } catch (final CommandSyntaxException ex) {
        assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument()));
        assertThat(ex.getCursor(), is(4));
    }
}
 
Example #12
Source File: NMS_1_14_3.java    From 1.13-Command-API with Apache License 2.0 6 votes vote down vote up
@Override
public FunctionWrapper[] getFunction(CommandContext cmdCtx, String str) throws CommandSyntaxException {
    Collection<CustomFunction> customFuncList = ArgumentTag.a(cmdCtx, str);

    FunctionWrapper[] result = new FunctionWrapper[customFuncList.size()];

    CustomFunctionData customFunctionData = getCLW(cmdCtx).getServer().getFunctionData();
    CommandListenerWrapper commandListenerWrapper = getCLW(cmdCtx).a().b(2);

    int count = 0;
    for(CustomFunction customFunction : customFuncList) {
        @SuppressWarnings("deprecation")
        NamespacedKey minecraftKey = new NamespacedKey(customFunction.a().b(), customFunction.a().getKey());
        ToIntBiFunction<CustomFunction, CommandListenerWrapper> obj = customFunctionData::a;

        FunctionWrapper wrapper = new FunctionWrapper(minecraftKey, obj, customFunction, commandListenerWrapper, e ->
                getCLW(cmdCtx).a(((CraftEntity) e).getHandle()));

        result[count] = wrapper;
        count++;
    }

    return result;
}
 
Example #13
Source File: TPArgumentType.java    From multiconnect with MIT License 5 votes vote down vote up
private static boolean isCoordinateArg(StringReader reader) {
    if (reader.peek() == '~') {
        reader.skip();
        if (reader.peek() == ' ')
            return true;
    }
    try {
        reader.readDouble();
    } catch (CommandSyntaxException e) {
        return false;
    }
    return reader.peek() == ' ';
}
 
Example #14
Source File: LongArgumentType.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public Long parse(final StringReader reader) throws CommandSyntaxException {
    final int start = reader.getCursor();
    final long result = reader.readLong();
    if (result < minimum) {
        reader.setCursor(start);
        throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooLow().createWithContext(reader, result, minimum);
    }
    if (result > maximum) {
        reader.setCursor(start);
        throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooHigh().createWithContext(reader, result, maximum);
    }
    return result;
}
 
Example #15
Source File: CommandDispatcherTest.java    From brigadier with MIT License 5 votes vote down vote up
@Test
public void testExecuteUnknownCommand() throws Exception {
    subject.register(literal("bar"));
    subject.register(literal("baz"));

    try {
        subject.execute("foo", source);
        fail();
    } catch (final CommandSyntaxException ex) {
        assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand()));
        assertThat(ex.getCursor(), is(0));
    }
}
 
Example #16
Source File: StringReaderTest.java    From brigadier with MIT License 5 votes vote down vote up
@Test
public void expect_none() throws Exception {
    final StringReader reader = new StringReader("");
    try {
        reader.expect('a');
        fail();
    } catch (final CommandSyntaxException ex) {
        assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedSymbol()));
        assertThat(ex.getCursor(), is(0));
    }
}
 
Example #17
Source File: DoubleArgumentType.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public Double parse(final StringReader reader) throws CommandSyntaxException {
    final int start = reader.getCursor();
    final double result = reader.readDouble();
    if (result < minimum) {
        reader.setCursor(start);
        throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.doubleTooLow().createWithContext(reader, result, minimum);
    }
    if (result > maximum) {
        reader.setCursor(start);
        throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.doubleTooHigh().createWithContext(reader, result, maximum);
    }
    return result;
}
 
Example #18
Source File: Arguments.java    From BoundingBoxOutlineReloaded with MIT License 5 votes vote down vote up
private static <T> T getArgumentValueOrDefault(CommandContext<CommandSource> context,
                                               String name,
                                               ArgumentFetcher<T> getValue,
                                               Supplier<T> defaultValue) throws CommandSyntaxException {
    try {
        return getValue.get(context, name);
    } catch (IllegalArgumentException exception) {
        return defaultValue.get();
    }
}
 
Example #19
Source File: SpawnCommand.java    From fabric-carpet with MIT License 5 votes vote down vote up
private static EntityCategory getCategory(String string) throws CommandSyntaxException
{
    if (!Arrays.stream(EntityCategory.values()).map(EntityCategory::getName).collect(Collectors.toSet()).contains(string))
    {
        throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(EntityCategory.values()).map(EntityCategory::getName).collect(Collectors.joining(", ")))).create();
    }
    return EntityCategory.valueOf(string.toUpperCase());
}
 
Example #20
Source File: ForgeServerSparkPlugin.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
    String[] args = processArgs(context);
    if (args == null) {
        return Suggestions.empty();
    }

    ServerPlayerEntity player = context.getSource().asPlayer();
    return CompletableFuture.supplyAsync(() -> {
        for (String suggestion : this.platform.tabCompleteCommand(new ForgeCommandSender(player, this), args)) {
            builder.suggest(suggestion);
        }
        return builder.build();
    });
}
 
Example #21
Source File: StringReaderTest.java    From brigadier with MIT License 5 votes vote down vote up
@Test
public void readQuotedString_invalidQuoteEscape() throws Exception {
    try {
        new StringReader("'hello\\\"\'world").readQuotedString();
    } catch (final CommandSyntaxException ex) {
        assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidEscape()));
        assertThat(ex.getCursor(), is(7));
    }
}
 
Example #22
Source File: LiteralCommandNode.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public void parse(final StringReader reader, final CommandContextBuilder<S> contextBuilder) throws CommandSyntaxException {
    final int start = reader.getCursor();
    final int end = parse(reader);
    if (end > -1) {
        contextBuilder.withNode(this, StringRange.between(start, end));
        return;
    }

    throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.literalIncorrect().createWithContext(reader, literal);
}
 
Example #23
Source File: NBTSerializableValue.java    From fabric-carpet with MIT License 5 votes vote down vote up
private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, Tag newElement, Tag currentTag)
{
    Collection<Tag> targets;
    try
    {
        targets = nbtPath.getOrInit(currentTag, ListTag::new);
    }
    catch (CommandSyntaxException e)
    {
        return false;
    }

    boolean modified = false;
    for (Tag target : targets)
    {
        if (!(target instanceof AbstractListTag))
        {
            continue;
        }
        try
        {
            AbstractListTag<?> targetList = (AbstractListTag) target;
            if (!targetList.addTag(index < 0 ? targetList.size() + index + 1 : index, newElement.copy()))
                return false;
            modified = true;
        }
        catch (IndexOutOfBoundsException ignored)
        {
        }
    }
    return modified;
}
 
Example #24
Source File: StringReaderTest.java    From brigadier with MIT License 5 votes vote down vote up
@Test
public void readDouble_invalid() throws Exception {
    try {
        new StringReader("12.34.56").readDouble();
    } catch (final CommandSyntaxException ex) {
        assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidDouble()));
        assertThat(ex.getCursor(), is(0));
    }
}
 
Example #25
Source File: NMS_1_14.java    From 1.13-Command-API with Apache License 2.0 5 votes vote down vote up
@Override
public Location getLocation(CommandContext cmdCtx, String str, LocationType locationType, CommandSender sender)
		throws CommandSyntaxException {
	switch (locationType) {
	case BLOCK_POSITION:
		BlockPosition blockPos = ArgumentPosition.a(cmdCtx, str);
		return new Location(getCommandSenderWorld(sender), blockPos.getX(), blockPos.getY(), blockPos.getZ());
	case PRECISE_POSITION:
		Vec3D vecPos = ArgumentVec3.a(cmdCtx, str);
		return new Location(getCommandSenderWorld(sender), vecPos.x, vecPos.y, vecPos.z);
	}
	return null;
}
 
Example #26
Source File: NMS_1_13_1.java    From 1.13-Command-API with Apache License 2.0 5 votes vote down vote up
@Override
public Location getLocation(CommandContext cmdCtx, String str, LocationType locationType, CommandSender sender) throws CommandSyntaxException {
    switch (locationType) {
        case BLOCK_POSITION:
            BlockPosition blockPos = ArgumentPosition.a(cmdCtx, str);
            return new Location(getCommandSenderWorld(sender), blockPos.getX(), blockPos.getY(), blockPos.getZ());
        case PRECISE_POSITION:
            Vec3D vecPos = ArgumentVec3.a(cmdCtx, str);
            return new Location(getCommandSenderWorld(sender), vecPos.x, vecPos.y, vecPos.z);
    }
    return null;
}
 
Example #27
Source File: SettingsManager.java    From fabric-carpet with MIT License 5 votes vote down vote up
private ParsedRule<?> contextRule(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException
{
    String ruleName = StringArgumentType.getString(ctx, "rule");
    ParsedRule<?> rule = getRule(ruleName);
    if (rule == null)
        throw new SimpleCommandExceptionType(Messenger.c("rb "+ tr("ui.unknown_rule","Unknown rule")+": "+ruleName)).create();
    return rule;
}
 
Example #28
Source File: NMS_1_13.java    From 1.13-Command-API with Apache License 2.0 5 votes vote down vote up
@Override
public Player getPlayer(CommandContext cmdCtx, String str) throws CommandSyntaxException {
    Player target = Bukkit.getPlayer(((GameProfile) ArgumentProfile.a(cmdCtx, str).iterator().next()).getId());
    if (target == null) {
        throw ArgumentProfile.a.create();
    } else {
        return target;
    }
}
 
Example #29
Source File: NMS_1_14_3.java    From 1.13-Command-API with Apache License 2.0 5 votes vote down vote up
@Override
public Location2D getLocation2D(CommandContext cmdCtx, String key, LocationType locationType2d, CommandSender sender) throws CommandSyntaxException {
    switch (locationType2d) {
        case BLOCK_POSITION:
            BlockPosition2D blockPos = ArgumentVec2I.a(cmdCtx, key);
            return new Location2D(getCommandSenderWorld(sender), blockPos.a, blockPos.b);
        case PRECISE_POSITION:
            Vec2F vecPos = ArgumentVec2.a(cmdCtx, key);
            return new Location2D(getCommandSenderWorld(sender), vecPos.i, vecPos.j);
    }
    return null;
}
 
Example #30
Source File: SpawnCommand.java    From fabric-carpet with MIT License 5 votes vote down vote up
private static int setSpawnRates(ServerCommandSource source, String mobtype, int rounds) throws CommandSyntaxException
{
    EntityCategory cat = getCategory(mobtype);
    SpawnReporter.spawn_tries.put(cat, rounds);
    Messenger.m(source, "gi "+mobtype+" mobs will now spawn "+rounds+" times per tick");
    return 1;
}