Example usage for io.netty.buffer ByteBuf ensureWritable

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

Introduction

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

Prototype

public abstract ByteBuf ensureWritable(int minWritableBytes);

Source Link

Document

Expands the buffer #capacity() to make sure the number of #writableBytes() writable bytes is equal to or greater than the specified value.

Usage

From source file:at.yawk.accordion.netty.Framer.java

License:Mozilla Public License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    // length of this message
    int length = msg.readableBytes();
    if (length > MAXIMUM_MESSAGE_LENGTH) {
        throw new IOException("Message too long: " + length + " bytes");
    }//from w  ww .  ja v  a 2s . co m
    out.ensureWritable(2 + length);

    // write
    out.writeShort(length);
    msg.readBytes(out, length);
}

From source file:com.chat.common.netty.handler.encode.ProtobufVarint32LengthFieldPrepender.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    int bodyLen = msg.readableBytes();
    int headerLen = computeRawVarint32Size(bodyLen);
    out.ensureWritable(headerLen + bodyLen);
    writeRawVarint32(out, bodyLen);//  ww w . ja v a2 s .  co  m
    out.writeBytes(msg, msg.readerIndex(), bodyLen);
}

From source file:com.cloudera.livy.client.local.rpc.KryoMessageCodec.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf buf) throws Exception {
    ByteBuffer msgData = maybeEncrypt(serializer.serialize(msg));
    LOG.debug("Encoded message of type {} ({} bytes)", msg.getClass().getName(), msgData.remaining());
    checkSize(msgData.remaining());/*from  w ww.j a  va  2s. c  o  m*/

    buf.ensureWritable(msgData.remaining() + 4);
    buf.writeInt(msgData.remaining());
    buf.writeBytes(msgData);
}

From source file:com.lambdaworks.redis.codec.StringCodec.java

License:Apache License

public void encode(String str, ByteBuf target) {

    if (str == null) {
        return;/*  w w w . j av  a2s.c  om*/
    }

    if (utf8) {
        ByteBufUtil.writeUtf8(target, str);
        return;
    }

    if (ascii) {
        ByteBufUtil.writeAscii(target, str);
        return;
    }

    CharsetEncoder encoder = CharsetUtil.encoder(charset);
    int length = (int) ((double) str.length() * encoder.maxBytesPerChar());
    target.ensureWritable(length);
    try {
        final ByteBuffer dstBuf = target.nioBuffer(0, length);
        final int pos = dstBuf.position();
        CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dstBuf);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        target.writerIndex(target.writerIndex() + dstBuf.position() - pos);
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
}

From source file:com.linecorp.armeria.server.grpc.ArmeriaServerCall.java

License:Apache License

private static void encodeHeader(CharSequence name, CharSequence value, ByteBuf buf) {
    final int nameLen = name.length();
    final int valueLen = value.length();
    final int entryLen = nameLen + valueLen + 4;
    buf.ensureWritable(entryLen);
    int offset = buf.writerIndex();
    writeAscii(buf, offset, name, nameLen);
    offset += nameLen;/*  w w w .  j  a v a 2s .  c  om*/
    buf.setByte(offset++, ':');
    buf.setByte(offset++, ' ');
    writeAscii(buf, offset, value, valueLen);
    offset += valueLen;
    buf.setByte(offset++, '\r');
    buf.setByte(offset++, '\n');
    buf.writerIndex(offset);
}

From source file:com.necla.simba.server.gateway.server.frontend.FrontendFrameEncoder.java

License:Apache License

private void compress(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
    LOG.debug("compress here");
    byte[] inAry = new byte[msg.readableBytes()];
    msg.readBytes(inAry);//from   w  ww  . j a v  a 2  s  .c  o m
    int sizeEstimate = (int) Math.ceil(inAry.length * 1.001) + 12 + 4;
    LOG.debug("compress here2");

    out.ensureWritable(sizeEstimate);

    int beginIndex = out.writerIndex();

    out.writerIndex(beginIndex + 4);

    try {

        deflater.setInput(inAry);

        while (!deflater.needsInput()) {
            LOG.debug("compress here3333");

            int numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length);
            LOG.debug("Compressed numBytes=" + numBytes);
            out.writeBytes(encodeBuf, 0, numBytes);
            LOG.debug("compress here4");

        }

        deflater.finish();
        while (!deflater.finished()) {
            int numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length);
            out.writeBytes(encodeBuf, 0, numBytes);
            LOG.debug("compress here5");

        }
        deflater.reset();
        int len = out.writerIndex() - beginIndex - 4;

        Stats.sent(out.writerIndex() + beginIndex + 4);

        LOG.debug("Compressed len=" + len);
        len |= (1 << 30);
        out.setInt(beginIndex, len);
    } catch (Exception e) {
        LOG.debug("Exception" + e);
    }
}

