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:de.unipassau.isl.evs.ssh.core.network.handler.Encrypter.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
    final int decryptedLength = in.readableBytes();
    final int encryptedLength = encryptCipher.getOutputSize(decryptedLength);
    //Log.v(TAG, "Encrypting " + decryptedLength + "b data to " + encryptedLength + "b of encrypted data");
    out.writeInt(encryptedLength);//from  w ww  . ja va2 s  .c  o m

    out.ensureWritable(encryptedLength);
    final ByteBuffer inNio = in.nioBuffer(in.readerIndex(), decryptedLength);
    final ByteBuffer outNio = out.nioBuffer(out.writerIndex(), encryptedLength);
    encryptCipher.doFinal(inNio, outNio);
    if (inNio.hasRemaining()) {
        Log.wtf(TAG,
                "Crypto library did not read all bytes for encryption (" + inNio.remaining() + " remaining)");
    }
    if (outNio.hasRemaining()) {
        Log.wtf(TAG,
                "Crypto library did not write all bytes for encryption (" + outNio.remaining() + " remaining)");
    }
    out.writerIndex(out.writerIndex() + encryptedLength);
    in.readerIndex(in.readerIndex() + decryptedLength);
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private SSLEngineResult wrap(SSLEngine engine, ByteBuf in, ByteBuf out) throws SSLException {
    ByteBuffer in0 = in.nioBuffer();
    if (!in0.isDirect()) {
        ByteBuffer newIn0 = ByteBuffer.allocateDirect(in0.remaining());
        newIn0.put(in0).flip();/*from  www .  j  a  v a  2  s  .c  om*/
        in0 = newIn0;
    }

    for (;;) {
        ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
        SSLEngineResult result = engine.wrap(in0, out0);
        in.skipBytes(result.bytesConsumed());
        out.writerIndex(out.writerIndex() + result.bytesProduced());

        switch (result.getStatus()) {
        case BUFFER_OVERFLOW:
            out.ensureWritable(maxPacketBufferSize);
            break;
        default:
            return result;
        }
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private static SSLEngineResult unwrap(SSLEngine engine, ByteBuffer in, ByteBuf out) throws SSLException {
    int overflows = 0;
    for (;;) {/*from  ww  w  . j a  v a  2s.c  o  m*/
        ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
        SSLEngineResult result = engine.unwrap(in, out0);
        out.writerIndex(out.writerIndex() + result.bytesProduced());
        switch (result.getStatus()) {
        case BUFFER_OVERFLOW:
            int max = engine.getSession().getApplicationBufferSize();
            switch (overflows++) {
            case 0:
                out.ensureWritable(Math.min(max, in.remaining()));
                break;
            default:
                out.ensureWritable(max);
            }
            break;
        default:
            return result;
        }
    }
}

From source file:io.hekate.network.netty.NetworkProtocolCodec.java

License:Apache License

private static void doEncode(Object msg, ByteBufDataWriter out, Codec<Object> codec) throws CodecException {
    ByteBuf buf = out.buffer();

    try {/*from ww w  .  java 2 s .  c  om*/
        // Header indexes.
        int headStartIdx = buf.writerIndex();
        int headEndIdx = headStartIdx + HEADER_LENGTH;

        // Placeholder for the header.
        buf.ensureWritable(HEADER_LENGTH).writerIndex(headEndIdx);

        boolean internalMsg;

        if (msg instanceof NetworkProtocol) {
            // Encode internal message.
            internalMsg = true;

            NetworkProtocol netMsg = (NetworkProtocol) msg;

            encodeInternal(out, codec, netMsg);
        } else {
            // Encode user-defined message.
            internalMsg = false;

            codec.encode(msg, out);
        }

        // Calculate real message length.
        int len = buf.writerIndex() - headStartIdx;

        // Magic length value:
        //   negative - for protocol messages
        //   positive - for user messages
        if (internalMsg) {
            len = -len;
        }

        // Update length header.
        buf.setInt(headStartIdx, len);
    } catch (CodecException e) {
        throw e;
    } catch (Throwable t) {
        throw new CodecException("Failed to encode message [message=" + msg + ']', t);
    }
}

From source file:org.apache.activemq.artemis.protocol.amqp.util.DeliveryUtil.java

License:Apache License

public static int readDelivery(Receiver receiver, ByteBuf buffer) {
    int initial = buffer.writerIndex();
    // optimization by norman
    int count;/*from   w w  w .ja v  a  2 s.  co  m*/
    while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(),
            buffer.writableBytes())) > 0) {
        // Increment the writer index by the number of bytes written into it while calling recv.
        buffer.writerIndex(buffer.writerIndex() + count);
        buffer.ensureWritable(count);
    }
    return buffer.writerIndex() - initial;
}

