Search in sources :

Example 51 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Nucleus by NucleusPowered.

the class CommandBaseTests method testThatCommandSourcesCanExecuteStandardCommand.

/**
 * Tests that if a {@link CommandSource} that is not a player is provided, they can execute a standard command.
 *
 * @throws CommandException
 */
@Test
public void testThatCommandSourcesCanExecuteStandardCommand() throws CommandException {
    BasicCommand cmd = new BasicCommand();
    getInjector().injectMembers(cmd);
    cmd.postInit();
    CommandSource mock = getMockCommandSource();
    CommandResult result = cmd.process(mock, "");
    Assert.assertTrue("There should have been one success!", result.getSuccessCount().orElse(0) == 1);
}
Also used : CommandSource(org.spongepowered.api.command.CommandSource) CommandResult(org.spongepowered.api.command.CommandResult) Test(org.junit.Test)

Example 52 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Nucleus by NucleusPowered.

the class ListHomeCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    // args.getOne(subject);
    User user = this.getUserFromArgs(User.class, src, player, args);
    Text header;
    boolean other = src instanceof User && !((User) src).getUniqueId().equals(user.getUniqueId());
    if (other && user.hasPermission(this.exempt)) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.listhome.exempt"));
    }
    List<Home> msw = homeHandler.getHomes(user);
    if (msw.isEmpty()) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.home.nohomes"));
        return CommandResult.empty();
    }
    if (other) {
        header = plugin.getMessageProvider().getTextMessageWithFormat("home.title.name", user.getName());
    } else {
        header = plugin.getMessageProvider().getTextMessageWithFormat("home.title.normal");
    }
    List<Text> lt = msw.stream().sorted(Comparator.comparing(NamedLocation::getName)).map(x -> {
        Optional<Location<World>> olw = x.getLocation();
        if (!olw.isPresent()) {
            return Text.builder().append(Text.builder(x.getName()).color(TextColors.RED).onHover(TextActions.showText(plugin.getMessageProvider().getTextMessageWithFormat("home.warphoverinvalid", x.getName()))).build()).build();
        } else {
            final Location<World> lw = olw.get();
            return Text.builder().append(Text.builder(x.getName()).color(TextColors.GREEN).style(TextStyles.UNDERLINE).onHover(TextActions.showText(plugin.getMessageProvider().getTextMessageWithFormat("home.warphover", x.getName()))).onClick(TextActions.runCommand(other ? "/homeother " + user.getName() + " " + x.getName() : "/home " + x.getName())).build()).append(plugin.getMessageProvider().getTextMessageWithFormat("home.location", lw.getExtent().getName(), String.valueOf(lw.getBlockX()), String.valueOf(lw.getBlockY()), String.valueOf(lw.getBlockZ()))).build();
        }
    }).collect(Collectors.toList());
    PaginationList.Builder pb = Util.getPaginationBuilder(src).title(Text.of(TextColors.YELLOW, header)).padding(Text.of(TextColors.GREEN, "-")).contents(lt);
    pb.sendTo(src);
    return CommandResult.success();
}
Also used : RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) PermissionInformation(io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) HashMap(java.util.HashMap) GenericArguments(org.spongepowered.api.command.args.GenericArguments) RunAsync(io.github.nucleuspowered.nucleus.internal.annotations.RunAsync) PaginationList(org.spongepowered.api.service.pagination.PaginationList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Home(io.github.nucleuspowered.nucleus.api.nucleusdata.Home) SelectorWrapperArgument(io.github.nucleuspowered.nucleus.argumentparsers.SelectorWrapperArgument) Map(java.util.Map) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Util(io.github.nucleuspowered.nucleus.Util) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) TextColors(org.spongepowered.api.text.format.TextColors) NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) Location(org.spongepowered.api.world.Location) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) User(org.spongepowered.api.entity.living.player.User) CommandSource(org.spongepowered.api.command.CommandSource) TextStyles(org.spongepowered.api.text.format.TextStyles) NicknameArgument(io.github.nucleuspowered.nucleus.argumentparsers.NicknameArgument) NamedLocation(io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) HomeHandler(io.github.nucleuspowered.nucleus.modules.home.handlers.HomeHandler) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) World(org.spongepowered.api.world.World) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Comparator(java.util.Comparator) User(org.spongepowered.api.entity.living.player.User) Optional(java.util.Optional) Text(org.spongepowered.api.text.Text) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) World(org.spongepowered.api.world.World) PaginationList(org.spongepowered.api.service.pagination.PaginationList) Home(io.github.nucleuspowered.nucleus.api.nucleusdata.Home) Location(org.spongepowered.api.world.Location) NamedLocation(io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation)

