Search in sources :

Example 6 with CauseStackManager

use of org.spongepowered.api.event.CauseStackManager 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 CauseStackManager

use of org.spongepowered.api.event.CauseStackManager in project SpongeCommon by SpongePowered.

the class DamageEventUtil method createArmorModifiers.

public static Optional<DamageFunction> createArmorModifiers(final LivingEntity living, final DamageSource damageSource) {
    if (damageSource.isBypassArmor()) {
        return Optional.empty();
    }
    final DoubleUnaryOperator function = incomingDamage -> -(incomingDamage - CombatRules.getDamageAfterAbsorb((float) incomingDamage, living.getArmorValue(), (float) living.getAttributeValue(Attributes.ARMOR_TOUGHNESS)));
    final DamageFunction armorModifier;
    try (final CauseStackManager.StackFrame frame = ((Server) living.getServer()).causeStackManager().pushCauseFrame()) {
        frame.pushCause(living);
        frame.pushCause(Attributes.ARMOR_TOUGHNESS);
        armorModifier = DamageFunction.of(DamageModifier.builder().cause(frame.currentCause()).type(DamageModifierTypes.ARMOR).build(), function);
    }
    return Optional.of(armorModifier);
}
Also used : ResourceLocation(net.minecraft.resources.ResourceLocation) LivingEntity(net.minecraft.world.entity.LivingEntity) AABB(net.minecraft.world.phys.AABB) LivingEntityAccessor(org.spongepowered.common.accessor.world.entity.LivingEntityAccessor) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) MobType(net.minecraft.world.entity.MobType) EventContext(org.spongepowered.api.event.EventContext) Registry(net.minecraft.core.Registry) ChunkSource(net.minecraft.world.level.chunk.ChunkSource) CreatorTrackedBridge(org.spongepowered.common.bridge.CreatorTrackedBridge) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Map(java.util.Map) PotionEffect(org.spongepowered.api.effect.potion.PotionEffect) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Player(net.minecraft.world.entity.player.Player) List(java.util.List) BlockPos(net.minecraft.core.BlockPos) BlockDamageSource(org.spongepowered.api.event.cause.entity.damage.source.BlockDamageSource) Optional(java.util.Optional) ServerLocation(org.spongepowered.api.world.server.ServerLocation) Enchantment(net.minecraft.world.item.enchantment.Enchantment) LevelChunk(net.minecraft.world.level.chunk.LevelChunk) LevelChunkBridge(org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge) EventContextKeys(org.spongepowered.api.event.EventContextKeys) ServerWorld(org.spongepowered.api.world.server.ServerWorld) BlockState(net.minecraft.world.level.block.state.BlockState) HashMap(java.util.HashMap) DamageModifierTypes(org.spongepowered.api.event.cause.entity.damage.DamageModifierTypes) MobEffects(net.minecraft.world.effect.MobEffects) DoubleUnaryOperator(java.util.function.DoubleUnaryOperator) ArrayList(java.util.ArrayList) EntityDamageSource(net.minecraft.world.damagesource.EntityDamageSource) ItemStackUtil(org.spongepowered.common.item.util.ItemStackUtil) DamageSource(net.minecraft.world.damagesource.DamageSource) EnchantmentHelper(net.minecraft.world.item.enchantment.EnchantmentHelper) CombatRules(net.minecraft.world.damagesource.CombatRules) Server(org.spongepowered.api.Server) CauseStackManager(org.spongepowered.api.event.CauseStackManager) FallingBlockDamageSource(org.spongepowered.api.event.cause.entity.damage.source.FallingBlockDamageSource) Cause(org.spongepowered.api.event.Cause) Entity(net.minecraft.world.entity.Entity) DamageFunction(org.spongepowered.api.event.cause.entity.damage.DamageFunction) DamageModifier(org.spongepowered.api.event.cause.entity.damage.DamageModifier) EquipmentSlot(net.minecraft.world.entity.EquipmentSlot) Attributes(net.minecraft.world.entity.ai.attributes.Attributes) Mth(net.minecraft.util.Mth) Collections(java.util.Collections) ListTag(net.minecraft.nbt.ListTag) CauseStackManager(org.spongepowered.api.event.CauseStackManager) DamageFunction(org.spongepowered.api.event.cause.entity.damage.DamageFunction) DoubleUnaryOperator(java.util.function.DoubleUnaryOperator)

Example 8 with CauseStackManager