From source file:com.spotify.netty.handler.codec.zmtp.ZMTPUtils.java

License:Apache License

/**
 * Writes a ZMTP frame to a buffer.//from w ww  .  j  a  v  a 2 s  . c om
 *
 * @param frame  The frame to write.
 * @param buffer The target buffer.
 * @param more   True to write a more flag, false to write a final flag.
 */
public static void writeFrame(final ZMTPFrame frame, final ByteBuf buffer, final boolean more,
        final int version) {
    if (version == 1) {
        encodeLength(frame.size() + 1, buffer);
        buffer.writeByte(more ? MORE_FLAG : FINAL_FLAG);
    } else { // version == 2
        encodeZMTP2FrameHeader(frame.size(), more ? MORE_FLAG : FINAL_FLAG, buffer);
    }
    if (frame.hasData()) {
        //      final ByteBuf source = frame.getDataBuffer();
        byte[] data = frame.getData();
        buffer.ensureWritable(data.length);

        buffer.writeBytes(data);
        //      source.getBytes(source.readerIndex(), buffer, source.readableBytes());
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.Packet.java

License:Open Source License

public static int encodeFullPayload(int sequenceStart, ByteBuf payloadHolder, ByteBuf destination) {
    ByteBuf leBuf = destination.order(ByteOrder.LITTLE_ENDIAN);

    //TODO: this loop is identical to the one below, except it doesn't consume the source or update the destination.  Consolidate?
    //calculate the size of the final encoding, so we resize the destination at most once.
    int payloadRemaining = payloadHolder.readableBytes();
    int outputSize = 0;
    do {/* w  w  w .  j  a va2s  .c o m*/
        outputSize += 4; //header
        int chunkLength = Math.min(payloadRemaining, MAX_PAYLOAD);
        outputSize += chunkLength;
        payloadRemaining -= chunkLength;
        if (chunkLength == MAX_PAYLOAD)
            outputSize += 4; //need one more packet if last fragment is exactly 0xFFFF long.
    } while (payloadRemaining > 0);

    leBuf.ensureWritable(outputSize);

    int sequenceIter = sequenceStart;
    boolean lastChunkWasMaximumLength;
    do {
        int initialSize = payloadHolder.readableBytes();
        int maxSlice = MAX_PAYLOAD;
        int sendingPayloadSize = Math.min(maxSlice, initialSize);
        lastChunkWasMaximumLength = (sendingPayloadSize == maxSlice); //need to send a zero length payload if last fragment was exactly 0xFFFF long.

        ByteBuf nextChunk = payloadHolder.readSlice(sendingPayloadSize);
        leBuf.writeMedium(sendingPayloadSize);
        leBuf.writeByte(sequenceIter);
        leBuf.writeBytes(nextChunk);

        sequenceIter++;
    } while (payloadHolder.readableBytes() > 0 || lastChunkWasMaximumLength);
    return sequenceIter; //returns the next usable/expected sequence number.
}

From source file:com.torchmind.netty.msgpack.codec.MessageFrameCodec.java

License:Apache License

/**
 * {@inheritDoc}/*from  ww w  .j  av  a2  s. co  m*/
 */
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    // ensure buffer is writable
    out.ensureWritable((msg.readableBytes() + 4));

    // write length
    out.writeInt(msg.readableBytes());

    // write data
    out.writeBytes(msg);
}

From source file:com.zxcc.socket.protobuf.ProtobufVarint32LengthFieldPrepender.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    int bodyLen = msg.readableBytes();
    //        int headerLen = CodedOutputStream.computeRawVarint32Size(bodyLen);
    out.ensureWritable(bodyLen + 4);

    //        CodedOutputStream headerOut =
    //                CodedOutputStream.newInstance(new ByteBufOutputStream(out), headerLen);
    ////        headerOut.writeInt32NoTag(bodyLen);
    //        headerOut.writeFixed32NoTag(bodyLen);
    ////        headerOut.writeRawVarint32(bodyLen);
    //        headerOut.flush();
    out.writeInt(bodyLen);//from  w  ww .j ava2s  .com
    out.writeBytes(msg, msg.readerIndex(), bodyLen);
}