Example usage for io.netty.buffer ByteBuf writableBytes

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

Introduction

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

Prototype

public abstract int writableBytes();

Source Link

Document

Returns the number of writable bytes which is equal to (this.capacity - this.writerIndex) .

Usage

From source file:alluxio.worker.netty.DataServerUFSFileReadHandler.java

License:Apache License

@Override
protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException {
    ByteBuf buf = channel.alloc().buffer(len, len);
    try {//from www  .j  a  va  2 s.c  om
        InputStream in = ((FileReadRequestInternal) mRequest).mInputStream;
        if (in != null) { // if we have not reached the end of the file
            while (buf.writableBytes() > 0 && buf.writeBytes(in, buf.writableBytes()) != -1) {
            }
        }
        if (buf.readableBytes() == 0) {
            buf.release();
            return null;
        }
        return new DataNettyBufferV2(buf);
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}

From source file:com.cloudhopper.smpp.pdu.BaseSmResp.java

License:Apache License

@Override
public void writeBody(ByteBuf buffer) throws UnrecoverablePduException, RecoverablePduException {
    // when this PDU was parsed, it's possible it was missing the messageId instead
    // of having a NULL messageId. If that's the case, the commandLength will be just
    // enough for the headers (and theoretically any optional TLVs). Don't try to
    // write the NULL byte for that case.
    // See special note in 4.4.2 of SMPP 3.4 spec
    if (!((buffer.writableBytes() == 0) && (this.messageId == null))) {
        ChannelBufferUtil.writeNullTerminatedString(buffer, this.messageId);
    }//from w ww .j  a  v a 2  s  . c o  m
}

From source file:com.datastax.driver.core.FrameCompressor.java

License:Apache License

protected static ByteBuffer outputNioBuffer(ByteBuf buf) {
    int index = buf.writerIndex();
    int len = buf.writableBytes();
    return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len);
}

From source file:com.github.sparkfy.network.protocol.MessageEncoder.java

License:Apache License

/***
 * Encodes a Message by invoking its encode() method. For non-data messages, we will add one
 * ByteBuf to 'out' containing the total frame length, the message type, and the message itself.
 * In the case of a ChunkFetchSuccess, we will also add the ManagedBuffer corresponding to the
 * data to 'out', in order to enable zero-copy transfer.
 *//*ww  w.  j  a v  a  2  s  . co m*/
@Override
public void encode(ChannelHandlerContext ctx, Message in, List<Object> out) throws Exception {
    Object body = null;
    long bodyLength = 0;
    boolean isBodyInFrame = false;

    // If the message has a body, take it out to enable zero-copy transfer for the payload.
    if (in.body() != null) {
        try {
            bodyLength = in.body().size();
            body = in.body().convertToNetty();
            isBodyInFrame = in.isBodyInFrame();
        } catch (Exception e) {
            in.body().release();
            if (in instanceof AbstractResponseMessage) {
                AbstractResponseMessage resp = (AbstractResponseMessage) in;
                // Re-encode this message as a failure response.
                String error = e.getMessage() != null ? e.getMessage() : "null";
                logger.error(
                        String.format("Error processing %s for client %s", in, ctx.channel().remoteAddress()),
                        e);
                encode(ctx, resp.createFailureResponse(error), out);
            } else {
                throw e;
            }
            return;
        }
    }

    Message.Type msgType = in.type();
    // All messages have the frame length, message type, and message itself. The frame length
    // may optionally include the length of the body data, depending on what message is being
    // sent.
    int headerLength = 8 + msgType.encodedLength() + in.encodedLength();
    long frameLength = headerLength + (isBodyInFrame ? bodyLength : 0);
    ByteBuf header = ctx.alloc().heapBuffer(headerLength);
    header.writeLong(frameLength);
    msgType.encode(header);
    in.encode(header);
    assert header.writableBytes() == 0;

    if (body != null) {
        // We transfer ownership of the reference on in.body() to MessageWithHeader.
        // This reference will be freed when MessageWithHeader.deallocate() is called.
        out.add(new MessageWithHeader(in.body(), header, body, bodyLength));
    } else {
        out.add(header);
    }
}

From source file:com.linecorp.armeria.internal.grpc.GrpcMessageMarshaller.java

License:Apache License

private ByteBuf serializeProto(Message message) throws IOException {
    if (GrpcSerializationFormats.isProto(serializationFormat)) {
        final ByteBuf buf = alloc.buffer(message.getSerializedSize());
        boolean success = false;
        try {//from   ww  w . ja v  a2s.c  o m
            message.writeTo(CodedOutputStream.newInstance(buf.nioBuffer(0, buf.writableBytes())));
            buf.writerIndex(buf.capacity());
            success = true;
        } finally {
            if (!success) {
                buf.release();
            }
        }
        return buf;
    }

    if (GrpcSerializationFormats.isJson(serializationFormat)) {
        final ByteBuf buf = alloc.buffer();
        boolean success = false;
        try (ByteBufOutputStream os = new ByteBufOutputStream(buf)) {
            jsonMarshaller.writeValue(message, os);
            success = true;
        } finally {
            if (!success) {
                buf.release();
            }
        }
        return buf;
    }
    throw new IllegalStateException("Unknown serialization format: " + serializationFormat);
}

