Example usage for io.netty.buffer ByteBuf release

List of usage examples for io.netty.buffer ByteBuf release

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf release.

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:io.jsql.orientserver.OConnection.java

License:Open Source License

public void removebuff(ByteBuf buf) {
    buf.release();
    buf = null;
}

From source file:io.lettuce.core.protocol.CommandHandler.java

License:Apache License

/**
 * @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext, java.lang.Object)
 *//*from  w ww  .jav a2 s  . co m*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    ByteBuf input = (ByteBuf) msg;

    if (!input.isReadable() || input.refCnt() == 0) {
        logger.warn("{} Input not readable {}, {}", logPrefix(), input.isReadable(), input.refCnt());
        return;
    }

    if (debugEnabled) {
        logger.debug("{} Received: {} bytes, {} commands in the stack", logPrefix(), input.readableBytes(),
                stack.size());
    }

    try {
        if (buffer.refCnt() < 1) {
            logger.warn("{} Ignoring received data for closed or abandoned connection", logPrefix());
            return;
        }

        if (debugEnabled && ctx.channel() != channel) {
            logger.debug("{} Ignoring data for a non-registered channel {}", logPrefix(), ctx.channel());
            return;
        }

        if (traceEnabled) {
            logger.trace("{} Buffer: {}", logPrefix(), input.toString(Charset.defaultCharset()).trim());
        }

        buffer.writeBytes(input);

        decode(ctx, buffer);
    } finally {
        input.release();
    }
}

From source file:io.lunamc.plugins.example.netty.ExamplePlayHandler.java

License:Apache License

private void writeBrand(ChannelHandlerContext ctx) {
    ByteBuf data = ctx.alloc().buffer();
    ByteBuf out = ctx.alloc().buffer();//w w w .  j a  v a 2  s. c  om
    try {
        // Write plugin message data
        ProtocolUtils.writeString(data, "LunaMC_Example");

        // Write packet id of plugin message (0x18)
        ProtocolUtils.writeVarInt(out, 0x18);
        // Write channel name
        ProtocolUtils.writeString(out, "MC|Brand");
        // Write plugin message
        ProtocolUtils.writeVarInt(out, data.readableBytes());
        out.writeBytes(data);
    } finally {
        data.release();
    }

    // Send it to the client
    ctx.writeAndFlush(out, ctx.voidPromise());
}

From source file:io.moquette.parser.netty.SubAckEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext chc, SubAckMessage message, ByteBuf out) {
    if (message.types().isEmpty()) {
        throw new IllegalArgumentException("Found a suback message with empty topics");
    }/*from   ww  w  . j  a  v  a  2 s.c  o m*/

    int variableHeaderSize = 2 + message.types().size();
    ByteBuf buff = chc.alloc().buffer(6 + variableHeaderSize);
    try {
        buff.writeByte(AbstractMessage.SUBACK << 4);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeShort(message.getMessageID());
        for (QOSType c : message.types()) {
            buff.writeByte(c.byteValue());
        }

        out.writeBytes(buff);
    } finally {
        buff.release();
    }
}

From source file:io.pravega.shared.protocol.netty.AppendDecoder.java

License:Open Source License

private ByteBuf getAppendDataBuf(WireCommands.AppendBlockEnd blockEnd, int sizeOfWholeEventsInBlock)
        throws IOException {
    ByteBuf appendDataBuf = currentBlock.getData().slice(0, sizeOfWholeEventsInBlock);
    int remaining = currentBlock.getData().readableBytes() - sizeOfWholeEventsInBlock;
    if (remaining > 0) {
        ByteBuf dataRemainingInBlock = currentBlock.getData().slice(sizeOfWholeEventsInBlock, remaining);
        WireCommand cmd = CommandDecoder.parseCommand(dataRemainingInBlock);
        if (!(cmd.getType() == WireCommandType.PARTIAL_EVENT || cmd.getType() == WireCommandType.PADDING)) {
            throw new InvalidMessageException("Found " + cmd.getType()
                    + " at end of append block but was expecting a partialEvent or padding.");
        }/*  ww w  .j  a  v a2  s . c o m*/
        if (cmd.getType() == WireCommandType.PADDING && blockEnd.getData().readableBytes() != 0) {
            throw new InvalidMessageException("Unexpected data in BlockEnd");
        }
        if (cmd.getType() == WireCommandType.PARTIAL_EVENT) {
            // Work around a bug in netty:
            // See https://github.com/netty/netty/issues/5597
            if (appendDataBuf.readableBytes() == 0) {
                appendDataBuf.release();
                return wrappedBuffer(((WireCommands.PartialEvent) cmd).getData(), blockEnd.getData());
            } else {
                return wrappedBuffer(appendDataBuf, ((WireCommands.PartialEvent) cmd).getData(),
                        blockEnd.getData());
            }
        }
    }
    return appendDataBuf;
}

