Search in sources :

Example 6 with Sponge

use of org.spongepowered.api.Sponge in project SpongeCommon by SpongePowered.

the class VolumeStreamTest method onGamePreInitialization.

@Listener
public void onGamePreInitialization(final RegisterCommandEvent<Command.Parameterized> event) throws IOException, CommandException {
    this.schematicsDir = this.config.resolve("schematics");
    Files.createDirectories(this.config);
    final Parameter.Value<Biome> biomeKey = Parameter.registryElement(TypeToken.get(Biome.class), ImmutableList.of(VariableValueParameters.RegistryEntryBuilder.WORLD_FROM_LOCATABLE_HOLDER_PROVIDER, VariableValueParameters.RegistryEntryBuilder.WORLD_FROM_CAUSE_HOLDER_PROVIDER), RegistryTypes.BIOME, "minecraft").key("format").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Sets the biome in a selected region")).permission(this.plugin.metadata().id() + ".command.setbiome").addParameter(biomeKey).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Identity.nil(), Component.text("You must set both positions before copying", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Vector3i min = data.getPos1().min(data.getPos2());
        final Vector3i max = data.getPos1().max(data.getPos2());
        final Biome target = src.requireOne(biomeKey);
        player.world().biomeStream(min, max, StreamOptions.forceLoadedAndCopied()).map((world, biome, x, y, z) -> target).apply(VolumeCollectors.of(player.world(), VolumePositionTranslators.identity(), VolumeApplicators.applyBiomes()));
        return CommandResult.success();
    }).build(), "setBiome");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Copies a region of the world to your clipboard")).permission(this.plugin.metadata().id() + ".command.copy").executor(src -> {
        if (!(src.cause().root() instanceof Player)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Player player = (Player) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Identity.nil(), Component.text("You must set both positions before copying", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Vector3i min = data.getPos1().min(data.getPos2());
        final Vector3i max = data.getPos1().max(data.getPos2());
        data.setOrigin(player.blockPosition());
        final ArchetypeVolume archetypeVolume = player.world().createArchetypeVolume(min, max, player.blockPosition());
        data.setClipboard(archetypeVolume);
        player.sendMessage(Identity.nil(), Component.text("Saved to clipboard.", VolumeStreamTest.GREEN));
        return CommandResult.success();
    }).build(), "copy");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Pastes your clipboard to where you are standing")).permission(this.plugin.metadata().id() + ".command.paste").executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        final ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Identity.nil(), Component.text("You must copy something before pasting", NamedTextColor.RED));
            return CommandResult.success();
        }
        try (final CauseStackManager.StackFrame frame = Sponge.server().causeStackManager().pushCauseFrame()) {
            frame.pushCause(this.plugin);
            volume.applyToWorld(player.world(), player.blockPosition(), SpawnTypes.PLACEMENT::get);
        }
        src.sendMessage(Identity.nil(), Component.text("Pasted clipboard into world.", VolumeStreamTest.GREEN));
        return CommandResult.success();
    }).build(), "paste");
    final Parameter.Value<String> fileName = Parameter.string().key("fileName").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Pastes your clipboard to where you are standing")).permission(this.plugin.metadata().id() + ".command.paste").addParameter(fileName).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final String file = src.requireOne(fileName);
        final Path desiredFilePath = this.schematicsDir.resolve(file + VolumeStreamTest.FILE_ENDING);
        if (Files.exists(desiredFilePath)) {
            throw new CommandException(Component.text(file + " already exists, please delete the file first", NamedTextColor.RED));
        }
        if (Files.isDirectory(desiredFilePath)) {
            throw new CommandException(Component.text(file + "is a directory, please use a file name", NamedTextColor.RED));
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        final ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Identity.nil(), Component.text("You must copy something before pasting", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Schematic schematic = Schematic.builder().volume(data.getClipboard()).metaValue(Schematic.METADATA_AUTHOR, player.name()).metaValue(Schematic.METADATA_NAME, file).build();
        final DataContainer schematicData = Sponge.dataManager().translator(Schematic.class).orElseThrow(() -> new IllegalStateException("Sponge doesn't have a DataTranslator for Schematics!")).translate(schematic);
        try {
            final Path output = Files.createFile(desiredFilePath);
            DataFormats.NBT.get().writeTo(new GZIPOutputStream(Files.newOutputStream(output)), schematicData);
            player.sendMessage(Identity.nil(), Component.text("Saved schematic to " + output.toAbsolutePath(), VolumeStreamTest.SAVE));
        } catch (final Exception e) {
            e.printStackTrace();
            final StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            final Component errorText = Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n"));
            final TextComponent text = Component.text("Error saving schematic: " + e.getMessage(), NamedTextColor.RED).hoverEvent(HoverEvent.showText(errorText));
            return CommandResult.builder().error(text).build();
        }
        return CommandResult.success();
    }).build(), "save");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Load a schematic from file")).permission(this.plugin.metadata().id() + ".command.load").addParameter(fileName).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final String file = src.requireOne(fileName);
        final Path desiredFilePath = this.schematicsDir.resolve(file + VolumeStreamTest.FILE_ENDING);
        if (!Files.isRegularFile(desiredFilePath)) {
            throw new CommandException(Component.text("File " + file + " was not a normal schemaic file"));
        }
        final Schematic schematic;
        final DataContainer schematicContainer;
        try (final GZIPInputStream stream = new GZIPInputStream(Files.newInputStream(desiredFilePath))) {
            schematicContainer = DataFormats.NBT.get().readFrom(stream);
        } catch (IOException e) {
            e.printStackTrace();
            final StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            final Component errorText = Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n"));
            final TextComponent text = Component.text("Error loading schematic: " + e.getMessage(), NamedTextColor.RED).hoverEvent(HoverEvent.showText(errorText));
            return CommandResult.builder().error(text).build();
        }
        schematic = Sponge.dataManager().translator(Schematic.class).orElseThrow(() -> new IllegalStateException("Expected a DataTranslator for a Schematic")).translate(schematicContainer);
        src.sendMessage(Identity.nil(), Component.text("Loaded schematic from " + file, TextColor.color(0x003434)));
        final PlayerData data = VolumeStreamTest.get(player);
        data.setClipboard(schematic);
        data.setOrigin(player.blockPosition());
        return CommandResult.success();
    }).build(), "load");
    final Parameter.Value<Rotation> rotation = Parameter.registryElement(TypeToken.get(Rotation.class), RegistryTypes.ROTATION).key("rotation").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Rotate clipboard")).permission(this.plugin.metadata().id() + ".command.rotate").addParameter(rotation).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final Rotation desiredRotation = src.requireOne(rotation);
        final Schematic schematic;
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.clipboard == null) {
            throw new CommandException(Component.text("Load a clipboard first before trying to rotate it"));
        }
        final ArchetypeVolume newClipboard = data.clipboard.transform(Transformation.builder().origin(data.clipboard.min().toDouble().add(data.clipboard.size().toDouble().div(2))).rotate(desiredRotation).build());
        src.sendMessage(Identity.nil(), Component.text("Rotated clipboard " + desiredRotation.angle().degrees() + " degrees"));
        data.setClipboard(newClipboard);
        return CommandResult.success();
    }).build(), "rotate");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) Command(org.spongepowered.api.command.Command) Inject(com.google.inject.Inject) Level(org.apache.logging.log4j.Level) VolumeApplicators(org.spongepowered.api.world.volume.stream.VolumeApplicators) Biome(org.spongepowered.api.world.biome.Biome) Map(java.util.Map) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) Path(java.nio.file.Path) PrintWriter(java.io.PrintWriter) TextComponent(net.kyori.adventure.text.TextComponent) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) TextColor(net.kyori.adventure.text.format.TextColor) Sponge(org.spongepowered.api.Sponge) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) StoppingEngineEvent(org.spongepowered.api.event.lifecycle.StoppingEngineEvent) UUID(java.util.UUID) TypeToken(io.leangen.geantyref.TypeToken) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Root(org.spongepowered.api.event.filter.cause.Root) Transformation(org.spongepowered.api.util.transformation.Transformation) Logger(org.apache.logging.log4j.Logger) Cancellable(org.spongepowered.api.event.Cancellable) GZIPOutputStream(java.util.zip.GZIPOutputStream) Player(org.spongepowered.api.entity.living.player.Player) VolumeCollectors(org.spongepowered.api.world.volume.stream.VolumeCollectors) HoverEvent(net.kyori.adventure.text.event.HoverEvent) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) NonNull(org.checkerframework.checker.nullness.qual.NonNull) DataContainer(org.spongepowered.api.data.persistence.DataContainer) EventContextKeys(org.spongepowered.api.event.EventContextKeys) Schematic(org.spongepowered.api.world.schematic.Schematic) ItemTypes(org.spongepowered.api.item.ItemTypes) HashMap(java.util.HashMap) Rotation(org.spongepowered.api.util.rotation.Rotation) ImmutableList(com.google.common.collect.ImmutableList) Parameter(org.spongepowered.api.command.parameter.Parameter) DataFormats(org.spongepowered.api.data.persistence.DataFormats) Component(net.kyori.adventure.text.Component) Server(org.spongepowered.api.Server) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) CauseStackManager(org.spongepowered.api.event.CauseStackManager) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) LoadableModule(org.spongepowered.test.LoadableModule) VolumePositionTranslators(org.spongepowered.api.world.volume.stream.VolumePositionTranslators) Files(java.nio.file.Files) Identity(net.kyori.adventure.identity.Identity) StringWriter(java.io.StringWriter) ConfigDir(org.spongepowered.api.config.ConfigDir) IOException(java.io.IOException) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) VariableValueParameters(org.spongepowered.api.command.parameter.managed.standard.VariableValueParameters) PluginContainer(org.spongepowered.plugin.PluginContainer) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) SpawnTypes(org.spongepowered.api.event.cause.entity.SpawnTypes) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Vector3i(org.spongepowered.math.vector.Vector3i) GZIPInputStream(java.util.zip.GZIPInputStream) DataContainer(org.spongepowered.api.data.persistence.DataContainer) Biome(org.spongepowered.api.world.biome.Biome) StringWriter(java.io.StringWriter) GZIPOutputStream(java.util.zip.GZIPOutputStream) CauseStackManager(org.spongepowered.api.event.CauseStackManager) TextComponent(net.kyori.adventure.text.TextComponent) Component(net.kyori.adventure.text.Component) PrintWriter(java.io.PrintWriter) Path(java.nio.file.Path) TextComponent(net.kyori.adventure.text.TextComponent) Player(org.spongepowered.api.entity.living.player.Player) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) CommandException(org.spongepowered.api.command.exception.CommandException) IOException(java.io.IOException) Rotation(org.spongepowered.api.util.rotation.Rotation) IOException(java.io.IOException) CommandException(org.spongepowered.api.command.exception.CommandException) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Vector3i(org.spongepowered.math.vector.Vector3i) Parameter(org.spongepowered.api.command.parameter.Parameter) Schematic(org.spongepowered.api.world.schematic.Schematic) Listener(org.spongepowered.api.event.Listener)