Example 53 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Nucleus by NucleusPowered.

the class HatCommand method executeWithPlayer.

@Override
protected CommandResult executeWithPlayer(CommandSource player, Player pl, CommandContext args, boolean isSelf) throws Exception {
    Optional<ItemStack> helmetOptional = pl.getHelmet();
    ItemStack stack = pl.getItemInHand(HandTypes.MAIN_HAND).orElseThrow(() -> ReturnMessageException.fromKey("command.generalerror.handempty"));
    ItemStack hand = stack.copy();
    hand.setQuantity(1);
    pl.setHelmet(hand);
    Text itemName = hand.get(Keys.DISPLAY_NAME).orElseGet(() -> Text.of(stack));
    GameMode gameMode = pl.get(Keys.GAME_MODE).orElse(GameModes.NOT_SET);
    if (gameMode != GameModes.CREATIVE) {
        if (stack.getQuantity() > 1) {
            stack.setQuantity(stack.getQuantity() - 1);
            pl.setItemInHand(HandTypes.MAIN_HAND, stack);
        } else {
            pl.setItemInHand(HandTypes.MAIN_HAND, null);
        }
    }
    // If the old item can't be placed back in the subject inventory, drop the item.
    helmetOptional.ifPresent(itemStack -> Util.getStandardInventory(pl).offer(itemStack.copy()).getRejectedItems().forEach(x -> Util.dropItemOnFloorAtLocation(x, pl.getWorld(), pl.getLocation().getPosition())));
    if (!isSelf) {
        player.sendMessage(plugin.getMessageProvider().getTextMessageWithTextFormat("command.hat.success", plugin.getNameUtil().getName(pl), itemName));
    }
    pl.sendMessage(plugin.getMessageProvider().getTextMessageWithTextFormat("command.hat.successself", itemName));
    return CommandResult.success();
}
Also used : NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) CommandResult(org.spongepowered.api.command.CommandResult) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) Keys(org.spongepowered.api.data.key.Keys) CommandSource(org.spongepowered.api.command.CommandSource) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) GameModes(org.spongepowered.api.entity.living.player.gamemode.GameModes) ItemStack(org.spongepowered.api.item.inventory.ItemStack) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) HandTypes(org.spongepowered.api.data.type.HandTypes) Optional(java.util.Optional) EssentialsEquivalent(io.github.nucleuspowered.nucleus.internal.docgen.annotations.EssentialsEquivalent) Util(io.github.nucleuspowered.nucleus.Util) Player(org.spongepowered.api.entity.living.player.Player) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) Text(org.spongepowered.api.text.Text) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 54 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Nucleus by NucleusPowered.