From source file:com.tesora.dve.sql.LargeMaxPktTest.java

License:Open Source License

@Test
public void testComQueryMessageContinuationOverlap() throws Exception {
    int defaultMaxPacket = 0xFFFFFF;
    int payloadSize = (defaultMaxPacket * 4) + (4 * 40); //four full packets and a little change, divisible by 4.
    ByteBuf source = Unpooled.buffer(payloadSize, payloadSize);
    Random rand = new Random(239873L);
    while (source.isWritable())
        source.writeInt(rand.nextInt());
    Assert.assertEquals(source.writableBytes(), 0, "Oops, I intended to fill up the source buffer");

    ByteBuf dest = Unpooled.buffer(payloadSize);

    MSPComQueryRequestMessage outboundMessage = MSPComQueryRequestMessage.newMessage(source.array());
    Packet.encodeFullMessage((byte) 0, outboundMessage, dest);

    int lengthOfNonUserdata = 5 + 4 + 4 + 4 + 4;
    Assert.assertEquals(dest.readableBytes(), payloadSize + lengthOfNonUserdata,
            "Number of bytes in destination buffer is wrong");

    Assert.assertEquals(dest.getUnsignedMedium(0), defaultMaxPacket, "First length should be maximum");
    Assert.assertEquals(dest.getByte(3), (byte) 0, "First sequenceID should be zero");
    Assert.assertEquals(dest.getByte(4), (byte) MSPComQueryRequestMessage.TYPE_IDENTIFIER,
            "First byte of payload should be MSPComQueryRequestMessage.TYPE_IDENTIFIER");

    ByteBuf sliceFirstPayload = dest.slice(5, (0xFFFFFF - 1));
    Assert.assertEquals(sliceFirstPayload, source.slice(0, 0xFFFFFF - 1));

}

From source file:com.tesora.dve.sql.LargeMaxPktTest.java

License:Open Source License

@Test
public void testComQueryMessageContinuationExact() throws Exception {
    int defaultMaxPacket = 0xFFFFFF;
    int payloadSize = (defaultMaxPacket * 4); //four full packets exactly, requires an empty trailing packet.
    ByteBuf source = Unpooled.buffer(payloadSize, payloadSize);
    Random rand = new Random(239873L);
    while (source.isWritable())
        source.writeInt(rand.nextInt());
    Assert.assertEquals(source.writableBytes(), 0, "Oops, I intended to fill up the source buffer");

    ByteBuf dest = Unpooled.buffer(payloadSize);

    MSPComQueryRequestMessage outboundMessage = MSPComQueryRequestMessage.newMessage(source.array());
    Packet.encodeFullMessage((byte) 0, outboundMessage, dest);

    int lengthOfNonUserdata = 5 + 4 + 4 + 4 + 4;//last packet has zero length payload
    Assert.assertEquals(dest.readableBytes(), payloadSize + lengthOfNonUserdata,
            "Number of bytes in destination buffer is wrong");

    Assert.assertEquals(dest.getUnsignedMedium(0), defaultMaxPacket, "First length should be maximum");
    Assert.assertEquals(dest.getByte(3), (byte) 0, "First sequenceID should be zero");
    Assert.assertEquals(dest.getByte(4), (byte) MSPComQueryRequestMessage.TYPE_IDENTIFIER,
            "First byte of payload should be MSPComQueryRequestMessage.TYPE_IDENTIFIER");

    ByteBuf sliceFirstPayload = dest.slice(5, (0xFFFFFF - 1));
    Assert.assertEquals(sliceFirstPayload, source.slice(0, 0xFFFFFF - 1));

}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecZLib.java

License:Apache License

private void deflate(ByteBuf out) {
    int numBytes;
    do {/*from ww  w.j  a v a  2 s  .  co m*/
        int writerIndex = out.writerIndex();
        numBytes = deflater.deflate(out.array(), out.arrayOffset() + writerIndex, out.writableBytes(),
                Deflater.SYNC_FLUSH);
        out.writerIndex(writerIndex + numBytes);
    } while (numBytes > 0);
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.CrypterTest.java

License:Open Source License

public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[] { 1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000 }) {
        buf.capacity(c);/*from w ww .  ja  v  a 2 s . c o  m*/
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);
        }

        channel.writeOutbound(buf.duplicate().retain());
        for (ByteBuf msg; (msg = channel.readOutbound()) != null;) {
            assertNotSame(buf, msg);
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.SignerTest.java

License:Open Source License

public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[] { 1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000 }) {
        buf.capacity(c);//from  w ww .  j a  va  2s  . co m
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);
        }

        channel.writeOutbound(buf.duplicate().retain());
        channel.runPendingTasks();
        for (Object msg; (msg = channel.readOutbound()) != null;) {
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}