Example 7 with Sponge

use of org.spongepowered.api.Sponge in project SpongeCommon by SpongePowered.

the class SpongePlaceholderContextBuilder method associatedObject.

@Override
@SuppressWarnings("unchecked")
public PlaceholderContext.Builder associatedObject(@Nullable final Object associatedObject) {
    if (associatedObject == null) {
        this.associatedObjectSupplier = null;
    } else if (associatedObject instanceof Supplier) {
        return this.associatedObject((Supplier<Object>) associatedObject);
    } else if (associatedObject instanceof SystemSubject) {
        this.associatedObjectSupplier = Sponge::systemSubject;
    } else if (associatedObject instanceof Server) {
        this.associatedObjectSupplier = Sponge::server;
    } else if (associatedObject instanceof Player) {
        return this.associatedObject((Player) associatedObject);
    } else if (associatedObject instanceof ServerWorld) {
        final ResourceKey key = ((ServerWorld) associatedObject).key();
        this.associatedObjectSupplier = () -> SpongeCommon.game().server().worldManager().world(key).orElse(null);
    } else if (associatedObject instanceof Entity) {
        final Entity entity = ((Entity) associatedObject);
        final ResourceKey key = entity.serverLocation().world().key();
        final UUID entityUuid = ((Entity) associatedObject).uniqueId();
        this.associatedObjectSupplier = () -> SpongeCommon.game().server().worldManager().world(key).flatMap(x -> x.entity(entityUuid)).orElse(null);
    } else {
        // We create a weak reference here so we don't hold on to game objects.
        final WeakReference<Object> objectWeakReference = new WeakReference<>(associatedObject);
        this.associatedObjectSupplier = objectWeakReference::get;
    }
    return this;
}
Also used : Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) Server(org.spongepowered.api.Server) SystemSubject(org.spongepowered.api.SystemSubject) ResourceKey(org.spongepowered.api.ResourceKey) ServerWorld(org.spongepowered.api.world.server.ServerWorld) WeakReference(java.lang.ref.WeakReference) Supplier(java.util.function.Supplier) Sponge(org.spongepowered.api.Sponge) UUID(java.util.UUID)