the class InfoCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Optional<InfoArgument.Result> oir = args.getOne(key);
    if (infoConfig.isUseDefaultFile() && !oir.isPresent() && !args.hasAny("l")) {
        // Do we have a default?
        String def = infoConfig.getDefaultInfoSection();
        Optional<TextFileController> list = infoHandler.getSection(def);
        if (list.isPresent()) {
            oir = Optional.of(new InfoArgument.Result(infoHandler.getInfoSections().stream().filter(def::equalsIgnoreCase).findFirst().get(), list.get()));
        }
    }
    if (oir.isPresent()) {
        TextFileController controller = oir.get().text;
        Text def = TextSerializers.FORMATTING_CODE.deserialize(oir.get().name);
        Text title = plugin.getMessageProvider().getTextMessageWithTextFormat("command.info.title.section", controller.getTitle(src).orElseGet(() -> Text.of(def)));
        controller.sendToPlayer(src, title);
        return CommandResult.success();
    }
    // Create a list of pages to load.
    Set<String> sections = infoHandler.getInfoSections();
    if (sections.isEmpty()) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.info.none"));
    }
    // Create the text.
    List<Text> s = Lists.newArrayList();
    sections.forEach(x -> {
        Text.Builder tb = Text.builder().append(Text.builder(x).color(TextColors.GREEN).style(TextStyles.ITALIC).onHover(TextActions.showText(plugin.getMessageProvider().getTextMessageWithFormat("command.info.hover", x))).onClick(TextActions.runCommand("/info " + x)).build());
        // If there is a title, then add it.
        infoHandler.getSection(x).get().getTitle(src).ifPresent(sub -> tb.append(Text.of(TextColors.GOLD, " - ")).append(sub));
        s.add(tb.build());
    });
    Util.getPaginationBuilder(src).contents().header(plugin.getMessageProvider().getTextMessageWithFormat("command.info.header.default")).title(plugin.getMessageProvider().getTextMessageWithFormat("command.info.title.default")).contents(s.stream().sorted(Comparator.comparing(Text::toPlain)).collect(Collectors.toList())).padding(Text.of(TextColors.GOLD, "-")).sendTo(src);
    return CommandResult.success();
}
Also used : Text(org.spongepowered.api.text.Text) TextFileController(io.github.nucleuspowered.nucleus.internal.TextFileController) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) CommandResult(org.spongepowered.api.command.CommandResult)

Example 55 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Nucleus by NucleusPowered.

the class EntityInfoCommand method executeCommand.

