Search in sources :

Example 36 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project Glowstone by GlowstoneMC.

the class QueryTest method testChannelRead.

private void testChannelRead(QueryHandler handler, byte[] recv, byte[] send) throws Exception {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    ByteBufAllocator alloc = mock(ByteBufAllocator.class);
    when(ctx.alloc()).thenReturn(alloc);
    when(alloc.buffer()).thenReturn(Unpooled.buffer());
    DatagramPacket packet = new DatagramPacket(Unpooled.wrappedBuffer(recv), null, address);
    handler.channelRead(ctx, packet);
    verify(ctx).write(argThat(new DatagramPacketMatcher(send)));
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DatagramPacket(io.netty.channel.socket.DatagramPacket) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 37 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project Glowstone by GlowstoneMC.

the class GlowPlayer method streamBlocks.

/**
 * Streams chunks to the player's client.
 */
private void streamBlocks() {
    Set<Key> previousChunks = null;
    ArrayList<Key> newChunks = new ArrayList<>();
    int centralX = location.getBlockX() >> 4;
    int centralZ = location.getBlockZ() >> 4;
    int radius = Math.min(server.getViewDistance(), 1 + settings.getViewDistance());
    if (firstStream) {
        firstStream = false;
        for (int x = centralX - radius; x <= centralX + radius; x++) {
            for (int z = centralZ - radius; z <= centralZ + radius; z++) {
                newChunks.add(GlowChunk.Key.of(x, z));
            }
        }
    } else if (Math.abs(centralX - prevCentralX) > radius || Math.abs(centralZ - prevCentralZ) > radius) {
        knownChunks.clear();
        for (int x = centralX - radius; x <= centralX + radius; x++) {
            for (int z = centralZ - radius; z <= centralZ + radius; z++) {
                newChunks.add(GlowChunk.Key.of(x, z));
            }
        }
    } else if (forceStream || prevCentralX != centralX || prevCentralZ != centralZ) {
        previousChunks = new HashSet<>(knownChunks);
        for (int x = centralX - radius; x <= centralX + radius; x++) {
            for (int z = centralZ - radius; z <= centralZ + radius; z++) {
                Key key = GlowChunk.Key.of(x, z);
                if (knownChunks.contains(key)) {
                    previousChunks.remove(key);
                } else {
                    newChunks.add(key);
                }
            }
        }
    } else {
        // early end if there's no changes
        return;
    }
    prevCentralX = centralX;
    prevCentralZ = centralZ;
    // sort chunks by distance from player - closer chunks sent first
    newChunks.sort((a, b) -> {
        double dx = 16 * a.getX() + 8 - location.getX();
        double dz = 16 * a.getZ() + 8 - location.getZ();
        double da = dx * dx + dz * dz;
        dx = 16 * b.getX() + 8 - location.getX();
        dz = 16 * b.getZ() + 8 - location.getZ();
        double db = dx * dx + dz * dz;
        return Double.compare(da, db);
    });
    // populate then send chunks to the player
    // done in two steps so that all the new chunks are finalized before any of them are sent
    // this prevents sending a chunk then immediately sending block changes in it because
    // one of its neighbors has populated
    // first step: force population then acquire lock on each chunk
    newChunks.forEach(newChunk -> {
        try {
            world.getChunkManager().forcePopulation(newChunk.getX(), newChunk.getZ());
        } catch (IllegalArgumentException e) {
            // The show must go on, so catch it here!
            logger.log(Level.SEVERE, "", e);
        }
        knownChunks.add(newChunk);
        chunkLock.acquire(newChunk);
    });
    boolean skylight = world.getEnvironment() == Environment.NORMAL;
    ByteBufAllocator alloc = session.getChannel() == null ? null : session.getChannel().alloc();
    for (GlowChunk.Key key : newChunks) {
        GlowChunk chunk = world.getChunk(key);
        ChunkDataMessage message = chunk.toMessage(skylight, true, alloc);
        if (message == null || message.getData() == null) {
            // allocator failed
            break;
        }
        session.sendAndRelease(message, message.getData());
    }
    // send visible block entity data
    newChunks.stream().flatMap(key -> world.getChunkAt(key.getX(), key.getZ()).getRawBlockEntities().stream()).forEach(entity -> entity.update(this));
    // and remove old chunks
    if (previousChunks != null) {
        previousChunks.forEach(key -> {
            session.send(new UnloadChunkMessage(key.getX(), key.getZ()));
            knownChunks.remove(key);
            chunkLock.release(key);
        });
        previousChunks.clear();
    }
}
Also used : GlowBlock(net.glowstone.block.GlowBlock) PlayerPortalEvent(org.bukkit.event.player.PlayerPortalEvent) GlowTeam(net.glowstone.scoreboard.GlowTeam) PlayerStatisticIncrementEvent(org.bukkit.event.player.PlayerStatisticIncrementEvent) Entry(net.glowstone.net.message.play.game.UserListItemMessage.Entry) TitleMessage(net.glowstone.net.message.play.game.TitleMessage) MaterialData(org.bukkit.material.MaterialData) Location(org.bukkit.Location) Map(java.util.Map) PlayerToggleSneakEvent(org.bukkit.event.player.PlayerToggleSneakEvent) EntityAnimation(org.bukkit.EntityAnimation) GlowWorld(net.glowstone.GlowWorld) GlowInventory(net.glowstone.inventory.GlowInventory) Position(net.glowstone.util.Position) EntityMetadataMessage(net.glowstone.net.message.play.entity.EntityMetadataMessage) Entity(org.bukkit.entity.Entity) GlowEffect(net.glowstone.constants.GlowEffect) MainHand(org.bukkit.inventory.MainHand) OpenWindowMessage(net.glowstone.net.message.play.inv.OpenWindowMessage) BlockVector(org.bukkit.util.BlockVector) Advancement(org.bukkit.advancement.Advancement) InventoryView(org.bukkit.inventory.InventoryView) InventoryOpenEvent(org.bukkit.event.inventory.InventoryOpenEvent) ChunkLock(net.glowstone.chunk.ChunkManager.ChunkLock) PlayerUnregisterChannelEvent(org.bukkit.event.player.PlayerUnregisterChannelEvent) Convert(net.glowstone.util.Convert) BoundingBox(org.bukkit.util.BoundingBox) BlockBreakAnimationMessage(net.glowstone.net.message.play.game.BlockBreakAnimationMessage) WindowPropertyMessage(net.glowstone.net.message.play.inv.WindowPropertyMessage) UpdateBlockEntityMessage(net.glowstone.net.message.play.game.UpdateBlockEntityMessage) RespawnMessage(net.glowstone.net.message.play.game.RespawnMessage) EntityUtils(net.glowstone.util.EntityUtils) GameRules(net.glowstone.constants.GameRules) PlayerLocaleChangeEvent(org.bukkit.event.player.PlayerLocaleChangeEvent) SoundCategory(org.bukkit.SoundCategory) EventFactory(net.glowstone.EventFactory) EntityVelocityMessage(net.glowstone.net.message.play.entity.EntityVelocityMessage) BossBar(org.bukkit.boss.BossBar) PlayerLevelChangeEvent(org.bukkit.event.player.PlayerLevelChangeEvent) PlayerResourcePackStatusEvent(org.bukkit.event.player.PlayerResourcePackStatusEvent) PositionRotationMessage(net.glowstone.net.message.play.game.PositionRotationMessage) HealthMessage(net.glowstone.net.message.play.game.HealthMessage) PluginMessage(net.glowstone.net.message.play.game.PluginMessage) Preconditions(com.google.common.base.Preconditions) Plugin(org.bukkit.plugin.Plugin) StatusFlags(net.glowstone.entity.meta.MetadataIndex.StatusFlags) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) SetWindowSlotMessage(net.glowstone.net.message.play.inv.SetWindowSlotMessage) Player(org.bukkit.entity.Player) PlayEffectMessage(net.glowstone.net.message.play.game.PlayEffectMessage) BlockChangeMessage(net.glowstone.net.message.play.game.BlockChangeMessage) Unpooled(io.netty.buffer.Unpooled) GlowWorldBorder(net.glowstone.GlowWorldBorder) Scoreboard(org.bukkit.scoreboard.Scoreboard) Merchant(org.bukkit.inventory.Merchant) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Locale(java.util.Locale) Instrument(org.bukkit.Instrument) Recipe(org.bukkit.inventory.Recipe) DamageCause(org.bukkit.event.entity.EntityDamageEvent.DamageCause) GlowChunk(net.glowstone.chunk.GlowChunk) Collection(java.util.Collection) Property(org.bukkit.inventory.InventoryView.Property) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BanList(org.bukkit.BanList) Reason(net.glowstone.net.message.play.game.StateChangeMessage.Reason) UUID(java.util.UUID) MultiBlockChangeMessage(net.glowstone.net.message.play.game.MultiBlockChangeMessage) UnloadChunkMessage(net.glowstone.net.message.play.game.UnloadChunkMessage) EntityType(org.bukkit.entity.EntityType) Collectors(java.util.stream.Collectors) StateChangeMessage(net.glowstone.net.message.play.game.StateChangeMessage) Villager(org.bukkit.entity.Villager) Objects(java.util.Objects) ComponentSerializer(net.md_5.bungee.chat.ComponentSerializer) PlayerExpChangeEvent(org.bukkit.event.player.PlayerExpChangeEvent) Queue(java.util.Queue) BlockBed(net.glowstone.block.blocktype.BlockBed) Title(com.destroystokyo.paper.Title) GlowServer.logger(net.glowstone.GlowServer.logger) InventoryUtil(net.glowstone.util.InventoryUtil) Level(java.util.logging.Level) HashSet(java.util.HashSet) GameMode(org.bukkit.GameMode) Environment(org.bukkit.World.Environment) ImmutableList(com.google.common.collect.ImmutableList) TickUtil(net.glowstone.util.TickUtil) ClientSettings(net.glowstone.entity.meta.ClientSettings) AsyncPlayerChatEvent(org.bukkit.event.player.AsyncPlayerChatEvent) MapView(org.bukkit.map.MapView) LinkedList(java.util.LinkedList) SpawnPositionMessage(net.glowstone.net.message.play.game.SpawnPositionMessage) WeatherType(org.bukkit.WeatherType) ExperienceMessage(net.glowstone.net.message.play.game.ExperienceMessage) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) GlowParticle(net.glowstone.constants.GlowParticle) NamedSoundEffectMessage(net.glowstone.net.message.play.game.NamedSoundEffectMessage) ConcurrentLinkedDeque(java.util.concurrent.ConcurrentLinkedDeque) Particle(org.bukkit.Particle) ItemFood(net.glowstone.block.itemtype.ItemFood) ChatColor(org.bukkit.ChatColor) GlowFishingHook(net.glowstone.entity.passive.GlowFishingHook) UserListHeaderFooterMessage(net.glowstone.net.message.play.game.UserListHeaderFooterMessage) HeldItemMessage(net.glowstone.net.message.play.inv.HeldItemMessage) ItemTable(net.glowstone.block.ItemTable) GlowBoss(net.glowstone.entity.monster.GlowBoss) PlayerVelocityEvent(org.bukkit.event.player.PlayerVelocityEvent) MapDataMessage(net.glowstone.net.message.play.game.MapDataMessage) PlayerBedLeaveEvent(org.bukkit.event.player.PlayerBedLeaveEvent) StopSoundMessage(net.glowstone.net.message.play.game.StopSoundMessage) World(org.bukkit.World) CloseWindowMessage(net.glowstone.net.message.play.inv.CloseWindowMessage) ChunkDataMessage(net.glowstone.net.message.play.game.ChunkDataMessage) Material(org.bukkit.Material) GlowInventoryView(net.glowstone.inventory.GlowInventoryView) BlockData(org.bukkit.block.data.BlockData) Set(java.util.Set) DelegateDeserialization(org.bukkit.configuration.serialization.DelegateDeserialization) ToolType(net.glowstone.inventory.ToolType) StandardCharsets(java.nio.charset.StandardCharsets) ItemStack(org.bukkit.inventory.ItemStack) ClientOption(com.destroystokyo.paper.ClientOption) MetadataIndex(net.glowstone.entity.meta.MetadataIndex) Action(net.glowstone.net.message.play.game.TitleMessage.Action) GlowOfflinePlayer(net.glowstone.GlowOfflinePlayer) InventoryMonitor(net.glowstone.inventory.InventoryMonitor) PlayerChangedMainHandEvent(org.bukkit.event.player.PlayerChangedMainHandEvent) Tag(org.bukkit.Tag) TimeMessage(net.glowstone.net.message.play.game.TimeMessage) Message(com.flowpowered.network.Message) PlayerRespawnEvent(org.bukkit.event.player.PlayerRespawnEvent) ArrayList(java.util.ArrayList) PlayerRegisterChannelEvent(org.bukkit.event.player.PlayerRegisterChannelEvent) BaseComponent(net.md_5.bungee.api.chat.BaseComponent) ProfileCache(net.glowstone.entity.meta.profile.ProfileCache) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) SetWindowContentsMessage(net.glowstone.net.message.play.inv.SetWindowContentsMessage) PlayParticleMessage(net.glowstone.net.message.play.game.PlayParticleMessage) Nullable(javax.annotation.Nullable) ResourcePackSendMessage(net.glowstone.net.message.play.player.ResourcePackSendMessage) TeleportCause(org.bukkit.event.player.PlayerTeleportEvent.TeleportCause) EntityRegainHealthEvent(org.bukkit.event.entity.EntityRegainHealthEvent) PlayerToggleSprintEvent(org.bukkit.event.player.PlayerToggleSprintEvent) Vector(org.bukkit.util.Vector) DyeColor(org.bukkit.DyeColor) Firework(org.bukkit.entity.Firework) PlayerProfile(com.destroystokyo.paper.profile.PlayerProfile) Enchantment(org.bukkit.enchantments.Enchantment) Statistic(org.bukkit.Statistic) Projectile(org.bukkit.entity.Projectile) PlayerBedEnterEvent(org.bukkit.event.player.PlayerBedEnterEvent) BlockFace(org.bukkit.block.BlockFace) Conversation(org.bukkit.conversations.Conversation) StatisticMap(net.glowstone.util.StatisticMap) Block(org.bukkit.block.Block) Difficulty(org.bukkit.Difficulty) DestroyEntitiesMessage(net.glowstone.net.message.play.entity.DestroyEntitiesMessage) PlayerReader(net.glowstone.io.PlayerDataService.PlayerReader) PlayerInventory(org.bukkit.inventory.PlayerInventory) SignEntity(net.glowstone.block.entity.SignEntity) Bukkit(org.bukkit.Bukkit) AdvancementProgress(org.bukkit.advancement.AdvancementProgress) JoinGameMessage(net.glowstone.net.message.play.game.JoinGameMessage) MaterialTags(com.destroystokyo.paper.MaterialTags) CreatureSpawnEvent(org.bukkit.event.entity.CreatureSpawnEvent) ChatMessageType(net.md_5.bungee.api.ChatMessageType) Sound(org.bukkit.Sound) InetSocketAddress(java.net.InetSocketAddress) List(java.util.List) JSONObject(org.json.simple.JSONObject) Key(net.glowstone.chunk.GlowChunk.Key) NotNull(org.jetbrains.annotations.NotNull) CompoundTag(net.glowstone.util.nbt.CompoundTag) ConversationAbandonedEvent(org.bukkit.conversations.ConversationAbandonedEvent) PlayerGameModeChangeEvent(org.bukkit.event.player.PlayerGameModeChangeEvent) PlayerRecipeMonitor(net.glowstone.inventory.crafting.PlayerRecipeMonitor) SignEditorMessage(net.glowstone.net.message.play.game.SignEditorMessage) Setter(lombok.Setter) SetPassengerMessage(net.glowstone.net.message.play.entity.SetPassengerMessage) GlowBlockEntity(net.glowstone.constants.GlowBlockEntity) Getter(lombok.Getter) MetadataMap(net.glowstone.entity.meta.MetadataMap) EntityAnimationMessage(net.glowstone.net.message.play.entity.EntityAnimationMessage) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Effect(org.bukkit.Effect) ByteBuf(io.netty.buffer.ByteBuf) Component(net.kyori.adventure.text.Component) GlowSession(net.glowstone.net.GlowSession) PlayerCommandPreprocessEvent(org.bukkit.event.player.PlayerCommandPreprocessEvent) GlowItem(net.glowstone.entity.objects.GlowItem) GlowMapCanvas(net.glowstone.map.GlowMapCanvas) GlowScoreboard(net.glowstone.scoreboard.GlowScoreboard) TextMessage(net.glowstone.util.TextMessage) Type(org.bukkit.Effect.Type) UpdateSignMessage(net.glowstone.net.message.play.game.UpdateSignMessage) StandardMessenger(org.bukkit.plugin.messaging.StandardMessenger) NamespacedKey(org.bukkit.NamespacedKey) Iterator(java.util.Iterator) ItemType(net.glowstone.block.itemtype.ItemType) GlowPlayerProfile(net.glowstone.entity.meta.profile.GlowPlayerProfile) PlayerDropItemEvent(org.bukkit.event.player.PlayerDropItemEvent) WorldType(org.bukkit.WorldType) UserListItemMessage(net.glowstone.net.message.play.game.UserListItemMessage) Note(org.bukkit.Note) FoodLevelChangeEvent(org.bukkit.event.entity.FoodLevelChangeEvent) PlayerTeleportEvent(org.bukkit.event.player.PlayerTeleportEvent) GlowSound(net.glowstone.constants.GlowSound) ChatMessage(net.glowstone.net.message.play.game.ChatMessage) Collections(java.util.Collections) PlayerChangedWorldEvent(org.bukkit.event.player.PlayerChangedWorldEvent) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ArrayList(java.util.ArrayList) UnloadChunkMessage(net.glowstone.net.message.play.game.UnloadChunkMessage) Key(net.glowstone.chunk.GlowChunk.Key) ChunkDataMessage(net.glowstone.net.message.play.game.ChunkDataMessage) Key(net.glowstone.chunk.GlowChunk.Key) NamespacedKey(org.bukkit.NamespacedKey) GlowChunk(net.glowstone.chunk.GlowChunk)