use of org.spongepowered.api.event.CauseStackManager in project SpongeCommon by SpongePowered.

the class SnapshotGenerationTest method init.

@Before
public void init() {
    PluginManager manager = Mockito.mock(PluginManager.class);
    this.eventManager = new SpongeEventManager(this.logger, manager);
    try {
        Field field = Timings.class.getDeclaredField("factory");
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, Mockito.mock(TimingsFactory.class));
    } catch (IllegalAccessException | NoSuchFieldException e) {
        e.printStackTrace();
    }
    this.plugin = new Object();
    PluginContainer container = Mockito.mock(PluginContainer.class);
    Mockito.when(manager.fromInstance(this.plugin)).thenReturn(Optional.of(container));
    Cause cause = Cause.of(EventContext.empty(), this);
    this.entity = Mockito.mock(Entity.class, withSettings().defaultAnswer(Mockito.RETURNS_MOCKS));
    this.event = SpongeEventFactory.createSpawnEntityEvent(cause, Lists.newArrayList(this.entity));
    Game game = mock(Game.class);
    CauseStackManager csm = mock(CauseStackManager.class);
    Mockito.when(game.getCauseStackManager()).thenReturn(csm);
}
Also used : Entity(org.spongepowered.api.entity.Entity) PluginContainer(org.spongepowered.plugin.PluginContainer) PluginManager(org.spongepowered.api.plugin.PluginManager) Field(java.lang.reflect.Field) Game(org.spongepowered.api.Game) CauseStackManager(org.spongepowered.api.event.CauseStackManager) TimingsFactory(co.aikar.timings.TimingsFactory) Cause(org.spongepowered.api.event.cause.Cause) Before(org.junit.Before)

Example 9 with CauseStackManager

use of org.spongepowered.api.event.CauseStackManager in project SpongeCommon by SpongePowered.

the class MixinRConThreadClient method run.

/**
 * @author Cybermaxke
 * @reason Fix RCON, is completely broken
 */
