Search in sources :

Example 1 with CommandContext

use of org.spongepowered.api.command.parameter.CommandContext in project SpongeCommon by SpongePowered.

the class CommandTest method onRegisterSpongeCommand.

@Listener
public void onRegisterSpongeCommand(final RegisterCommandEvent<Command.Parameterized> event) {
    final Parameter.Value<ServerPlayer> playerKey = Parameter.player().key("player").usage(key -> "[any player]").build();
    event.register(this.plugin, Command.builder().addParameter(playerKey).executor(context -> {
        final ServerPlayer player = context.one(playerKey).orElse(context.cause().root() instanceof ServerPlayer ? ((ServerPlayer) context.cause().root()) : null);
        this.logger.info(player.name());
        return CommandResult.success();
    }).build(), "getplayer");
    final Parameter.Value<String> playerParameterKey = Parameter.string().key("name").optional().build();
    event.register(this.plugin, Command.builder().addParameter(playerParameterKey).executor(context -> {
        final Optional<String> result = context.one(playerParameterKey);
        final Collection<GameProfile> collection;
        if (result.isPresent()) {
            // check to see if the string matches
            collection = Sponge.game().server().userManager().streamOfMatches(result.get().toLowerCase(Locale.ROOT)).collect(Collectors.toList());
        } else {
            collection = Sponge.game().server().userManager().streamAll().collect(Collectors.toList());
        }
        collection.forEach(x -> this.logger.info("GameProfile - UUID: {}, Name - {}", x.uniqueId().toString(), x.name().orElse("---")));
        return CommandResult.success();
    }).build(), "checkuser");
    final Parameter.Value<String> choicesKey = Parameter.choices("bacon", "eggs", "spam", "spam spam spam").key("choices").build();
    event.register(this.plugin, Command.builder().addParameter(choicesKey).executor(context -> {
        context.sendMessage(Identity.nil(), Component.text(context.requireOne(choicesKey)));
        return CommandResult.success();
    }).build(), "testchoices");
    final Parameter.Key<String> testKey = Parameter.key("testKey", String.class);
    final Parameter.Key<Component> requiredKey = Parameter.key("requiredKey", Component.class);
    event.register(this.plugin, Command.builder().addFlag(Flag.builder().alias("f").alias("flag").build()).addFlag(Flag.builder().alias("t").alias("text").setParameter(Parameter.string().key(testKey).build()).build()).addParameter(Parameter.formattingCodeText().key(requiredKey).build()).executor(context -> {
        context.sendMessage(Identity.nil(), Component.text(context.flagInvocationCount("flag")));
        context.sendMessage(Identity.nil(), Component.text(context.flagInvocationCount("t")));
        context.all(testKey).forEach(x -> context.sendMessage(Identity.nil(), Component.text(x)));
        context.sendMessage(Identity.nil(), context.requireOne(requiredKey));
        return CommandResult.success();
    }).build(), "flagtest");
    event.register(this.plugin, Command.builder().addFlag(Flag.builder().alias("t").alias("text").setParameter(Parameter.string().key(testKey).build()).build()).addParameter(Parameter.formattingCodeText().key(requiredKey).build()).executor(context -> {
        context.sendMessage(Identity.nil(), Component.text("optional_test"));
        context.sendMessage(Identity.nil(), Component.text(context.flagInvocationCount("t")));
        context.all(testKey).forEach(x -> context.sendMessage(Identity.nil(), Component.text(x)));
        context.sendMessage(Identity.nil(), context.requireOne(requiredKey));
        return CommandResult.success();
    }).build(), "optionalflagtest");
    event.register(this.plugin, Command.builder().executor(x -> {
        x.sendMessage(Identity.nil(), Component.text().content("Click Me").clickEvent(SpongeComponents.executeCallback(ctx -> ctx.sendMessage(Identity.nil(), Component.text("Hello")))).build());
        return CommandResult.success();
    }).build(), "testCallback");
    event.register(this.plugin, Command.builder().executor(x -> {
        final Collection<Entity> collection = Selector.builder().applySelectorType(SelectorTypes.ALL_ENTITIES.get()).addEntityType(EntityTypes.PLAYER.get(), false).addGameMode(GameModes.CREATIVE.get()).limit(1).includeSelf().build().select(x.cause());
        for (final Entity entity : collection) {
            x.sendMessage(Identity.nil(), Component.text(entity.toString()));
        }
        return CommandResult.success();
    }).build(), "testselector");
    final Parameter.Key<ServerLocation> serverLocationKey = Parameter.key("serverLocation", ServerLocation.class);
    final Parameter.Value<ServerLocation> serverLocationParameter = Parameter.location().key(serverLocationKey).build();
    event.register(this.plugin, Command.builder().addParameter(serverLocationParameter).executor(x -> {
        x.sendMessage(Identity.nil(), Component.text(x.requireOne(serverLocationKey).toString()));
        return CommandResult.success();
    }).build(), "testlocation");
    final Parameter.Key<ValueParameter<?>> commandParameterKey = Parameter.key("valueParameter", new TypeToken<ValueParameter<?>>() {
    });
    final TypeToken<ValueParameter<?>> typeToken = new TypeToken<ValueParameter<?>>() {
    };
    event.register(this.plugin, Command.builder().addParameter(serverLocationParameter).addParameter(Parameter.registryElement(typeToken, commandContext -> Sponge.game(), RegistryTypes.REGISTRY_KEYED_VALUE_PARAMETER, "sponge").key(commandParameterKey).build()).executor(x -> {
        x.sendMessage(Identity.nil(), Component.text(x.requireOne(serverLocationKey).toString()));
        x.sendMessage(Identity.nil(), Component.text(x.requireOne(commandParameterKey).toString()));
        return CommandResult.success();
    }).build(), "testcatalogcompletion");
    final Parameter.Key<TestEnum> enumParameterKey = Parameter.key("enum", TestEnum.class);
    final Parameter.Key<String> stringKey = Parameter.key("stringKey", String.class);
    event.register(this.plugin, Command.builder().addParameter(Parameter.enumValue(TestEnum.class).key(enumParameterKey).build()).addParameter(Parameter.string().key(stringKey).completer((context, currentInput) -> Arrays.asList("bacon", "eggs", "spam").stream().map(CommandCompletion::of).collect(Collectors.toList())).build()).executor(x -> {
        x.sendMessage(Identity.nil(), Component.text(x.one(enumParameterKey).orElse(TestEnum.ONE).name()));
        return CommandResult.success();
    }).build(), "testenum");
    final Parameter.Key<ResourceKey> resourceKeyKey = Parameter.key("rk", ResourceKey.class);
    event.register(this.plugin, Command.builder().addParameter(Parameter.resourceKey().key(resourceKeyKey).build()).executor(x -> {
        x.sendMessage(Identity.nil(), Component.text(x.requireOne(resourceKeyKey).formatted()));
        return CommandResult.success();
    }).build(), "testrk");
    final Parameter.Key<UUID> userKey = Parameter.key("user", UUID.class);
    event.register(this.plugin, Command.builder().addParameter(Parameter.user().key(userKey).build()).executor(context -> {
        Sponge.server().userManager().load(context.requireOne(userKey)).thenAcceptAsync(x -> context.sendMessage(Identity.nil(), Component.text(x.map(User::name).orElse("unknown"))), Sponge.server().scheduler().executor(this.plugin));
        return CommandResult.success();
    }).build(), "getuser");
    final Parameter.Key<String> stringLiteralKey = Parameter.key("literal", String.class);
    event.register(this.plugin, Command.builder().executor(context -> {
        context.sendMessage(Identity.nil(), Component.text("Collected literals: " + String.join(", ", context.all(stringLiteralKey))));
        return CommandResult.success();
    }).terminal(true).addParameter(Parameter.firstOfBuilder(Parameter.literal(String.class, "1", "1").key(stringLiteralKey).build()).or(Parameter.literal(String.class, "2", "2").key(stringLiteralKey).build()).terminal().build()).addParameter(Parameter.seqBuilder(Parameter.literal(String.class, "3", "3").key(stringLiteralKey).build()).then(Parameter.literal(String.class, "4", "4").key(stringLiteralKey).build()).terminal().build()).addParameter(Parameter.literal(String.class, "5", "5").optional().key(stringLiteralKey).build()).addParameter(Parameter.literal(String.class, "6", "6").key(stringLiteralKey).build()).build(), "testnesting");
    final Parameter.Value<SystemSubject> systemSubjectValue = Parameter.builder(SystemSubject.class).key("systemsubject").addParser(VariableValueParameters.literalBuilder(SystemSubject.class).literal(Collections.singleton("-")).returnValue(Sponge::systemSubject).build()).build();
    event.register(this.plugin, Command.builder().addParameter(Parameter.firstOf(systemSubjectValue, CommonParameters.PLAYER)).addParameter(Parameter.remainingJoinedStrings().key(stringKey).build()).executor(context -> {
        final Audience audience;
        final String name;
        if (context.hasAny(systemSubjectValue)) {
            audience = context.requireOne(systemSubjectValue);
            name = "Console";
        } else {
            final ServerPlayer player = context.requireOne(CommonParameters.PLAYER);
            name = player.name();
            audience = player;
        }
        final String message = context.requireOne(stringKey);
        context.sendMessage(Identity.nil(), Component.text("To " + name + "> " + message));
        final Object root = context.cause().root();
        final Identity identity = root instanceof ServerPlayer ? ((ServerPlayer) root).identity() : Identity.nil();
        audience.sendMessage(identity, Component.text("From " + name + "> " + message));
        return CommandResult.success();
    }).build(), "testmessage");
    event.register(this.plugin, Command.builder().addParameter(CommonParameters.BOOLEAN).executor(ctx -> {
        if (ctx.requireOne(CommonParameters.BOOLEAN)) {
            // custom error
            return CommandResult.error(Component.text("custom error"));
        }
        return CommandResult.builder().error(null).build();
    }).build(), "errormessage");
    final Command.Builder builder = Command.builder();
    final ValueCompleter stringValueCompleter = (c, s) -> s.isEmpty() ? Collections.singletonList(CommandCompletion.of("x")) : Arrays.asList(s, s + "bar", "foo_" + s).stream().map(CommandCompletion::of).collect(Collectors.toList());
    // final ValueCompleter stringValueCompleter = null;
    final Parameter.Value<String> r_opt = Parameter.remainingJoinedStrings().key("r_def").optional().build();
    final Parameter.Value<String> r_req = Parameter.remainingJoinedStrings().key("r_req").completer(stringValueCompleter).build();
    final Parameter.Value<String> opt1 = Parameter.string().optional().key("opt1").build();
    final Parameter.Value<String> opt2 = Parameter.string().optional().key("opt2").build();
    final Parameter.Value<String> topt = Parameter.string().optional().key("topt").terminal().build();
    final Parameter.Value<String> req1 = Parameter.string().key("req1").completer(stringValueCompleter).build();
    final Parameter.Value<String> req2 = Parameter.string().key("req2").build();
    final Parameter.Value<Boolean> lit1 = Parameter.literal(Boolean.class, true, "lit1").key("lit1").build();
    final Parameter.Value<Boolean> lit2 = Parameter.literal(Boolean.class, true, "lit2").key("lit2").build();
    final Parameter optSeq_lit_req1 = Parameter.seqBuilder(lit1).then(req1).optional().build();
    final Parameter optSeq_lit_req2 = Parameter.seqBuilder(lit2).then(req2).optional().build();
    final Parameter seq_req_2 = Parameter.seqBuilder(req1).then(req2).build();
    final Parameter seq_opt_2 = Parameter.seqBuilder(opt1).then(opt2).build();
    final Parameter seq_opt_2_req = Parameter.seqBuilder(opt1).then(opt2).then(req1).build();
    // <req1>
    builder.addChild(Command.builder().executor(context -> CommandTest.printParameters(context, req1)).addParameter(req1).build(), "required");
    // subcommand|<r_def>
    builder.addChild(Command.builder().executor(context -> CommandTest.printParameters(context, r_opt)).addParameter(r_opt).addChild(Command.builder().executor(c -> CommandTest.printParameters(c, r_opt)).build(), "subcommand").build(), "optional_or_subcmd");
    // https://bugs.mojang.com/browse/MC-165562 usage does not show up after a space if there are no completions
    // [def1] <r_req>
    // TODO missing executed command when only providing a single value
    builder.addChild(Command.builder().executor(context -> CommandTest.printParameters(context, opt1, r_req)).addParameters(opt1, r_req).build(), "optional_r_required");
    // [opt1] [opt2] <r_req>
    // TODO missing executed command when only providing a single value
    builder.addChild(Command.builder().executor(context -> CommandTest.printParameters(context, opt1, opt2, r_req)).addParameters(opt1, opt2, r_req).build(), "optional_optional_required");
    // [opt1] [opt2]
    // TODO some redundancy in generated nodes because opt1 node can terminate early
    builder.addChild(Command.builder().executor(context -> CommandTest.printParameters(context, opt1, opt2)).addParameters(opt1, opt2).build(), "optional_optional");
    // [opt1] [literal <req1>]
    // TODO completion does not include req1 when opt1/literal is ambigous
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, opt1, lit1, req1)).addParameters(opt1, optSeq_lit_req1).build(), "optional_optsequence_literal_required");
    // [literal <req1>] [literal2 <req2>]
    // TODO sequences are not optional
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, lit1, req1, lit2, req2)).addParameters(optSeq_lit_req1, optSeq_lit_req2).build(), "opt_sequence_2_literal_required");
    // <<req1> <req2>>
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, req1, req2)).addParameters(seq_req_2).build(), "seq_required_required");
    // <[opt1] [opt2]>
    // TODO some redundancy in generated nodes because opt1 node can terminate early
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, opt1, opt2)).addParameters(seq_opt_2).build(), "seq_optional_optional");
    // <[opt1] [opt2] <req>>
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, opt1, opt2, req1)).addParameters(seq_opt_2_req).build(), "seq_optional_optional_required");
    // [opt1] <req> [opt2]
    // TODO some redundancy in generated nodes because req1 node can terminate early
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, opt1, req1, opt2)).addParameters(opt1, req1, opt2).build(), "optional_required_optional");
    // [opt1] [topt] !terminal
    // or
    // [opt1] [topt] <req1>
    builder.addChild(Command.builder().executor(c -> CommandTest.printParameters(c, opt1, topt, req1)).addParameters(opt1, topt, req1).build(), "optional_toptional_optional");
    event.register(this.plugin, builder.build(), "testcommand", "testcmd");
    // Adapted from https://github.com/SpongePowered/Sponge/issues/3238#issuecomment-750456173
    final Command.Parameterized firstSub = Command.builder().addParameter(CommonParameters.BOOLEAN).executor(c -> {
        c.sendMessage(Identity.nil(), Component.text("first"));
        return CommandResult.success();
    }).build();
    final Command.Parameterized secondSub = Command.builder().addParameter(CommonParameters.BOOLEAN).executor(c -> {
        c.sendMessage(Identity.nil(), Component.text("second"));
        return CommandResult.success();
    }).build();
    final Command.Parameterized parent = Command.builder().executor(c -> {
        c.sendMessage(Identity.nil(), Component.text("parent"));
        return CommandResult.success();
    }).addParameters(CommonParameters.WORLD).addParameters(Parameter.firstOf(Parameter.subcommand(firstSub, "first"), Parameter.subcommand(secondSub, "second"))).terminal(true).build();
    event.register(this.plugin, parent, "testterminal");
    // exceptions
    event.register(this.plugin, Command.builder().shortDescription(Component.text("test throwing execptions")).addChild(Command.builder().executor(ctx -> {
        throw new CommandException(Component.text("Exit via exception"));
    }).build(), "exception").addChild(Command.builder().executor(ctx -> {
        return CommandResult.error(Component.text("Exit via failed result"));
    }).build(), "failedresult").build(), "testfailure");
    event.register(this.plugin, Command.builder().addParameter(Parameter.enumValue(TestEnum.class).modifier(new ValueParameterModifier<TestEnum>() {

        @Override
        @NotNull
        public Optional<? extends TestEnum> modifyResult(final Parameter.@NotNull Key<? super TestEnum> parameterKey, final ArgumentReader.@NotNull Immutable reader, final CommandContext.@NotNull Builder context, @Nullable final TestEnum value) throws ArgumentParseException {
            if (value == TestEnum.THREE) {
                throw reader.createException(Component.text("Can't select three!"));
            }
            return Optional.ofNullable(value);
        }

        @Override
        public List<CommandCompletion> modifyCompletion(@NotNull final CommandContext context, @NotNull final String currentInput, final List<CommandCompletion> completions) {
            return completions.stream().filter(x -> !x.completion().equalsIgnoreCase(TestEnum.THREE.name())).collect(Collectors.toList());
        }

        @Override
        @Nullable
        public Component modifyExceptionMessage(@Nullable final Component exceptionMessage) {
            if (exceptionMessage == null) {
                return null;
            }
            return exceptionMessage.replaceText(builder -> {
                builder.match(", three").replacement("").once();
            });
        }
    }).key(enumParameterKey).build()).executor(x -> {
        x.sendMessage(Identity.nil(), Component.text(x.one(enumParameterKey).orElse(TestEnum.ONE).name()));
        return CommandResult.success();
    }).build(), "testenummodified");
    final Parameter.Value<String> testString = Parameter.string().key("string").build();
    final Parameter.Value<Component> jsonTextParameter = Parameter.jsonText().key("text").build();
    event.register(this.plugin, Command.builder().addParameter(jsonTextParameter).addParameter(testString).executor(ctx -> {
        ctx.sendMessage(Identity.nil(), ctx.requireOne(jsonTextParameter));
        ctx.sendMessage(Identity.nil(), Component.text(ctx.requireOne(testString)));
        return CommandResult.success();
    }).build(), "testcomponentjson");
    final Parameter.Value<Integer> firstIntParameter = Parameter.integerNumber().key("int1").build();
    final Parameter.Value<Integer> secondIntParameter = Parameter.integerNumber().key("int2").build();
    final Parameter.Value<Operator> operatorParameter = Parameter.operator().key("operator").build();
    event.register(this.plugin, Command.builder().addParameter(firstIntParameter).addParameter(operatorParameter).addParameter(secondIntParameter).executor(ctx -> {
        final int first = ctx.requireOne(firstIntParameter);
        final int second = ctx.requireOne(secondIntParameter);
        final Operator operator = ctx.requireOne(operatorParameter);
        ctx.sendMessage(Identity.nil(), Component.text(first));
        ctx.sendMessage(Identity.nil(), RegistryTypes.OPERATOR.get().findValueKey(operator).map(key -> Component.text(key.asString())).orElse(Component.text("Not set")));
        ctx.sendMessage(Identity.nil(), Component.text(second));
        if (operator instanceof Operator.Simple) {
            ctx.sendMessage(Identity.nil(), Component.text(((Operator.Simple) operator).apply(first, second)));
        }
        return CommandResult.success();
    }).build(), "testoperator");
    final Parameter.Value<Color> colorParameter = Parameter.color().key("color").build();
    event.register(this.plugin, Command.builder().addParameter(colorParameter).executor(ctx -> {
        final Color color = ctx.requireOne(colorParameter);
        final TextColor textColor = TextColor.color(color);
        final String colorString = color.toString();
        ctx.sendMessage(Identity.nil(), Component.text().color(textColor).content(colorString).build());
        return CommandResult.success();
    }).build(), "textcolor");
    final Parameter.Value<Integer> rangedInt1 = Parameter.rangedInteger(1, Integer.MAX_VALUE).key("quantity").build();
    event.register(this.plugin, Command.builder().addParameter(Parameter.firstOf(playerKey, Parameter.user().key(userKey).build())).addParameter(choicesKey).addParameter(rangedInt1).executor(ctx -> {
        if (ctx.hasAny(playerKey)) {
            ctx.sendMessage(Identity.nil(), Component.text(ctx.requireOne(playerKey).name()));
        } else {
            ctx.sendMessage(Identity.nil(), Component.text(ctx.requireOne(userKey).toString()));
        }
        ctx.sendMessage(Identity.nil(), Component.text(ctx.requireOne(choicesKey)));
        ctx.sendMessage(Identity.nil(), Component.text(ctx.requireOne(rangedInt1)));
        return CommandResult.success();
    }).build(), "firstoftest");
}
Also used : Operator(org.spongepowered.api.command.parameter.managed.operator.Operator) Arrays(java.util.Arrays) Command(org.spongepowered.api.command.Command) Inject(com.google.inject.Inject) ValueCompleter(org.spongepowered.api.command.parameter.managed.ValueCompleter) Locale(java.util.Locale) GameProfile(org.spongepowered.api.profile.GameProfile) Selector(org.spongepowered.api.command.selector.Selector) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) CommandCompletion(org.spongepowered.api.command.CommandCompletion) User(org.spongepowered.api.entity.living.player.User) TextColor(net.kyori.adventure.text.format.TextColor) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) ArgumentReader(org.spongepowered.api.command.parameter.ArgumentReader) UUID(java.util.UUID) TypeToken(io.leangen.geantyref.TypeToken) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ArgumentParseException(org.spongepowered.api.command.exception.ArgumentParseException) Optional(java.util.Optional) NotNull(org.jetbrains.annotations.NotNull) ValueParameter(org.spongepowered.api.command.parameter.managed.ValueParameter) ServerLocation(org.spongepowered.api.world.server.ServerLocation) Flag(org.spongepowered.api.command.parameter.managed.Flag) GameModes(org.spongepowered.api.entity.living.player.gamemode.GameModes) EntityTypes(org.spongepowered.api.entity.EntityTypes) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) ResourceKey(org.spongepowered.api.ResourceKey) Nullable(org.checkerframework.checker.nullness.qual.Nullable) CommonParameters(org.spongepowered.api.command.parameter.CommonParameters) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) Identity(net.kyori.adventure.identity.Identity) Entity(org.spongepowered.api.entity.Entity) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) ValueParameterModifier(org.spongepowered.api.command.parameter.managed.ValueParameterModifier) VariableValueParameters(org.spongepowered.api.command.parameter.managed.standard.VariableValueParameters) SelectorTypes(org.spongepowered.api.command.selector.SelectorTypes) PluginContainer(org.spongepowered.plugin.PluginContainer) Audience(net.kyori.adventure.audience.Audience) CommandContext(org.spongepowered.api.command.parameter.CommandContext) SystemSubject(org.spongepowered.api.SystemSubject) Color(org.spongepowered.api.util.Color) SpongeComponents(org.spongepowered.api.adventure.SpongeComponents) Listener(org.spongepowered.api.event.Listener) Collections(java.util.Collections) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Entity(org.spongepowered.api.entity.Entity) CommandContext(org.spongepowered.api.command.parameter.CommandContext) ServerLocation(org.spongepowered.api.world.server.ServerLocation) CommandCompletion(org.spongepowered.api.command.CommandCompletion) List(java.util.List) TextColor(net.kyori.adventure.text.format.TextColor) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) UUID(java.util.UUID) Identity(net.kyori.adventure.identity.Identity) Optional(java.util.Optional) Audience(net.kyori.adventure.audience.Audience) TextColor(net.kyori.adventure.text.format.TextColor) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Color(org.spongepowered.api.util.Color) ArgumentReader(org.spongepowered.api.command.parameter.ArgumentReader) ResourceKey(org.spongepowered.api.ResourceKey) GameProfile(org.spongepowered.api.profile.GameProfile) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Operator(org.spongepowered.api.command.parameter.managed.operator.Operator) User(org.spongepowered.api.entity.living.player.User) ArgumentParseException(org.spongepowered.api.command.exception.ArgumentParseException) NotNull(org.jetbrains.annotations.NotNull) ValueParameter(org.spongepowered.api.command.parameter.managed.ValueParameter) Component(net.kyori.adventure.text.Component) ValueCompleter(org.spongepowered.api.command.parameter.managed.ValueCompleter) SystemSubject(org.spongepowered.api.SystemSubject) CommandException(org.spongepowered.api.command.exception.CommandException) Command(org.spongepowered.api.command.Command) TypeToken(io.leangen.geantyref.TypeToken) ValueParameter(org.spongepowered.api.command.parameter.managed.ValueParameter) Parameter(org.spongepowered.api.command.parameter.Parameter) Listener(org.spongepowered.api.event.Listener)

