Search in sources :

Example 6 with ArgumentParseException

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();
    }
}
Also used : CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandException(org.spongepowered.api.command.CommandException) CommandCallable(org.spongepowered.api.command.CommandCallable) Tuple(org.spongepowered.api.util.Tuple)

Example 7 with ArgumentParseException

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;
}
Also used : Matcher(java.util.regex.Matcher) Instant(java.time.Instant) UUID(java.util.UUID) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) Nullable(javax.annotation.Nullable)

Example 8 with ArgumentParseException

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));
}
Also used : Nucleus(io.github.nucleuspowered.nucleus.Nucleus) LongFunction(java.util.function.LongFunction) CommandSource(org.spongepowered.api.command.CommandSource) HashMap(java.util.HashMap) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Maps(com.google.common.collect.Maps) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) List(java.util.List) Matcher(java.util.regex.Matcher) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Pattern(java.util.regex.Pattern) Nullable(javax.annotation.Nullable) Matcher(java.util.regex.Matcher)

Example 9 with ArgumentParseException

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());
    }
}
Also used : SimpleDispatcher(org.spongepowered.api.command.dispatcher.SimpleDispatcher) ImmutableMap(com.google.common.collect.ImmutableMap) Game(org.spongepowered.api.Game) Assert.assertTrue(org.junit.Assert.assertTrue) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) List(java.util.List) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Assert.assertFalse(org.junit.Assert.assertFalse) CommandExecutor(org.spongepowered.api.command.spec.CommandExecutor) TestHooks(org.spongepowered.api.util.test.TestHooks) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Before(org.junit.Before) TestPlainTextSerializer(org.spongepowered.api.text.TestPlainTextSerializer) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) SimpleDispatcher(org.spongepowered.api.command.dispatcher.SimpleDispatcher) Test(org.junit.Test)

Example 10 with ArgumentParseException

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());
    }
}
Also used : SimpleDispatcher(org.spongepowered.api.command.dispatcher.SimpleDispatcher) ImmutableMap(com.google.common.collect.ImmutableMap) Game(org.spongepowered.api.Game) Assert.assertTrue(org.junit.Assert.assertTrue) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) List(java.util.List) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Assert.assertFalse(org.junit.Assert.assertFalse) CommandExecutor(org.spongepowered.api.command.spec.CommandExecutor) TestHooks(org.spongepowered.api.util.test.TestHooks) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Before(org.junit.Before) TestPlainTextSerializer(org.spongepowered.api.text.TestPlainTextSerializer) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) SimpleDispatcher(org.spongepowered.api.command.dispatcher.SimpleDispatcher) Test(org.junit.Test)

Aggregations

ArgumentParseException (org.spongepowered.api.command.args.ArgumentParseException)12 CommandContext (org.spongepowered.api.command.args.CommandContext)11 List (java.util.List)9 Text (org.spongepowered.api.text.Text)8 Nullable (javax.annotation.Nullable)7 GenericArguments (org.spongepowered.api.command.args.GenericArguments)7 CommandSpec (org.spongepowered.api.command.spec.CommandSpec)7 CommandSource (org.spongepowered.api.command.CommandSource)6 CommandArgs (org.spongepowered.api.command.args.CommandArgs)6 CommandElement (org.spongepowered.api.command.args.CommandElement)6 ImmutableList (com.google.common.collect.ImmutableList)5 StartsWithPredicate (org.spongepowered.api.util.StartsWithPredicate)5 TranslationHelper.t (org.lanternpowered.server.text.translation.TranslationHelper.t)4 CommandException (org.spongepowered.api.command.CommandException)4 CommandResult (org.spongepowered.api.command.CommandResult)4 PluginContainer (org.spongepowered.api.plugin.PluginContainer)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 Lists (com.google.common.collect.Lists)3 Collectors (java.util.stream.Collectors)3 Test (org.junit.Test)3