Example 38 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project crate by crate.

the class MessagesTest method testBufferInSendDataRowIsReleasedIfGetValueFromRowFails.

@Test
public void testBufferInSendDataRowIsReleasedIfGetValueFromRowFails() {
    Channel channel = mock(Channel.class);
    ByteBufAllocator byteBufAllocator = mock(ByteBufAllocator.class);
    ByteBuf buf = Unpooled.buffer();
    when(byteBufAllocator.buffer()).thenReturn(buf);
    when(channel.alloc()).thenReturn(byteBufAllocator);
    try {
        Messages.sendDataRow(channel, new Row() {

            @Override
            public int numColumns() {
                return 1;
            }

            @Override
            public Object get(int index) {
                throw new IllegalArgumentException("Dummy");
            }
        }, Collections.singletonList(PGTypes.get(DataTypes.INTEGER)), null);
        fail("sendDataRow should raise an exception");
    } catch (Exception ignored) {
    }
    assertThat(buf.refCnt(), is(0));
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) Row(io.crate.data.Row) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 39 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project spring-framework by spring-projects.

the class AbstractDataBufferAllocatingTests method verifyAllocations.

private void verifyAllocations() {
    if (this.bufferFactory instanceof NettyDataBufferFactory) {
        ByteBufAllocator allocator = ((NettyDataBufferFactory) this.bufferFactory).getByteBufAllocator();
        if (allocator instanceof PooledByteBufAllocator) {
            Instant start = Instant.now();
            while (true) {
                PooledByteBufAllocatorMetric metric = ((PooledByteBufAllocator) allocator).metric();
                long total = getAllocations(metric.directArenas()) + getAllocations(metric.heapArenas());
                if (total == 0) {
                    return;
                }
                if (Instant.now().isBefore(start.plus(Duration.ofSeconds(5)))) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                    // ignore
                    }
                    continue;
                }
                assertThat(total).as("ByteBuf Leak: " + total + " unreleased allocations").isEqualTo(0);
            }
        }
    }
}
Also used : UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) Instant(java.time.Instant) PooledByteBufAllocatorMetric(io.netty.buffer.PooledByteBufAllocatorMetric) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator)