Example 2 with CommandContext

use of org.spongepowered.api.command.parameter.CommandContext in project SpongeCommon by SpongePowered.

the class WorldTest method createRandomCheckerboardWorld.

private CommandResult createRandomCheckerboardWorld(final CommandContext context) {
    final WorldManager wm = Sponge.server().worldManager();
    final ServerPlayer player = (ServerPlayer) context.cause().root();
    final String owner = player.name();
    final Random random = player.world().random();
    final List<RegistryReference<Biome>> allBiomes = Sponge.server().registry(RegistryTypes.BIOME).streamEntries().map(RegistryEntry::asReference).collect(Collectors.toList());
    final List<RegistryReference<Biome>> biomes = IntStream.range(0, random.nextInt(allBiomes.size())).mapToObj(i -> allBiomes.get(random.nextInt(allBiomes.size()))).collect(Collectors.toList());
    final List<Structure> allStructures = RegistryTypes.STRUCTURE.get().stream().collect(Collectors.toList());
    final Map<Structure, SeparatedStructureConfig> abundantStructures = IntStream.range(0, random.nextInt(allStructures.size())).mapToObj(i -> allStructures.get(random.nextInt(allStructures.size()))).distinct().collect(Collectors.toMap(s -> s, s -> SeparatedStructureConfig.of(random.nextInt(3) + 2, 1, random.nextInt(10))));
    final Map<Structure, SeparatedStructureConfig> rareStructures = IntStream.range(0, random.nextInt(8) + 2).mapToObj(i -> allStructures.get(random.nextInt(allStructures.size()))).distinct().collect(Collectors.toMap(s -> s, s -> SeparatedStructureConfig.of(random.nextInt(10) + 6, 5, random.nextInt(10))));
    final StructureGenerationConfig structureConfig = StructureGenerationConfig.builder().addStructures(abundantStructures).addStructures(rareStructures).build();
    final NoiseConfig noiseConfig = NoiseConfig.builder().height(256).build();
    final NoiseGeneratorConfig noiseGenConfig = NoiseGeneratorConfig.builder().structureConfig(structureConfig).noiseConfig(noiseConfig).seaLevel(// 2 rolls
    random.nextInt(61 - 1) + 1 + random.nextInt(30)).build();
    final ResourceKey worldKey = ResourceKey.of(this.plugin, owner.toLowerCase());
    final WorldTemplate customTemplate = WorldTemplate.builder().from(WorldTemplate.overworld()).key(worldKey).worldType(WorldTypes.OVERWORLD).serializationBehavior(SerializationBehavior.NONE).loadOnStartup(false).performsSpawnLogic(true).displayName(Component.text("Custom world by " + owner)).generator(ChunkGenerator.noise(BiomeProvider.checkerboard(CheckerboardBiomeConfig.builder().addBiomes(biomes).scale(random.nextInt(16 - 2) + 2).build()), noiseGenConfig)).build();
    if (player.world().key().equals(worldKey)) {
        player.setLocation(ServerLocation.of(wm.defaultWorld(), wm.defaultWorld().properties().spawnPosition()));
    }
    context.sendMessage(Identity.nil(), Component.text("Generating your world..."));
    wm.deleteWorld(worldKey).thenCompose(b -> wm.loadWorld(customTemplate)).thenAccept(w -> this.transportToWorld(player, w)).exceptionally(e -> {
        context.sendMessage(Identity.nil(), Component.text("Failed to teleport!", NamedTextColor.DARK_RED));
        e.printStackTrace();
        return null;
    });
    return CommandResult.success();
}
Also used : IntStream(java.util.stream.IntStream) RegistryEntry(org.spongepowered.api.registry.RegistryEntry) PortalType(org.spongepowered.api.world.portal.PortalType) Command(org.spongepowered.api.command.Command) ServerWorld(org.spongepowered.api.world.server.ServerWorld) Game(org.spongepowered.api.Game) SerializationBehavior(org.spongepowered.api.world.SerializationBehavior) WorldType(org.spongepowered.api.world.WorldType) Inject(com.google.inject.Inject) Random(java.util.Random) Biome(org.spongepowered.api.world.biome.Biome) Title(net.kyori.adventure.title.Title) WorldTemplate(org.spongepowered.api.world.server.WorldTemplate) BiomeProvider(org.spongepowered.api.world.biome.provider.BiomeProvider) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) Map(java.util.Map) NoiseGeneratorConfig(org.spongepowered.api.world.generation.config.NoiseGeneratorConfig) ResourceKey(org.spongepowered.api.ResourceKey) ChunkGenerator(org.spongepowered.api.world.generation.ChunkGenerator) NoSuchElementException(java.util.NoSuchElementException) CommonParameters(org.spongepowered.api.command.parameter.CommonParameters) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) RegistryKey(org.spongepowered.api.registry.RegistryKey) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) WorldTypes(org.spongepowered.api.world.WorldTypes) WorldManager(org.spongepowered.api.world.server.WorldManager) Structure(org.spongepowered.api.world.generation.structure.Structure) Identity(net.kyori.adventure.identity.Identity) CheckerboardBiomeConfig(org.spongepowered.api.world.biome.provider.CheckerboardBiomeConfig) Sponge(org.spongepowered.api.Sponge) Axis(org.spongepowered.api.util.Axis) TypeToken(io.leangen.geantyref.TypeToken) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) SeparatedStructureConfig(org.spongepowered.api.world.generation.config.structure.SeparatedStructureConfig) List(java.util.List) RegistryReference(org.spongepowered.api.registry.RegistryReference) Vector3d(org.spongepowered.math.vector.Vector3d) PluginContainer(org.spongepowered.plugin.PluginContainer) StructureGenerationConfig(org.spongepowered.api.world.generation.config.structure.StructureGenerationConfig) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) NoiseConfig(org.spongepowered.api.world.generation.config.noise.NoiseConfig) ServerLocation(org.spongepowered.api.world.server.ServerLocation) NoiseGeneratorConfig(org.spongepowered.api.world.generation.config.NoiseGeneratorConfig) RegistryReference(org.spongepowered.api.registry.RegistryReference) NoiseConfig(org.spongepowered.api.world.generation.config.noise.NoiseConfig) WorldManager(org.spongepowered.api.world.server.WorldManager) ResourceKey(org.spongepowered.api.ResourceKey) StructureGenerationConfig(org.spongepowered.api.world.generation.config.structure.StructureGenerationConfig) Random(java.util.Random) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) SeparatedStructureConfig(org.spongepowered.api.world.generation.config.structure.SeparatedStructureConfig) Structure(org.spongepowered.api.world.generation.structure.Structure) WorldTemplate(org.spongepowered.api.world.server.WorldTemplate)