From source file:org.apache.activemq.artemis.utils.UTF8Util.java

License:Apache License

public static void saveUTF(final ByteBuf out, final String str) {

    if (str.length() > 0xffff) {
        throw ActiveMQUtilBundle.BUNDLE.stringTooLong(str.length());
    }//from w  w w  . ja  v  a2  s .com

    final int len = UTF8Util.calculateUTFSize(str);

    if (len > 0xffff) {
        throw ActiveMQUtilBundle.BUNDLE.stringTooLong(len);
    }

    out.writeShort((short) len);

    final int stringLength = str.length();

    if (UTF8Util.isTrace) {
        // This message is too verbose for debug, that's why we are using trace here
        ActiveMQUtilLogger.LOGGER.trace("Saving string with utfSize=" + len + " stringSize=" + stringLength);
    }

    if (out.hasArray()) {
        out.ensureWritable(len);
        final byte[] bytes = out.array();
        final int writerIndex = out.writerIndex();
        final int index = out.arrayOffset() + writerIndex;
        if (PlatformDependent.hasUnsafe()) {
            unsafeOnHeapWriteUTF(str, bytes, index, stringLength);
        } else {
            writeUTF(str, bytes, index, stringLength);
        }
        out.writerIndex(writerIndex + len);
    } else {
        if (PlatformDependent.hasUnsafe() && out.hasMemoryAddress()) {
            out.ensureWritable(len);
            final long addressBytes = out.memoryAddress();
            final int writerIndex = out.writerIndex();
            unsafeOffHeapWriteUTF(str, addressBytes, writerIndex, stringLength);
            out.writerIndex(writerIndex + len);
        } else {
            final StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer();
            final byte[] bytes = buffer.borrowByteBuffer(len);
            writeUTF(str, bytes, 0, stringLength);
            out.writeBytes(bytes, 0, len);
        }
    }
}

From source file:org.apache.hive.spark.client.rpc.KryoMessageCodec.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf buf) throws Exception {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    Output kryoOut = new Output(bytes);
    kryos.get().writeClassAndObject(kryoOut, msg);
    kryoOut.flush();/*w ww  .j  ava2 s  .  co m*/

    byte[] msgData = maybeEncrypt(bytes.toByteArray());
    LOG.debug("Encoded message of type {} ({} bytes)", msg.getClass().getName(), msgData.length);
    checkSize(msgData.length);

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

From source file:org.apache.spark.sql.hive.thriftserver.rsc.KryoMessageCodec.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf buf) throws Exception {

    LOG.info("tlitest  message type: " + msg.getClass().getName());
    LOG.info("tlitest msg: " + msg);

    ByteBuffer msgData = maybeEncrypt(serializer.serialize(msg));

    LOG.info("Encoded message of type {} ({} bytes)", msg.getClass().getName(), msgData.remaining());
    checkSize(msgData.remaining());/*from w  w  w.  j ava2 s.  c  o m*/

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

From source file:org.apache.tajo.plan.function.stream.BufferPool.java

License:Apache License

/**
 * the ByteBuf will increase to writable size
 * @param buf//w ww .j a  va  2s .  c  o m
 * @param minWritableBytes required minimum writable size
 */
public static void ensureWritable(ByteBuf buf, int minWritableBytes) {
    buf.ensureWritable(minWritableBytes);
}

From source file:org.eclipse.neoscada.protocol.iec60870.apci.APDUEncoder.java

License:Open Source License

private void handleIFormat(final InformationTransfer msg, ByteBuf out) {
    final ByteBuf data = msg.getData();
    try {/*  ww  w . ja va2  s  .  c om*/
        out = out.order(ByteOrder.LITTLE_ENDIAN);

        final int len = data.readableBytes();

        if (len > Constants.APCI_MAX_DATA_LENGTH) {
            throw new EncoderException(String.format("Packet too big - %s bytes", len));
        }

        out.ensureWritable(6 + len);
        out.writeByte(Constants.START_BYTE);
        out.writeByte(4 + len);
        out.writeShort(msg.getSendSequenceNumber() << 1);
        out.writeShort(msg.getReceiveSequenceNumber() << 1);
        out.writeBytes(data);
    } finally {
        ReferenceCountUtil.release(msg.getData());
    }
}