Example 40 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project baseio by generallycloud.

the class TestNettyByteBuf method test_release.

static void test_release() {
    ByteBufAllocator a = ByteBufAllocator.DEFAULT;
    Util.exec(() -> {
        buf = a.buffer(16);
    });
    Util.exec(() -> {
        buf.release();
    });
    System.out.println(buf);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator)

Aggregations

ByteBufAllocator (io.netty.buffer.ByteBufAllocator)79 ByteBuf (io.netty.buffer.ByteBuf)48 ArrayList (java.util.ArrayList)17 Test (org.junit.Test)17 Test (org.junit.jupiter.api.Test)11 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)10 Channel (io.netty.channel.Channel)9 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 IOException (java.io.IOException)8 UnpooledByteBufAllocator (io.netty.buffer.UnpooledByteBufAllocator)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 ChannelFuture (io.netty.channel.ChannelFuture)6 Mono (reactor.core.publisher.Mono)6 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)4 InetSocketAddress (java.net.InetSocketAddress)4 StandardCharsets (java.nio.charset.StandardCharsets)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 NettyDataBufferFactory (org.springframework.core.io.buffer.NettyDataBufferFactory)4 RecvByteBufAllocator (io.netty.channel.RecvByteBufAllocator)3 ByteBuffer (java.nio.ByteBuffer)3