Example 3 with CommandContext

use of org.spongepowered.api.command.parameter.CommandContext in project SpongeCommon by SpongePowered.

the class MapTest method listMaps.

private CommandResult listMaps(final CommandContext ctx) {
    final Collection<MapInfo> mapInfos = Sponge.server().mapStorage().allMapInfos();
    ctx.sendMessage(Identity.nil(), Component.text(mapInfos.size()));
    final List<MapInfo> list = new ArrayList<>(mapInfos);
    list.sort(Comparator.comparingInt(info -> info.toContainer().getInt(DataQuery.of("UnsafeMapId")).get()));
    for (final MapInfo mapInfo : list) {
        ctx.sendMessage(Identity.nil(), Component.text("id: " + mapInfo.toContainer().getInt(DataQuery.of("UnsafeMapId")).get() + " loc: " + mapInfo.get(Keys.MAP_LOCATION).get()));
    }
    return CommandResult.success();
}
Also used : Color(java.awt.Color) Command(org.spongepowered.api.command.Command) MapDecoration(org.spongepowered.api.map.decoration.MapDecoration) Inject(com.google.inject.Inject) Banner(org.spongepowered.api.block.entity.Banner) Supports(org.spongepowered.api.event.filter.data.Supports) ItemStack(org.spongepowered.api.item.inventory.ItemStack) DataQuery(org.spongepowered.api.data.persistence.DataQuery) MapDecorationTypes(org.spongepowered.api.map.decoration.MapDecorationTypes) CommandExecutor(org.spongepowered.api.command.CommandExecutor) ImageIO(javax.imageio.ImageIO) Vector2i(org.spongepowered.math.vector.Vector2i) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) LocatableBlock(org.spongepowered.api.world.LocatableBlock) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BlockTypes(org.spongepowered.api.block.BlockTypes) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) UUID(java.util.UUID) MapColor(org.spongepowered.api.map.color.MapColor) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) MapStorage(org.spongepowered.api.map.MapStorage) Keys(org.spongepowered.api.data.Keys) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MapInfo(org.spongepowered.api.map.MapInfo) HandTypes(org.spongepowered.api.data.type.HandTypes) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) RegistryEntry(org.spongepowered.api.registry.RegistryEntry) Getter(org.spongepowered.api.event.filter.Getter) ServerWorld(org.spongepowered.api.world.server.ServerWorld) MapDecorationType(org.spongepowered.api.map.decoration.MapDecorationType) ItemTypes(org.spongepowered.api.item.ItemTypes) CompletableFuture(java.util.concurrent.CompletableFuture) DataView(org.spongepowered.api.data.persistence.DataView) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MapDecorationOrientation(org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) MapShade(org.spongepowered.api.map.color.MapShade) MapDecorationOrientations(org.spongepowered.api.map.decoration.orientation.MapDecorationOrientations) ResourceKey(org.spongepowered.api.ResourceKey) RayTrace(org.spongepowered.api.util.blockray.RayTrace) MapColorTypes(org.spongepowered.api.map.color.MapColorTypes) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) RayTraceResult(org.spongepowered.api.util.blockray.RayTraceResult) CommandResult(org.spongepowered.api.command.CommandResult) MapCanvas(org.spongepowered.api.map.MapCanvas) LoadableModule(org.spongepowered.test.LoadableModule) Identity(net.kyori.adventure.identity.Identity) IOException(java.io.IOException) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) File(java.io.File) PluginContainer(org.spongepowered.plugin.PluginContainer) Audience(net.kyori.adventure.audience.Audience) CreateMapEvent(org.spongepowered.api.event.action.CreateMapEvent) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) Comparator(java.util.Comparator) Collections(java.util.Collections) CommandException(org.spongepowered.api.command.exception.CommandException) MapColorType(org.spongepowered.api.map.color.MapColorType) ArrayList(java.util.ArrayList) MapInfo(org.spongepowered.api.map.MapInfo)