From source file:io.pravega.shared.protocol.netty.AppendEncodeDecodeTest.java

License:Open Source License

private void read(ByteBuf in, List<Object> results) throws Exception {
    ByteBuf segmented = (ByteBuf) lengthDecoder.decode(null, in);
    while (segmented != null) {
        int before = results.size();
        WireCommand command = CommandDecoder.parseCommand(segmented);
        if (appendDecoder.acceptInboundMessage(command)) {
            Request request = appendDecoder.processCommand(command);
            if (request != null) {
                results.add(request);//from  w w w  .ja  v a 2 s  .  c om
            }
        } else {
            results.add(command);
        }
        assertTrue(results.size() == before || results.size() == before + 1);
        segmented.release();
        segmented = (ByteBuf) lengthDecoder.decode(null, in);
    }
}

From source file:io.reactiverse.pgclient.impl.codec.decoder.InitiateSslHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // This must be a single byte buffer - after that follow the SSL handshake
    ByteBuf byteBuf = (ByteBuf) msg;
    byte b = byteBuf.getByte(0);
    byteBuf.release();
    switch (b) {/*  w  w  w  .  j  ava 2 s.  c om*/
    case MessageType.SSL_YES: {
        conn.socket().upgradeToSsl(v -> {
            ctx.pipeline().remove(this);
            upgradeFuture.complete();
        });
        break;
    }
    case MessageType.SSL_NO: {
        upgradeFuture.fail(new Exception("Postgres Server does not handle SSL connection"));
        break;
    }
    default:
        upgradeFuture.fail(new Exception("Invalid SSL connection message"));
        break;
    }
}

From source file:io.reactivesocket.netty.tcp.client.ReactiveSocketClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object content) {
    ByteBuf byteBuf = (ByteBuf) content;
    try {// ww w. j  a  v a  2  s  .com
        MutableDirectByteBuf mutableDirectByteBuf = new MutableDirectByteBuf(byteBuf);
        final Frame from = Frame.from(mutableDirectByteBuf, 0, mutableDirectByteBuf.capacity());
        subjects.forEach(o -> o.onNext(from));
    } finally {
        byteBuf.release();
    }
}

From source file:io.reactivesocket.netty.tcp.server.ReactiveSocketServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf content = (ByteBuf) msg;
    try {//from   ww w.  j  a v  a  2s  . c o  m
        MutableDirectByteBuf mutableDirectByteBuf = new MutableDirectByteBuf(content);
        Frame from = Frame.from(mutableDirectByteBuf, 0, mutableDirectByteBuf.capacity());
        channelRegistered(ctx);
        ServerTcpDuplexConnection connection = duplexConnections.computeIfAbsent(ctx.channel().id(), i -> {
            logger.info("No connection found for channel id: " + i + " from host "
                    + ctx.channel().remoteAddress().toString());
            ServerTcpDuplexConnection c = new ServerTcpDuplexConnection(ctx);
            ReactiveSocket reactiveSocket = DefaultReactiveSocket.fromServerConnection(c, setupHandler,
                    leaseGovernor, throwable -> throwable.printStackTrace());
            reactiveSocket.startAndWait();
            return c;
        });
        if (connection != null) {
            connection.getSubscribers().forEach(o -> o.onNext(from));
        }
    } finally {
        content.release();
    }
}

From source file:io.reactivex.netty.protocol.http.server.Http10Test.java

License:Apache License

@Test
public void testHttp1_0RequestWithContent() throws Exception {
    HttpClientRequest<ByteBuf> request = HttpClientRequest.create(HttpVersion.HTTP_1_0, HttpMethod.GET, "/");
    final ByteBuf response = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("localhost", mockServerPort)
            .enableWireLogging(LogLevel.ERROR).build().submit(request)
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() {
                @Override//  w  ww. j  a v  a 2 s.c  o  m
                public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> response) {
                    return response.getContent();
                }
            }).map(new Func1<ByteBuf, ByteBuf>() {
                @Override
                public ByteBuf call(ByteBuf byteBuf) {
                    return byteBuf.retain();
                }
            }).toBlocking().toFuture().get(1, TimeUnit.MINUTES);
    Assert.assertEquals("Unexpected Content.", WELCOME_SERVER_MSG, response.toString(Charset.defaultCharset()));
    response.release();
}