@Override
public CommandResult executeCommand(Player player, CommandContext args) throws Exception {
    // Get all the entities in the world.
    Vector3i playerPos = player.getLocation().getBlockPosition();
    Collection<Entity> entities = player.getWorld().getEntities().stream().filter(// 11 blocks.
    x -> x.getLocation().getBlockPosition().distanceSquared(playerPos) < 121).collect(Collectors.toList());
    BlockRay<World> bl = BlockRay.from(player).distanceLimit(10).stopFilter(BlockRay.continueAfterFilter(x -> {
        Vector3i pt1 = x.getLocation().getBlockPosition();
        Vector3i pt2 = pt1.add(0, 1, 0);
        return entities.stream().allMatch(e -> {
            Vector3i current = e.getLocation().getBlockPosition();
            // We don't want it to stop until one of these are hit.
            return !(current.equals(pt1) || current.equals(pt2));
        });
    }, 1)).build();
    Optional<BlockRayHit<World>> ob = bl.end();
    if (ob.isPresent()) {
        BlockRayHit<World> brh = ob.get();
        Vector3d location = brh.getLocation().getPosition();
        Vector3d locationOneUp = location.add(0, 1, 0);
        Optional<Entity> entityOptional = entities.stream().filter(e -> {
            Vector3i current = e.getLocation().getBlockPosition();
            return current.equals(location.toInt()) || current.equals(locationOneUp.toInt());
        }).sorted(Comparator.comparingDouble(x -> x.getLocation().getPosition().distanceSquared(location))).findFirst();
        if (entityOptional.isPresent()) {
            // Display info about the entity
            Entity entity = entityOptional.get();
            EntityType type = entity.getType();
            List<Text> lt = new ArrayList<>();
            lt.add(plugin.getMessageProvider().getTextMessageWithFormat("command.entityinfo.id", type.getId(), Util.getTranslatableIfPresent(type)));
            lt.add(plugin.getMessageProvider().getTextMessageWithFormat("command.entityinfo.uuid", entity.getUniqueId().toString()));
            if (args.hasAny("e") || args.hasAny("extended")) {
                // For each key, see if the entity supports it. If so, get and print the value.
                DataScanner.getInstance().getKeysForHolder(entity).entrySet().stream().filter(x -> x.getValue() != null).filter(x -> {
                    // Work around a Sponge bug.
                    try {
                        return entity.supports(x.getValue());
                    } catch (Exception e) {
                        return false;
                    }
                }).forEach(x -> {
                    Key<? extends BaseValue<Object>> k = (Key<? extends BaseValue<Object>>) x.getValue();
                    if (entity.get(k).isPresent()) {
                        DataScanner.getText(player, "command.entityinfo.key", x.getKey(), entity.get(k).get()).ifPresent(lt::add);
                    }
                });
            }
            Sponge.getServiceManager().provideUnchecked(PaginationService.class).builder().contents(lt).padding(Text.of(TextColors.GREEN, "-")).title(plugin.getMessageProvider().getTextMessageWithFormat("command.entityinfo.list.header", String.valueOf(brh.getBlockX()), String.valueOf(brh.getBlockY()), String.valueOf(brh.getBlockZ()))).sendTo(player);
            return CommandResult.success();
        }
    }
    player.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.entityinfo.none"));
    return CommandResult.empty();
}
Also used : RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) DataScanner(io.github.nucleuspowered.nucleus.internal.DataScanner) PermissionInformation(io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) Vector3d(com.flowpowered.math.vector.Vector3d) HashMap(java.util.HashMap) GenericArguments(org.spongepowered.api.command.args.GenericArguments) BlockRay(org.spongepowered.api.util.blockray.BlockRay) Key(org.spongepowered.api.data.key.Key) ArrayList(java.util.ArrayList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Map(java.util.Map) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Util(io.github.nucleuspowered.nucleus.Util) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) TextColors(org.spongepowered.api.text.format.TextColors) BlockRayHit(org.spongepowered.api.util.blockray.BlockRayHit) CommandResult(org.spongepowered.api.command.CommandResult) Collection(java.util.Collection) BaseValue(org.spongepowered.api.data.value.BaseValue) Sponge(org.spongepowered.api.Sponge) PaginationService(org.spongepowered.api.service.pagination.PaginationService) CommandElement(org.spongepowered.api.command.args.CommandElement) Entity(org.spongepowered.api.entity.Entity) Collectors(java.util.stream.Collectors) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) Vector3i(com.flowpowered.math.vector.Vector3i) World(org.spongepowered.api.world.World) EntityType(org.spongepowered.api.entity.EntityType) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Comparator(java.util.Comparator) Entity(org.spongepowered.api.entity.Entity) BaseValue(org.spongepowered.api.data.value.BaseValue) ArrayList(java.util.ArrayList) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) CommandResult(org.spongepowered.api.command.CommandResult) Text(org.spongepowered.api.text.Text) World(org.spongepowered.api.world.World) EntityType(org.spongepowered.api.entity.EntityType) Vector3d(com.flowpowered.math.vector.Vector3d) Vector3i(com.flowpowered.math.vector.Vector3i) PaginationService(org.spongepowered.api.service.pagination.PaginationService) Key(org.spongepowered.api.data.key.Key) BlockRayHit(org.spongepowered.api.util.blockray.BlockRayHit)

Aggregations

CommandResult (org.spongepowered.api.command.CommandResult)62 Text (org.spongepowered.api.text.Text)46 CommandContext (org.spongepowered.api.command.args.CommandContext)40 List (java.util.List)39 CommandSource (org.spongepowered.api.command.CommandSource)37 Player (org.spongepowered.api.entity.living.player.Player)36 Sponge (org.spongepowered.api.Sponge)34 Optional (java.util.Optional)33 Collectors (java.util.stream.Collectors)33 Permissions (io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions)26 RegisterCommand (io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand)26 AbstractCommand (io.github.nucleuspowered.nucleus.internal.command.AbstractCommand)26 NonnullByDefault (org.spongepowered.api.util.annotation.NonnullByDefault)26 TextColors (org.spongepowered.api.text.format.TextColors)25 CommandElement (org.spongepowered.api.command.args.CommandElement)21 Util (io.github.nucleuspowered.nucleus.Util)20 GenericArguments (org.spongepowered.api.command.args.GenericArguments)20 NoModifiers (io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers)18 SuggestedLevel (io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel)18 CommandException (org.spongepowered.api.command.CommandException)18