Example 4 with CommandContext

use of org.spongepowered.api.command.parameter.CommandContext in project SpongeCommon by SpongePowered.

the class SpongeCommand method reloadWorldExecutor.

@NonNull
private CommandResult reloadWorldExecutor(final CommandContext context) {
    final ServerWorld target = context.requireOne(this.worldKey);
    final ResourceKey worldId = target.key();
    SpongeGameConfigs.getForWorld(target).reload().whenComplete(($, error) -> {
        if (error != null) {
            context.sendMessage(Identity.nil(), Component.text(b -> b.content("Failed to reload configuration for world ").append(Component.text(worldId.toString(), Style.style(TextDecoration.BOLD))).append(Component.text(". See the console for details.")).color(NamedTextColor.RED)));
            SpongeCommon.logger().error("Failed to reload configuration of world '{}'", worldId, error);
        } else {
            context.sendMessage(Identity.nil(), Component.text("Successfully reloaded configuration for world ", NamedTextColor.GREEN).append(Component.text(worldId.toString(), Style.style(TextDecoration.BOLD))).append(Component.text("!")));
        }
    });
    return CommandResult.success();
}
Also used : ServerWorld(org.spongepowered.api.world.server.ServerWorld) RefreshGameEvent(org.spongepowered.api.event.lifecycle.RefreshGameEvent) ServerLevelBridge(org.spongepowered.common.bridge.server.level.ServerLevelBridge) Command(org.spongepowered.api.command.Command) URL(java.net.URL) SpongeGameConfigs(org.spongepowered.common.config.SpongeGameConfigs) ItemStack(org.spongepowered.api.item.inventory.ItemStack) PluginMetadata(org.spongepowered.plugin.metadata.PluginMetadata) Method(java.lang.reflect.Method) LinearComponents(net.kyori.adventure.text.LinearComponents) TextComponent(net.kyori.adventure.text.TextComponent) TextColor(net.kyori.adventure.text.format.TextColor) LocatableBlock(org.spongepowered.api.world.LocatableBlock) Collection(java.util.Collection) Launch(org.spongepowered.common.launch.Launch) Sponge(org.spongepowered.api.Sponge) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Keys(org.spongepowered.api.data.Keys) List(java.util.List) Optional(java.util.Optional) JoinConfiguration(net.kyori.adventure.text.JoinConfiguration) Player(org.spongepowered.api.entity.living.player.Player) HoverEvent(net.kyori.adventure.text.event.HoverEvent) ServerLocation(org.spongepowered.api.world.server.ServerLocation) PluginContributor(org.spongepowered.plugin.metadata.model.PluginContributor) Timings(co.aikar.timings.Timings) NonNull(org.checkerframework.checker.nullness.qual.NonNull) ServerWorld(org.spongepowered.api.world.server.ServerWorld) LocalDateTime(java.time.LocalDateTime) CompletableFuture(java.util.concurrent.CompletableFuture) ClickEvent(net.kyori.adventure.text.event.ClickEvent) ServerLevel(net.minecraft.server.level.ServerLevel) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) Style(net.kyori.adventure.text.format.Style) SpongeEventManager(org.spongepowered.common.event.manager.SpongeEventManager) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) MBeanServer(javax.management.MBeanServer) ResourceKey(org.spongepowered.api.ResourceKey) RayTrace(org.spongepowered.api.util.blockray.RayTrace) ManagementFactory(java.lang.management.ManagementFactory) Nullable(org.checkerframework.checker.nullness.qual.Nullable) CommonParameters(org.spongepowered.api.command.parameter.CommonParameters) CommandResult(org.spongepowered.api.command.CommandResult) LevelBridge(org.spongepowered.common.bridge.world.level.LevelBridge) Identity(net.kyori.adventure.identity.Identity) TextDecoration(net.kyori.adventure.text.format.TextDecoration) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) DecimalFormat(java.text.DecimalFormat) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) File(java.io.File) SpongeTimingsFactory(co.aikar.timings.sponge.SpongeTimingsFactory) CommandMapping(org.spongepowered.api.command.manager.CommandMapping) Entity(net.minecraft.world.entity.Entity) PluginContainer(org.spongepowered.plugin.PluginContainer) DateTimeFormatter(java.time.format.DateTimeFormatter) SpongeConfigs(org.spongepowered.common.applaunch.config.core.SpongeConfigs) CommandContext(org.spongepowered.api.command.parameter.CommandContext) SpongeComponents(org.spongepowered.api.adventure.SpongeComponents) Mth(net.minecraft.util.Mth) ResourceKey(org.spongepowered.api.ResourceKey) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Example 5 with CommandContext

