use of org.spongepowered.api.command.args.ArgumentParseException in project Nucleus by NucleusPowered.
the class AbstractCommand method process.
private CommandResult process(CommandSource source, String command, String arguments, CommandArgs args) throws CommandException {
// Phase one: child command processing. Keep track of all thrown arguments.
List<Tuple<String, CommandException>> thrown = Lists.newArrayList();
final CommandContext context = new CommandContext();
T castedSource;
try {
// If we have a child command to execute, then we execute it.
if (args.hasNext() && this.dispatcher.containsAlias(args.peek())) {
Object state = args.getState();
String next = args.next();
try {
// If this works, then we're A-OK.
CommandCallable callable = this.dispatcher.get(next.toLowerCase()).get().getCallable();
if (callable instanceof AbstractCommand) {
return ((AbstractCommand) callable).process(source, command + " " + next, arguments, args);
}
return callable.process(source, arguments);
} catch (NucleusCommandException e) {
// Didn't work out. Let's move on.
thrown.addAll(e.getExceptions());
if (!e.isAllowFallback()) {
throw e;
}
} catch (CommandException e) {
// If the Exception is _not_ of right type, wrap it and add it. This shouldn't happen though.
thrown.add(Tuple.of(command + " " + next, e));
} finally {
args.setState(state);
}
}
// Phase one: test for what is required
if (requiresEconomy && !plugin.getEconHelper().economyServiceExists()) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.economyrequired"));
return CommandResult.empty();
}
// Phase two: source type - test to see if the person in question can execute this command.
castedSource = checkSourceType(source);
// Phase three - test the permission.
if (!testPermissionOnSubject(castedSource)) {
throw new CommandPermissionException();
}
if (!this.hasExecutor) {
if (thrown.isEmpty()) {
// OK, we just process the usage command instead.
return this.usageCommand.process(source, "", args.nextIfPresent().map(String::toLowerCase).orElse(null));
} else {
throw new NucleusCommandException(thrown);
}
}
// Phase four - create the context and parse the arguments.
this.argumentParser.parse(source, args, context);
if (args.hasNext()) {
thrown.add(Tuple.of(command, new NucleusArgumentParseException(Text.of(TextColors.RED, "Too many arguments"), args.getRaw(), args.getRawPosition(), Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null), true)));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
} catch (NucleusCommandException nce) {
throw nce;
} catch (ArgumentParseException ape) {
// get the command to get the usage/subs from.
thrown.add(Tuple.of(command, NucleusArgumentParseException.from(ape, Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null))));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (CommandException ex) {
// Errors at this point are expected, so we'll run with it - no need for debug mode checks.
thrown.add(Tuple.of(command, ex));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (Throwable throwable) {
String m;
if (throwable.getMessage() == null) {
m = "null";
} else {
m = throwable.getMessage();
}
thrown.add(Tuple.of(command, new CommandException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.unexpected", m), throwable)));
// this is on demand, so we should throw it.
throwable.printStackTrace();
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
try {
commandTimings.startTimingIfSync();
ContinueMode mode = preProcessChecks(castedSource, context);
if (!mode.cont) {
return mode.returnType;
}
if (castedSource instanceof Player) {
@SuppressWarnings("unchecked") ContinueMode cm = runChecks((Player) castedSource, context);
if (!cm.cont) {
return cm.returnType;
}
}
// If we're running async...
if (isAsync) {
// Create an executor that runs the command async.
plugin.getLogger().debug("Running " + this.getClass().getName() + " in async mode.");
Sponge.getScheduler().createAsyncExecutor(plugin).execute(() -> onExecute(castedSource, context));
// Tell Sponge we're done.
return CommandResult.success();
}
return onExecute(castedSource, context);
} finally {
commandTimings.stopTimingIfSync();
}
}
use of org.spongepowered.api.command.args.ArgumentParseException in project Nucleus by NucleusPowered.
the class MailFilterArgument method parseValue.
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
// Get all the arguments in list.
List<UUID> players = Lists.newArrayList();
boolean console = false;
Instant ea = null;
Instant l = null;
List<String> message = Lists.newArrayList();
while (args.hasNext()) {
String toParse = args.next();
try {
String s = toParse.substring(0, 2);
switch(s) {
case "p:":
player(toParse.split(":", 2)[1]).ifPresent(players::add);
break;
case "m:":
message.add(toParse.split(":", 2)[1]);
break;
case "c:":
console = true;
break;
case "b:":
Matcher b = late.matcher(toParse);
if (b.find()) {
// Days before
l = Instant.now().minus(Integer.parseInt(b.group(1)), ChronoUnit.DAYS);
}
break;
case "a:":
Matcher a = early.matcher(toParse);
if (a.find()) {
ea = Instant.now().minus(Integer.parseInt(a.group(1)), ChronoUnit.DAYS);
}
break;
}
} catch (Exception e) {
// ignored
}
}
List<NucleusMailService.MailFilter> lmf = Lists.newArrayList();
if (console || !players.isEmpty()) {
lmf.add(handler.createSenderFilter(console, players));
}
if (ea != null || l != null) {
lmf.add(handler.createDateFilter(ea, l));
}
if (!message.isEmpty()) {
lmf.add(handler.createMessageFilter(false, message));
}
return lmf.isEmpty() ? null : lmf;
}
use of org.spongepowered.api.command.args.ArgumentParseException in project Nucleus by NucleusPowered.
the class WorldTimeArgument method getValue.
private LongFunction<Long> getValue(String arg, CommandArgs args) throws ArgumentParseException {
if (tickAliases.containsKey(arg)) {
return tickAliases.get(arg);
}
// <number>h
Matcher m1 = tfh.matcher(arg);
if (m1.matches()) {
// Get the number, multiply by 1000, return.
long i = Long.parseLong(m1.group(1));
if (i > 23 || i < 0) {
throw args.createError(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("args.worldtime.24herror"));
}
i -= 6;
if (i < 0) {
i += 24;
}
final long res = i * 1000;
return x -> res;
}
// <number>am,pm
Matcher m2 = ampm.matcher(arg);
if (m2.matches()) {
// Get the number, multiply by 1000, return.
int i = Integer.parseInt(m2.group(1));
if (i > 12 || i < 1) {
throw args.createError(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("args.worldtime.12herror"));
}
// Modify to 24 hour time, based on am/pm
String id = m2.group(2).toLowerCase();
if (id.startsWith("p") && i < 12) {
// 11 pm -> 23, 12 pm -> 12.
i += 12;
} else if (id.startsWith("a") && i == 12) {
// 12 am -> 0
i = 0;
}
// Adjust for Minecraft time.
i -= 6;
if (i < 0) {
i += 24;
}
final long res = i * 1000;
return x -> res;
}
// 0 -> 23999
if (ticks.matcher(arg).matches()) {
final long i = Long.parseLong(arg);
if (i >= 0 && i <= 23999) {
return x -> i;
}
throw args.createError(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("args.worldtime.ticks"));
}
throw args.createError(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("args.worldtime.error", arg));
}
use of org.spongepowered.api.command.args.ArgumentParseException in project SpongeAPI by SpongePowered.
the class ChildCommandsTest method testErrorOnNonExistentChildWithNoExecutor.
@Test
public void testErrorOnNonExistentChildWithNoExecutor() throws CommandException {
final CommandSpec spec = CommandSpec.builder().children(ImmutableMap.of(ImmutableList.of("child"), CommandSpec.builder().executor((src, args) -> CommandResult.builder().successCount(1).build()).build())).childArgumentParseExceptionFallback(false).build();
final SimpleDispatcher execute = new SimpleDispatcher();
execute.register(spec, "parent");
try {
execute.process(mock(CommandSource.class), "parent wrong");
} catch (ArgumentParseException ex) {
assertEquals("Input command wrong was not a valid subcommand!\nwrong\n^", ex.getMessage());
}
}
use of org.spongepowered.api.command.args.ArgumentParseException in project SpongeAPI by SpongePowered.
the class ChildCommandsTest method testErrorOnNonExistentChildWithNoOtherParameters.
@Test
public void testErrorOnNonExistentChildWithNoOtherParameters() throws CommandException {
final CommandSpec spec = CommandSpec.builder().children(ImmutableMap.of(ImmutableList.of("child"), CommandSpec.builder().executor((src, args) -> CommandResult.builder().successCount(1).build()).build())).childArgumentParseExceptionFallback(false).executor((src, args) -> CommandResult.success()).build();
final SimpleDispatcher execute = new SimpleDispatcher();
execute.register(spec, "parent");
try {
execute.process(mock(CommandSource.class), "parent wrong");
} catch (ArgumentParseException ex) {
assertEquals("Input command wrong was not a valid subcommand!\nwrong\n^", ex.getMessage());
}
}
Aggregations