下面列出了java.util.function.ToIntBiFunction#com.mojang.brigadier.exceptions.CommandSyntaxException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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.");
}
}
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);
}
}
@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;
}
@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()));
}
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;
}
@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;
}
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;
}
@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;
}
@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));
}
}
@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;
}
@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();
});
}
@Test
public void parse_tooBig() throws Exception {
final StringReader reader = new StringReader("5");
try {
integer(-100, 0).parse(reader);
fail();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.integerTooHigh()));
assertThat(ex.getCursor(), is(0));
}
}
@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;
}
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<S> context, SuggestionsBuilder builder) throws CommandSyntaxException {
Collection<String> possibleValues = getPossibleValues();
if(possibleValues.isEmpty()) return Suggestions.empty();
String remaining = builder.getRemaining().toLowerCase();
for (String str : possibleValues) {
if (str.toLowerCase().startsWith(remaining)) {
builder.suggest(str = StringArgumentType.escapeIfRequired(str));
}
}
return builder.buildFuture();
}
private CompoundTag createNBT()
{
try
{
return StringNbtReader.parse(
"{display:{Lore:['\"\u00a7r1. Place item in dispenser.\"','\"\u00a7r2. Dispense item.\"','\"\u00a7r3. Ssss... BOOM!\"'],Name:'{\"text\":\"\u00a7rServer Creeper\"}'},EntityTag:{CustomName:\"TEST\",id:\"Creeper\",CustomNameVisible:1}}");
}catch(CommandSyntaxException e)
{
throw new RuntimeException(e);
}
}
@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));
}
}
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() == ' ';
}
@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));
}
}
@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;
}
@Override
public Void parse(StringReader reader) throws CommandSyntaxException {
if (reader.canRead() && reader.peek() == '@') {
new EntitySelectorParser(reader, singleTarget, playersOnly).parse();
} else {
reader.readUnquotedString();
}
return null;
}
@Test
public void parse_noSpaceSeparator() throws Exception {
subject.register(literal("foo").then(argument("bar", integer()).executes(command)));
try {
subject.execute("foo$", source);
fail();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand()));
assertThat(ex.getCursor(), is(0));
}
}
@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));
}
}
@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);
}
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;
}
@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;
}
@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;
}
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());
}
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;
}
@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;
}
}