use of org.spongepowered.api.command.parameter.CommandContext in project SpongeCommon by SpongePowered.

the class SpongeCommand method rootCommand.

@NonNull
private CommandResult rootCommand(final CommandContext context) {
    final PluginContainer platformPlugin = Launch.instance().platformPlugin();
    final PluginContainer apiPlugin = Launch.instance().apiPlugin();
    final PluginContainer minecraftPlugin = Launch.instance().minecraftPlugin();
    context.sendMessage(Identity.nil(), Component.text().append(Component.text("SpongePowered", NamedTextColor.YELLOW, TextDecoration.BOLD).append(Component.space()), Component.text("Plugin Platform (running on Minecraft " + minecraftPlugin.metadata().version() + ")"), Component.newline(), Component.text(apiPlugin.metadata().name().get() + ": " + apiPlugin.metadata().version()), Component.newline(), Component.text(platformPlugin.metadata().name().get() + ": " + platformPlugin.metadata().version())).build());
    final Optional<Command.Parameterized> parameterized = context.executedCommand();
    if (parameterized.isPresent()) {
        final String subcommands = parameterized.get().subcommands().stream().filter(x -> x.command().canExecute(context.cause())).flatMap(x -> x.aliases().stream()).collect(Collectors.joining(", "));
        if (!subcommands.isEmpty()) {
            context.sendMessage(Identity.nil(), Component.text().append(Component.newline(), Component.text("Available subcommands:"), Component.newline(), Component.text(subcommands)).build());
        }
    }
    return CommandResult.success();
}
Also used : RefreshGameEvent(org.spongepowered.api.event.lifecycle.RefreshGameEvent) ServerLevelBridge(org.spongepowered.common.bridge.server.level.ServerLevelBridge) Command(org.spongepowered.api.command.Command) URL(java.net.URL) SpongeGameConfigs(org.spongepowered.common.config.SpongeGameConfigs) ItemStack(org.spongepowered.api.item.inventory.ItemStack) PluginMetadata(org.spongepowered.plugin.metadata.PluginMetadata) Method(java.lang.reflect.Method) LinearComponents(net.kyori.adventure.text.LinearComponents) TextComponent(net.kyori.adventure.text.TextComponent) TextColor(net.kyori.adventure.text.format.TextColor) LocatableBlock(org.spongepowered.api.world.LocatableBlock) Collection(java.util.Collection) Launch(org.spongepowered.common.launch.Launch) Sponge(org.spongepowered.api.Sponge) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Keys(org.spongepowered.api.data.Keys) List(java.util.List) Optional(java.util.Optional) JoinConfiguration(net.kyori.adventure.text.JoinConfiguration) Player(org.spongepowered.api.entity.living.player.Player) HoverEvent(net.kyori.adventure.text.event.HoverEvent) ServerLocation(org.spongepowered.api.world.server.ServerLocation) PluginContributor(org.spongepowered.plugin.metadata.model.PluginContributor) Timings(co.aikar.timings.Timings) NonNull(org.checkerframework.checker.nullness.qual.NonNull) ServerWorld(org.spongepowered.api.world.server.ServerWorld) LocalDateTime(java.time.LocalDateTime) CompletableFuture(java.util.concurrent.CompletableFuture) ClickEvent(net.kyori.adventure.text.event.ClickEvent) ServerLevel(net.minecraft.server.level.ServerLevel) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) Style(net.kyori.adventure.text.format.Style) SpongeEventManager(org.spongepowered.common.event.manager.SpongeEventManager) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) MBeanServer(javax.management.MBeanServer) ResourceKey(org.spongepowered.api.ResourceKey) RayTrace(org.spongepowered.api.util.blockray.RayTrace) ManagementFactory(java.lang.management.ManagementFactory) Nullable(org.checkerframework.checker.nullness.qual.Nullable) CommonParameters(org.spongepowered.api.command.parameter.CommonParameters) CommandResult(org.spongepowered.api.command.CommandResult) LevelBridge(org.spongepowered.common.bridge.world.level.LevelBridge) Identity(net.kyori.adventure.identity.Identity) TextDecoration(net.kyori.adventure.text.format.TextDecoration) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) DecimalFormat(java.text.DecimalFormat) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) File(java.io.File) SpongeTimingsFactory(co.aikar.timings.sponge.SpongeTimingsFactory) CommandMapping(org.spongepowered.api.command.manager.CommandMapping) Entity(net.minecraft.world.entity.Entity) PluginContainer(org.spongepowered.plugin.PluginContainer) DateTimeFormatter(java.time.format.DateTimeFormatter) SpongeConfigs(org.spongepowered.common.applaunch.config.core.SpongeConfigs) CommandContext(org.spongepowered.api.command.parameter.CommandContext) SpongeComponents(org.spongepowered.api.adventure.SpongeComponents) Mth(net.minecraft.util.Mth) PluginContainer(org.spongepowered.plugin.PluginContainer) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Aggregations

List (java.util.List)7 Collectors (java.util.stream.Collectors)7 Identity (net.kyori.adventure.identity.Identity)7 Component (net.kyori.adventure.text.Component)7 NamedTextColor (net.kyori.adventure.text.format.NamedTextColor)7 ResourceKey (org.spongepowered.api.ResourceKey)7 Sponge (org.spongepowered.api.Sponge)7 Command (org.spongepowered.api.command.Command)7 CommandResult (org.spongepowered.api.command.CommandResult)7 CommandContext (org.spongepowered.api.command.parameter.CommandContext)7 Parameter (org.spongepowered.api.command.parameter.Parameter)7 Collection (java.util.Collection)6 Optional (java.util.Optional)6 UUID (java.util.UUID)6 CommonParameters (org.spongepowered.api.command.parameter.CommonParameters)6 ServerWorld (org.spongepowered.api.world.server.ServerWorld)6 PluginContainer (org.spongepowered.plugin.PluginContainer)6 File (java.io.File)5 ArrayList (java.util.ArrayList)5 CompletableFuture (java.util.concurrent.CompletableFuture)5