@Override
@Overwrite
public void run() {
    // / Sponge: START
    // Initialize the source
    this.source = new RConConsoleSource(SpongeImpl.getServer());
    ((IMixinRConConsoleSource) this.source).setConnection((RConThreadClient) (Object) this);
    // Call the connection event
    final RconConnectionEvent.Connect connectEvent;
    try {
        connectEvent = SpongeImpl.getScheduler().callSync(() -> {
            final CauseStackManager causeStackManager = Sponge.getCauseStackManager();
            causeStackManager.pushCause(this);
            causeStackManager.pushCause(this.source);
            final RconConnectionEvent.Connect event = SpongeEventFactory.createRconConnectionEventConnect(causeStackManager.getCurrentCause(), (RconSource) this.source);
            SpongeImpl.postEvent(event);
            causeStackManager.popCauses(2);
            return event;
        }).get();
    } catch (InterruptedException | ExecutionException ignored) {
        closeSocket();
        return;
    }
    if (connectEvent.isCancelled()) {
        closeSocket();
        return;
    }
    // /         'closeSocket' is moved out of the loop
    while (true) {
        try {
            if (!this.running) {
                break;
            }
            final BufferedInputStream bufferedinputstream = new BufferedInputStream(this.clientSocket.getInputStream());
            final int i = bufferedinputstream.read(this.buffer, 0, this.buffer.length);
            if (10 <= i) {
                int j = 0;
                final int k = RConUtils.getBytesAsLEInt(this.buffer, 0, i);
                if (k != i - 4) {
                    break;
                }
                j += 4;
                final int l = RConUtils.getBytesAsLEInt(this.buffer, j, i);
                j += 4;
                final int i1 = RConUtils.getRemainingBytesAsLEInt(this.buffer, j);
                j += 4;
                switch(i1) {
                    case 2:
                        if (this.loggedIn) {
                            final String command = RConUtils.getBytesAsString(this.buffer, j, i);
                            try {
                                // / Sponge: START
                                // Execute the command on the main thread and wait for it
                                SpongeImpl.getScheduler().callSync(() -> {
                                    final CauseStackManager causeStackManager = Sponge.getCauseStackManager();
                                    // Only add the RemoteConnection here, the RconSource
                                    // will be added by the command manager
                                    causeStackManager.pushCause(this);
                                    SpongeImpl.getServer().getCommandManager().executeCommand(this.source, command);
                                    causeStackManager.popCause();
                                }).get();
                                final String logContents = this.source.getLogContents();
                                this.source.resetLog();
                                sendMultipacketResponse(l, logContents);
                            // / Sponge: END
                            } catch (Exception exception) {
                                sendMultipacketResponse(l, "Error executing: " + command + " (" + exception.getMessage() + ")");
                            }
                            continue;
                        }
                        sendLoginFailedResponse();
                        // Sponge: 'continue' -> 'break', disconnect when a invalid operation is requested
                        break;
                    case 3:
                        final String password = RConUtils.getBytesAsString(this.buffer, j, i);
                        if (!password.isEmpty() && password.equals(this.rconPassword)) {
                            // / Sponge: START
                            final RconConnectionEvent.Login event = SpongeImpl.getScheduler().callSync(() -> {
                                final CauseStackManager causeStackManager = Sponge.getCauseStackManager();
                                causeStackManager.pushCause(this);
                                causeStackManager.pushCause(this.source);
                                final RconConnectionEvent.Login event1 = SpongeEventFactory.createRconConnectionEventLogin(causeStackManager.getCurrentCause(), (RconSource) this.source);
                                SpongeImpl.postEvent(event1);
                                causeStackManager.popCauses(2);
                                return event1;
                            }).get();
                            if (!event.isCancelled()) {
                                this.loggedIn = true;
                                sendResponse(l, 2, "");
                                continue;
                            }
                        // / Sponge: END
                        }
                        this.loggedIn = false;
                        sendLoginFailedResponse();
                        // Sponge: 'continue' -> 'break', disconnect if login failed
                        break;
                    default:
                        sendMultipacketResponse(l, String.format("Unknown request %s", Integer.toHexString(i1)));
                        // Sponge: 'continue' -> 'break', disconnect when a invalid operation is requested
                        break;
                }
            }
        } catch (IOException e) {
            break;
        } catch (Exception e) {
            LOGGER.error("Exception whilst parsing RCON input", e);
            break;
        }
    }
    closeSocket();
}
Also used : RconSource(org.spongepowered.api.command.source.RconSource) IOException(java.io.IOException) RConConsoleSource(net.minecraft.network.rcon.RConConsoleSource) IMixinRConConsoleSource(org.spongepowered.common.interfaces.IMixinRConConsoleSource) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) BufferedInputStream(java.io.BufferedInputStream) CauseStackManager(org.spongepowered.api.event.CauseStackManager) RconConnectionEvent(org.spongepowered.api.event.network.rcon.RconConnectionEvent) ExecutionException(java.util.concurrent.ExecutionException) IMixinRConConsoleSource(org.spongepowered.common.interfaces.IMixinRConConsoleSource) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Example 10 with CauseStackManager

use of org.spongepowered.api.event.CauseStackManager in project SpongeAPI by SpongePowered.

the class ChildCommandsTest method initialize.

@Before
public void initialize() throws Exception {
    TestPlainTextSerializer.inject();
    Game game = mock(Game.class);
    CauseStackManager csm = mock(CauseStackManager.class);
    when(game.getCauseStackManager()).thenReturn(csm);
    when(csm.pushCause(null)).thenReturn(csm);
    when(csm.popCause()).thenReturn(null);
    CommandManager cm = mock(CommandManager.class);
    when(game.getCommandManager()).thenReturn(cm);
    TestHooks.setGame(game);
    TestHooks.setInstance("commandManager", cm);
}
Also used : Game(org.spongepowered.api.Game) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Before(org.junit.Before)

Aggregations

CauseStackManager (org.spongepowered.api.event.CauseStackManager)14 HashMap (java.util.HashMap)4 Map (java.util.Map)4 EventContextKeys (org.spongepowered.api.event.EventContextKeys)4 RconConnectionEvent (org.spongepowered.api.event.network.rcon.RconConnectionEvent)4 Inject (org.spongepowered.asm.mixin.injection.Inject)4 IOException (java.io.IOException)3 BlockPos (net.minecraft.core.BlockPos)3 BufferedInputStream (java.io.BufferedInputStream)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 List (java.util.List)2 Optional (java.util.Optional)2 ExecutionException (java.util.concurrent.ExecutionException)2 DoubleUnaryOperator (java.util.function.DoubleUnaryOperator)2 Predicate (java.util.function.Predicate)2 Registry (net.minecraft.core.Registry)2 ListTag (net.minecraft.nbt.ListTag)2 Entity (net.minecraft.world.entity.Entity)2