Example 8 with Sponge

use of org.spongepowered.api.Sponge 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 9 with Sponge

use of org.spongepowered.api.Sponge in project SpongeCommon by SpongePowered.

the class ServerLoginPacketListenerImplMixin method handleAcceptedLogin.

/**
 * @author morph - April 27th, 2021
 * @author dualspiral - July 17th, 2021
 *
 * @reason support async ban/whitelist service and user->player syncing.
 */
@Overwrite
public void handleAcceptedLogin() {
    if (!this.gameProfile.isComplete()) {
        this.gameProfile = this.shadow$createFakeProfile(this.gameProfile);
    }
    // Sponge start - avoid #tick calling handleAcceptedLogin more than once.
    if (this.impl$accepted) {
        return;
    }
    this.impl$accepted = true;
    final PlayerList playerList = this.server.getPlayerList();
    // Sponge end
    // Sponge start - completable future
    ((PlayerListBridge) playerList).bridge$canPlayerLogin(this.connection.getRemoteAddress(), this.gameProfile).handle((componentOpt, throwable) -> {
        if (throwable != null) {
            // An error occurred during login checks so we ask to abort.
            ((ConnectionBridge) this.connection).bridge$setKickReason(new TextComponent("An error occurred checking ban/whitelist status."));
            SpongeCommon.logger().error("An error occurred when checking the ban/whitelist status of {}.", this.gameProfile.getId().toString());
            SpongeCommon.logger().error(throwable);
        } else if (componentOpt != null) {
            // We handle this later
            ((ConnectionBridge) this.connection).bridge$setKickReason(componentOpt);
        }
        try {
            ((SpongeServer) SpongeCommon.server()).userManager().handlePlayerLogin(this.gameProfile);
        } catch (final IOException e) {
            throw new CompletionException(e);
        }
        return null;
    }).handleAsync((ignored, throwable) -> {
        if (throwable != null) {
            // We're just going to disconnect here, because something went horribly wrong.
            if (throwable instanceof CompletionException) {
                throw (CompletionException) throwable;
            } else {
                throw new CompletionException(throwable);
            }
        }
        // Sponge end
        this.state = ServerLoginPacketListenerImpl.State.ACCEPTED;
        if (this.server.getCompressionThreshold() >= 0 && !this.connection.isMemoryConnection()) {
            this.connection.send(new ClientboundLoginCompressionPacket(this.server.getCompressionThreshold()), (param0) -> this.connection.setupCompression(this.server.getCompressionThreshold()));
        }
        this.connection.send(new ClientboundGameProfilePacket(this.gameProfile));
        final ServerPlayer var1 = this.server.getPlayerList().getPlayer(this.gameProfile.getId());
        if (var1 != null) {
            this.state = ServerLoginPacketListenerImpl.State.DELAY_ACCEPT;
            this.delayedAcceptPlayer = this.server.getPlayerList().getPlayerForLogin(this.gameProfile);
        } else {
            // Sponge start - Also send the channel registrations using the minecraft channel, for compatibility
            final ServerSideConnection connection = (ServerSideConnection) this;
            ((SpongeChannelManager) Sponge.channelManager()).sendChannelRegistrations(connection);
            try {
                this.server.getPlayerList().placeNewPlayer(this.connection, this.server.getPlayerList().getPlayerForLogin(this.gameProfile));
                // invalidate just to be sure there is no user cached for the online player anymore
                Sponge.server().userManager().removeFromCache(this.gameProfile.getId());
            } catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }, SpongeCommon.server()).exceptionally(throwable -> {
        // If a throwable exists, we're just going to disconnect the user, better than leaving them in limbo.
        if (throwable != null) {
            this.impl$disconnectError(throwable, this.state == ServerLoginPacketListenerImpl.State.ACCEPTED || this.state == ServerLoginPacketListenerImpl.State.READY_TO_ACCEPT);
        }
        return null;
    // Sponge End
    });
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) ServerSideConnection(org.spongepowered.api.network.ServerSideConnection) ConnectionBridge(org.spongepowered.common.bridge.network.ConnectionBridge) ServerSideConnectionEvent(org.spongepowered.api.event.network.ServerSideConnectionEvent) Inject(org.spongepowered.asm.mixin.injection.Inject) SpongeServer(org.spongepowered.common.SpongeServer) Connection(net.minecraft.network.Connection) Overwrite(org.spongepowered.asm.mixin.Overwrite) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) EventContext(org.spongepowered.api.event.EventContext) PlayerList(net.minecraft.server.players.PlayerList) ClientboundLoginCompressionPacket(net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket) ServerPlayer(net.minecraft.server.level.ServerPlayer) CallbackInfo(org.spongepowered.asm.mixin.injection.callback.CallbackInfo) MinecraftServer(net.minecraft.server.MinecraftServer) Mixin(org.spongepowered.asm.mixin.Mixin) Component(net.kyori.adventure.text.Component) ConnectionHolderBridge(org.spongepowered.common.bridge.network.ConnectionHolderBridge) PlayerListBridge(org.spongepowered.common.bridge.server.players.PlayerListBridge) At(org.spongepowered.asm.mixin.injection.At) Opcodes(org.objectweb.asm.Opcodes) ServerLoginPacketListenerImplBridge(org.spongepowered.common.bridge.server.network.ServerLoginPacketListenerImplBridge) ClientboundGameProfilePacket(net.minecraft.network.protocol.login.ClientboundGameProfilePacket) ServerLoginPacketListenerImpl(net.minecraft.server.network.ServerLoginPacketListenerImpl) Redirect(org.spongepowered.asm.mixin.injection.Redirect) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Sponge(org.spongepowered.api.Sponge) SpongeChannelManager(org.spongepowered.common.network.channel.SpongeChannelManager) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) SpongeCommon(org.spongepowered.common.SpongeCommon) Final(org.spongepowered.asm.mixin.Final) ClientboundDisconnectPacket(net.minecraft.network.protocol.game.ClientboundDisconnectPacket) Cause(org.spongepowered.api.event.Cause) TextComponent(net.minecraft.network.chat.TextComponent) Shadow(org.spongepowered.asm.mixin.Shadow) ClientboundLoginCompressionPacket(net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket) PlayerList(net.minecraft.server.players.PlayerList) ConnectionBridge(org.spongepowered.common.bridge.network.ConnectionBridge) CompletionException(java.util.concurrent.CompletionException) ServerPlayer(net.minecraft.server.level.ServerPlayer) ServerSideConnection(org.spongepowered.api.network.ServerSideConnection) IOException(java.io.IOException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) ClientboundGameProfilePacket(net.minecraft.network.protocol.login.ClientboundGameProfilePacket) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Example 10 with Sponge

