use of org.spongepowered.api.command.args.ArgumentParseException in project SpongeAPI by SpongePowered.
the class ChildCommandsTest method testSimpleChildCommandIsThrownOnErrorWhenSelected.
@Test
public void testSimpleChildCommandIsThrownOnErrorWhenSelected() throws CommandException {
final AtomicBoolean parentExecuted = new AtomicBoolean();
final AtomicBoolean childExecuted = new AtomicBoolean();
final CommandSpec spec = CommandSpec.builder().children(ImmutableMap.of(ImmutableList.of("child"), CommandSpec.builder().arguments(GenericArguments.literal(Text.of("test"), "test")).executor((src, args) -> {
childExecuted.set(true);
return CommandResult.builder().successCount(1).build();
}).build())).arguments(GenericArguments.literal(Text.of("t"), "child")).executor((src, args) -> {
parentExecuted.set(true);
return CommandResult.success();
}).childArgumentParseExceptionFallback(false).build();
final SimpleDispatcher execute = new SimpleDispatcher();
execute.register(spec, "parent");
try {
execute.process(mock(CommandSource.class), "parent child");
} catch (ArgumentParseException ex) {
// ignored - we check this with the booleans
}
assertFalse(childExecuted.get());
assertFalse(parentExecuted.get());
}
use of org.spongepowered.api.command.args.ArgumentParseException in project LanternServer by LanternPowered.
the class CommandTime method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
final Map<String, Integer> presets = new HashMap<>();
presets.put("day", 1000);
presets.put("night", 13000);
specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none())).child(CommandSpec.builder().arguments(new CommandElement(Text.of("value")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
final String input = args.next().toLowerCase();
// Try to use one of the presets first
if (presets.containsKey(input)) {
return presets.get(input);
}
try {
return Integer.parseInt(input);
} catch (NumberFormatException ex) {
throw args.createError(t("Expected an integer or a valid preset, but input '%s' was not", input));
}
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
final String prefix = args.nextIfPresent().orElse("");
return presets.keySet().stream().filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
}
}).executor((src, args) -> {
WorldProperties world = CommandHelper.getWorldProperties(src, args);
int time = args.<Integer>getOne("value").get();
world.setWorldTime(time);
src.sendMessage(t("commands.time.set", time));
return CommandResult.success();
}).build(), "set").child(CommandSpec.builder().arguments(GenericArguments.integer(Text.of("value"))).executor((src, args) -> {
WorldProperties world = CommandHelper.getWorldProperties(src, args);
int time = args.<Integer>getOne("value").get();
world.setWorldTime(world.getWorldTime() + time);
src.sendMessage(t("commands.time.added", time));
return CommandResult.success();
}).build(), "add").child(CommandSpec.builder().arguments(GenericArguments2.enumValue(Text.of("value"), QueryType.class)).executor((src, args) -> {
WorldProperties world = CommandHelper.getWorldProperties(src, args);
QueryType queryType = args.<QueryType>getOne("value").get();
int result;
switch(queryType) {
case DAYTIME:
result = (int) (world.getWorldTime() % Integer.MAX_VALUE);
break;
case GAMETIME:
result = (int) (world.getTotalTime() % Integer.MAX_VALUE);
break;
case DAY:
result = (int) (world.getTotalTime() / 24000);
break;
default:
throw new IllegalStateException("Unknown query type: " + queryType);
}
src.sendMessage(t("commands.time.query", result));
return CommandResult.builder().successCount(1).queryResult(result).build();
}).build(), "query");
}
use of org.spongepowered.api.command.args.ArgumentParseException in project LanternServer by LanternPowered.
the class CommandHelp method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
final Comparator<CommandMapping> comparator = Comparator.comparing(CommandMapping::getPrimaryAlias);
specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("command")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
return args.next();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
final String nextArg = args.nextIfPresent().orElse("");
return Lantern.getGame().getCommandManager().getAliases().stream().filter(new StartsWithPredicate(nextArg)).collect(Collectors.toList());
}
})).description(Text.of("View a list of all commands")).extendedDescription(Text.of("View a list of all commands. Hover over\n" + " a command to view its description. Click\n" + " a command to insert it into your chat bar.")).executor((src, args) -> {
Optional<String> command = args.getOne("command");
if (command.isPresent()) {
Optional<? extends CommandMapping> mapping = Sponge.getCommandManager().get(command.get());
if (mapping.isPresent()) {
CommandCallable callable = mapping.get().getCallable();
Optional<? extends Text> desc;
// command name in the usage message
if (callable instanceof CommandSpec) {
Text.Builder builder = Text.builder();
callable.getShortDescription(src).ifPresent(des -> builder.append(des, Text.NEW_LINE));
builder.append(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
Text extendedDescription;
try {
// TODO: Why is there no method :(
extendedDescription = (Text) extendedDescriptionField.get(callable);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (extendedDescription != null) {
builder.append(Text.NEW_LINE, extendedDescription);
}
src.sendMessage(builder.build());
} else if ((desc = callable.getHelp(src)).isPresent()) {
src.sendMessage(desc.get());
} else {
src.sendMessage(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
}
return CommandResult.success();
}
throw new CommandException(Text.of("No such command: ", command.get()));
}
Lantern.getGame().getScheduler().submitAsyncTask(() -> {
TreeSet<CommandMapping> commands = new TreeSet<>(comparator);
commands.addAll(Collections2.filter(Sponge.getCommandManager().getAll().values(), input -> input.getCallable().testPermission(src)));
final Text title = Text.builder("Available commands:").color(TextColors.DARK_GREEN).build();
final List<Text> lines = commands.stream().map(c -> getDescription(src, c)).collect(Collectors.toList());
// Console sources cannot see/use the pagination
if (!(src instanceof ConsoleSource)) {
Sponge.getGame().getServiceManager().provide(PaginationService.class).get().builder().title(title).padding(Text.of(TextColors.DARK_GREEN, "=")).contents(lines).sendTo(src);
} else {
src.sendMessage(title);
src.sendMessages(lines);
}
return null;
});
return CommandResult.success();
});
}
use of org.spongepowered.api.command.args.ArgumentParseException in project LanternServer by LanternPowered.
the class CommandListBans method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("ips")) {
private final List<String> choices = Arrays.asList("ips", "players");
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
return args.next();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
final String start = args.nextIfPresent().orElse("").toLowerCase();
return this.choices.stream().filter(new StartsWithPredicate(start)).collect(Collectors.toList());
}
})).executor((src, args) -> {
final boolean showIpBans = "ips".equalsIgnoreCase(args.<String>getOne("ips").orElse(null));
final BanService banService = Lantern.getGame().getServiceManager().provideUnchecked(BanService.class);
List<String> entries;
if (showIpBans) {
entries = banService.getIpBans().stream().map(ban -> ban.getAddress().getHostAddress()).collect(Collectors.toList());
src.sendMessage(t("commands.banlist.ips", entries.size()));
} else {
entries = banService.getProfileBans().stream().map(ban -> ban.getProfile().getName().orElse(ban.getProfile().getUniqueId().toString())).collect(Collectors.toList());
src.sendMessage(t("commands.banlist.players", entries.size()));
}
src.sendMessage(Text.of(Joiner.on(", ").join(entries)));
return CommandResult.success();
});
}
use of org.spongepowered.api.command.args.ArgumentParseException in project LanternServer by LanternPowered.
the class CommandParticle method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
specBuilder.arguments(new PatternMatchingCommandElement(Text.of("type")) {
@Override
protected Iterable<String> getChoices(CommandSource source) {
return Sponge.getGame().getRegistry().getAllOf(ParticleType.class).stream().filter(type -> ((LanternParticleType) type).getInternalType().isPresent()).map(CatalogType::getId).collect(Collectors.toList());
}
@Override
protected Object getValue(String choice) throws IllegalArgumentException {
final Optional<ParticleType> ret = Sponge.getGame().getRegistry().getType(ParticleType.class, choice);
if (!ret.isPresent() || !((LanternParticleType) ret.get()).getInternalType().isPresent()) {
throw new IllegalArgumentException("Invalid input " + choice + " was found");
}
return ret.get();
}
}, GenericArguments2.targetedVector3d(Text.of("position")), // The default value should be 0 for x, y and z
GenericArguments2.vector3d(Text.of("offset"), Vector3d.ZERO), GenericArguments2.doubleNum(Text.of("speed"), 1.0), GenericArguments.optional(GenericArguments2.integer(Text.of("count"), 1)), GenericArguments.optional(new CommandElement(Text.of("mode")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
return args.next();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
Optional<String> arg = args.nextIfPresent();
if (arg.isPresent()) {
return Stream.of("normal", "force").filter(new StartsWithPredicate(arg.get())).collect(Collectors.toList());
}
return Collections.emptyList();
}
}), GenericArguments.optional(GenericArguments.player(Text.of("player"))), GenericArguments.optional(new CommandElement(Text.of("params")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
List<Integer> params = new ArrayList<>();
while (args.hasNext()) {
String arg = args.next();
try {
params.add(Integer.parseInt(arg));
} catch (NumberFormatException e) {
throw args.createError(t("Expected an integer, but input '%s' was not", arg));
}
}
return params.stream().mapToInt(i -> i).toArray();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
return Collections.emptyList();
}
})).executor((src, args) -> {
final LanternParticleType particleType = args.<LanternParticleType>getOne("type").get();
final int particleId = particleType.getInternalType().getAsInt();
final Vector3f position = args.<Vector3d>getOne("position").get().toFloat();
final Vector3f offset = args.<Vector3d>getOne("offset").get().toFloat();
final float speed = args.<Double>getOne("speed").get().floatValue();
final int count = args.<Integer>getOne("count").orElse(1);
final boolean longDistance = args.<String>getOne("mode").map(mode -> mode.equalsIgnoreCase("force")).orElse(false);
final int[] params = args.<int[]>getOne("params").orElse(new int[0]);
final LanternWorld world = CommandHelper.getWorld(src, args);
final int dataLength;
if (particleType == ParticleTypes.BLOCK_CRACK || particleType == ParticleTypes.BLOCK_DUST || particleType == ParticleTypes.FALLING_DUST) {
dataLength = 1;
} else if (particleType == ParticleTypes.ITEM_CRACK) {
dataLength = 2;
} else {
dataLength = 0;
}
if (params.length != dataLength) {
throw new CommandException(t("Invalid parameters (%s), length mismatch (got %s, expected %s) for the particle type %s", Arrays.toString(params), params.length, dataLength, particleType.getId()));
}
final MessagePlayOutSpawnParticle message = new MessagePlayOutSpawnParticle(particleId, position, offset, speed, count, params, longDistance);
if (args.hasAny("player")) {
args.<LanternPlayer>getOne("player").get().getConnection().send(message);
} else {
for (LanternPlayer player : world.getRawPlayers()) {
player.getConnection().send(message);
}
}
src.sendMessage(t("commands.particle.success", particleType.getName(), count));
return CommandResult.success();
});
}
Aggregations