use of org.spongepowered.api.Sponge in project SpongeCommon by SpongePowered.

the class TimingsExport method reportTimings.

/**
 * Builds an XML report of the timings to be uploaded for parsing.
 *
 * @param sender Who to report to
 */
static void reportTimings(CommandSource sender) {
    Platform platform = SpongeImpl.getGame().getPlatform();
    JsonObjectBuilder builder = JSONUtil.objectBuilder().add("version", platform.getContainer(IMPLEMENTATION).getVersion().orElse(platform.getMinecraftVersion().getName() + "-DEV")).add("maxplayers", SpongeImpl.getGame().getServer().getMaxPlayers()).add("start", TimingsManager.timingStart / 1000).add("end", System.currentTimeMillis() / 1000).add("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000);
    if (!TimingsManager.privacy) {
        builder.add("server", getServerName()).add("motd", Sponge.getServer().getMotd().toPlain()).add("online-mode", Sponge.getServer().getOnlineMode()).add("icon", SpongeImpl.getServer().getServerStatusResponse().getFavicon());
    }
    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    builder.add("system", JSONUtil.objectBuilder().add("timingcost", getCost()).add("name", System.getProperty("os.name")).add("version", System.getProperty("os.version")).add("jvmversion", System.getProperty("java.version")).add("arch", System.getProperty("os.arch")).add("maxmem", runtime.maxMemory()).add("cpu", runtime.availableProcessors()).add("runtime", ManagementFactory.getRuntimeMXBean().getUptime()).add("flags", RUNTIME_FLAG_JOINER.join(runtimeBean.getInputArguments())).add("gc", JSONUtil.mapArrayToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> {
        return JSONUtil.singleObjectPair(input.getName(), JSONUtil.arrayOf(input.getCollectionCount(), input.getCollectionTime()));
    })));
    Set<BlockType> blockTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();
    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        blockTypeSet.addAll(timingHistory.blockTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }
    // Current snapshot
    history[i] = new TimingHistory();
    blockTypeSet.addAll(history[i].blockTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);
    JsonObjectBuilder handlersBuilder = JSONUtil.objectBuilder();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.timed && !id.isSpecial()) {
                continue;
            }
            handlersBuilder.add(id.id, JSONUtil.arrayOf(group.id, id.name));
        }
    }
    builder.add("idmap", JSONUtil.objectBuilder().add("groups", JSONUtil.mapArrayToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> {
        return JSONUtil.singleObjectPair(group.id, group.name);
    })).add("handlers", handlersBuilder).add("worlds", JSONUtil.mapArrayToObject(TimingHistory.worldMap.entrySet(), (entry) -> {
        return JSONUtil.singleObjectPair(entry.getValue(), entry.getKey());
    })).add("tileentity", JSONUtil.mapArrayToObject(blockTypeSet, (blockType) -> {
        return JSONUtil.singleObjectPair(Block.getIdFromBlock((Block) blockType), blockType.getId());
    })).add("entity", JSONUtil.mapArrayToObject(entityTypeSet, (entityType) -> {
        if (entityType == EntityTypes.UNKNOWN) {
            return null;
        }
        return JSONUtil.singleObjectPair(TimingsPls.getEntityId(entityType), entityType.getId());
    })));
    // Information about loaded plugins
    builder.add("plugins", JSONUtil.mapArrayToObject(SpongeImpl.getGame().getPluginManager().getPlugins(), (plugin) -> {
        return JSONUtil.objectBuilder().add(plugin.getId(), JSONUtil.objectBuilder().add("version", plugin.getVersion().orElse("")).add("description", plugin.getDescription().orElse("")).add("website", plugin.getUrl().orElse("")).add("authors", AUTHOR_LIST_JOINER.join(plugin.getAuthors()))).build();
    }));
    // Information on the users Config
    builder.add("config", JSONUtil.objectBuilder().add("sponge", serializeConfigNode(SpongeImpl.getGlobalConfig().getRootNode())));
    new TimingsExport(sender, builder.build(), history).start();
}
Also used : SpongeImpl(org.spongepowered.common.SpongeImpl) HttpURLConnection(java.net.HttpURLConnection) JsonObject(com.google.gson.JsonObject) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HISTORY(co.aikar.timings.TimingsManager.HISTORY) URL(java.net.URL) JsonObjectBuilder(co.aikar.util.JSONUtil.JsonObjectBuilder) IMPLEMENTATION(org.spongepowered.api.Platform.Component.IMPLEMENTATION) Platform(org.spongepowered.api.Platform) JsonElement(com.google.gson.JsonElement) InetAddress(java.net.InetAddress) Block(net.minecraft.block.Block) EntityTypes(org.spongepowered.api.entity.EntityTypes) Text(org.spongepowered.api.text.Text) RconSource(org.spongepowered.api.command.source.RconSource) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) ManagementFactory(java.lang.management.ManagementFactory) TextColors(org.spongepowered.api.text.format.TextColors) OutputStream(java.io.OutputStream) RuntimeMXBean(java.lang.management.RuntimeMXBean) TextActions(org.spongepowered.api.text.action.TextActions) CommandSource(org.spongepowered.api.command.CommandSource) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) JSONUtil(co.aikar.util.JSONUtil) JsonArray(com.google.gson.JsonArray) BlockType(org.spongepowered.api.block.BlockType) Entry(java.util.Map.Entry) EntityType(org.spongepowered.api.entity.EntityType) GZIPOutputStream(java.util.zip.GZIPOutputStream) Joiner(com.google.common.base.Joiner) InputStream(java.io.InputStream) Platform(org.spongepowered.api.Platform) RuntimeMXBean(java.lang.management.RuntimeMXBean) EntityType(org.spongepowered.api.entity.EntityType) BlockType(org.spongepowered.api.block.BlockType) JsonObjectBuilder(co.aikar.util.JSONUtil.JsonObjectBuilder)

Aggregations

Sponge (org.spongepowered.api.Sponge)17 List (java.util.List)11 Optional (java.util.Optional)9 CommandResult (org.spongepowered.api.command.CommandResult)8 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 Collectors (java.util.stream.Collectors)7 Component (net.kyori.adventure.text.Component)7 IOException (java.io.IOException)6 Collection (java.util.Collection)6 UUID (java.util.UUID)6 ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)6 Inject (com.google.inject.Inject)5 TypeToken (io.leangen.geantyref.TypeToken)5 Identity (net.kyori.adventure.identity.Identity)5 NamedTextColor (net.kyori.adventure.text.format.NamedTextColor)5 ResourceKey (org.spongepowered.api.ResourceKey)5 RegistryTypes (org.spongepowered.api.registry.RegistryTypes)5 Nullable (javax.annotation.Nullable)4 EntityType (org.spongepowered.api.entity.EntityType)4