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:org.asynchttpclient.request.body.generator.PushBody.java

License:Open Source License

private void move(ByteBuf target, ByteBuffer source) {
    int size = Math.min(target.writableBytes(), source.remaining());
    if (size > 0) {
        ByteBuffer slice = source.slice();
        slice.limit(size);//from   w  w  w  . ja  v a 2  s.c o  m
        target.writeBytes(slice);
        source.position(source.position() + size);
    }
}

From source file:org.asynchttpclient.request.body.multipart.part.FileMultipartPart.java

License:Open Source License

@Override
protected long transferContentTo(ByteBuf target) throws IOException {
    int transferred = target.writeBytes(channel, target.writableBytes());
    position += transferred;/*from ww  w .j av a  2  s  . co m*/
    if (position == length) {
        state = MultipartState.POST_CONTENT;
        channel.close();
    }
    return transferred;
}

From source file:org.asynchttpclient.request.body.multipart.part.MultipartPart.java

License:Open Source License

protected long transfer(ByteBuf source, ByteBuf target, MultipartState sourceFullyWrittenState) {

    int sourceRemaining = source.readableBytes();
    int targetRemaining = target.writableBytes();

    if (sourceRemaining <= targetRemaining) {
        target.writeBytes(source);/*from   ww  w  .  j a v  a 2 s .com*/
        state = sourceFullyWrittenState;
        return sourceRemaining;
    } else {
        target.writeBytes(source, targetRemaining);
        return targetRemaining;
    }
}

From source file:org.curioswitch.common.server.framework.redis.ProtobufRedisCodec.java

License:Open Source License

private static void encodeTo(Message message, ByteBuf target) {
    try {/*from   ww w . jav a  2s . c  o m*/
        message.writeTo(
                CodedOutputStream.newInstance(target.nioBuffer(target.writerIndex(), target.writableBytes())));
    } catch (IOException e) {
        throw new UncheckedIOException("Could not encode message.", e);
    }
}

From source file:org.fusesource.hawtdispatch.netty.HawtSocketChannel.java

License:Apache License

private void onReadReady() {
    final ChannelPipeline pipeline = pipeline();
    final ByteBuf byteBuf = pipeline.inboundByteBuffer();
    boolean closed = false;
    boolean read = false;
    boolean firedInboundBufferSuspended = false;
    try {/*from ww w.j av  a  2s.  c om*/
        expandReadBuffer(byteBuf);
        loop: for (;;) {

            int localReadAmount = byteBuf.writeBytes(javaChannel(), byteBuf.writableBytes());
            if (localReadAmount > 0) {
                read = true;
            } else if (localReadAmount < 0) {
                closed = true;
                break;
            }

            switch (expandReadBuffer(byteBuf)) {
            case 0:
                // Read all - stop reading.
                break loop;
            case 1:
                // Keep reading until everything is read.
                break;
            case 2:
                // Let the inbound handler drain the buffer and continue reading.
                if (read) {
                    read = false;
                    pipeline.fireInboundBufferUpdated();
                    if (!byteBuf.isWritable()) {
                        throw new IllegalStateException(
                                "an inbound handler whose buffer is full must consume at " + "least one byte.");
                    }
                }
            }
        }
    } catch (Throwable t) {
        if (read) {
            read = false;
            pipeline.fireInboundBufferUpdated();
        }

        if (t instanceof IOException) {
            closed = true;
        } else if (!closed) {
            firedInboundBufferSuspended = true;
            pipeline.fireChannelReadSuspended();
        }
        pipeline().fireExceptionCaught(t);
    } finally {
        if (read) {
            pipeline.fireInboundBufferUpdated();
        }

        if (closed) {
            setInputShutdown();
            if (isOpen()) {
                if (Boolean.TRUE.equals(config().getOption(ChannelOption.ALLOW_HALF_CLOSURE))) {
                    pipeline.fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
                } else {
                    close(newPromise());
                }
            }
        } else if (!firedInboundBufferSuspended) {
            pipeline.fireChannelReadSuspended();
        }

        if (!config().isAutoRead()) {
            readSource.suspend();
        }
    }
}

From source file:org.hornetq.amqp.dealer.util.DeliveryUtil.java

License:Apache License

public static int readDelivery(Receiver receiver, ByteBuf buffer) {
    int initial = buffer.writerIndex();
    // optimization by norman
    int count;//w  w w . j  av 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);
    }
    return buffer.writerIndex() - initial;
}

From source file:org.opendaylight.capwap.ODLCapwapHeader.java

License:Open Source License

/**Method converts Capwap header encoder into byte array.
 * @return true: success, false: failure
 *///ww w .jav a  2  s.  c o  m
public boolean encodeHeader(ByteBuf bbuf) {
    if (bbuf.writableBytes() < ODLCapwapConsts.ODL_CAPWAP_MIN_HDRLEN) {
        System.out.println("Byte Buffer do not have capacity to write " + ODLCapwapConsts.ODL_CAPWAP_MIN_HDRLEN
                + " bytes");
        return false;
    }

    byte[] hdrbytes = new byte[ODLCapwapConsts.ODL_CAPWAP_MIN_HDRLEN];
    hdrbytes[0] = preamble;
    /* Converting the header len value */
    hdrbytes[1] = (byte) ((hlen >> 2) & ODLCapwapConsts.ODL_CAPWAP_HLEN_MASK);
    /* Filling higher 3bits of RID */
    hdrbytes[1] |= (byte) (rid & 0x1C);
    /* Filling lower 2bits of RID (higher 2 bits of byte2) */
    hdrbytes[2] = (byte) ((rid & 0x03) << 6);
    /* WBID - 5 bits - bits 3-7 */
    hdrbytes[2] |= (byte) (wbid & 0x3E);
    /* Copying the T flag */
    hdrbytes[2] |= (byte) ((flagBits & 0x20) >> 5);
    /* Copying other flag bits */
    hdrbytes[3] = (byte) ((flagBits & 0x1F) << 3);
    /* Filling first byte of fragment ID */
    hdrbytes[4] = (byte) ((fragId & 0xFF00) >> 8);
    /* Filling the second byte of fragment ID */
    hdrbytes[5] = (byte) (fragId & 0x00FF);
    /* Most significant 8 bits of 13 bits */
    hdrbytes[6] = (byte) (((fragOffset) & 0x1FE0) >> 5);
    /* Least significant 5 bits (higher 5 bits of byte 8) */
    hdrbytes[7] = (byte) ((fragOffset & 0x1F) << 3);

    bbuf.resetWriterIndex();
    bbuf.writeBytes(hdrbytes);

    return true;
}

From source file:org.opendaylight.tcpmd5.netty.MD5NioSocketChannel.java

License:Open Source License

@Override
protected int doReadBytes(final ByteBuf buf) throws IOException {
    return buf.writeBytes(javaChannel(), buf.writableBytes());
}

From source file:org.spout.api.protocol.ByteBufferChannelProcessorTest.java

License:Open Source License

@Test
public void randomPassthrough() {

    mainThread = Thread.currentThread();

    ByteBuf buffer = Unpooled.buffer(2048);

    ChannelHandlerContext ctx = ChannelHandlerContextFaker.setup();

    ByteBufferChannelProcessor processor = new ByteBufferChannelProcessor(256);

    byte[] input = new byte[LENGTH];
    byte[] output = new byte[LENGTH];

    Random r = new Random();

    for (int i = 0; i < input.length; i++) {
        input[i] = (byte) (r.nextInt());
    }/*from w w w  .j ava 2  s .c  o m*/

    int writePointer = 0;
    int readPointer = 0;

    int pass = 0;

    while (writePointer < LENGTH && (pass++) < 512) {

        int toWrite = r.nextInt(512);

        if (r.nextInt(10) == 0) {
            // simulate "large" packets
            toWrite *= 10;
        }

        if (toWrite > buffer.writableBytes()) {
            toWrite = buffer.writableBytes();
        }
        if (toWrite > LENGTH - writePointer) {
            toWrite = LENGTH - writePointer;
        }

        System.out.println("Writing block of size " + toWrite);

        buffer.writeBytes(input, writePointer, toWrite);
        writePointer += toWrite;

        ByteBuf outputBuffer = processor.write(ctx, buffer);

        buffer.discardReadBytes();

        while (outputBuffer.isReadable()) {
            int toRead = r.nextInt(768);
            if (toRead > outputBuffer.readableBytes()) {
                toRead = outputBuffer.readableBytes();
            }
            System.out.println("ToRead: " + toRead + " of " + outputBuffer.readableBytes());
            outputBuffer.readBytes(output, readPointer, toRead);
            readPointer += toRead;
            outputBuffer.discardReadBytes();
        }

        outputBuffer.release();
    }

    buffer.release();

    for (int i = 0; i < input.length; i++) {
        assertTrue("Mismatch at position " + i, input[i] == output[i]);
    }
}

From source file:org.spout.api.protocol.CommonChannelProcessor.java

License:Open Source License

@Override
public final synchronized ByteBuf write(ChannelHandlerContext ctx, final ByteBuf input, final ByteBuf buffer) {
    ByteBuf ByteBuf = buffer == null ? getNewBufferInstance(ctx, capacity) : buffer;
    int nextSize = capacity;
    int remaining;
    ArrayList<ByteBuf> consumedBuffers = null;
    while ((remaining = input.readableBytes()) > 0) {
        int clamped = (remaining > byteBuffer.length) ? byteBuffer.length : remaining;
        input.readBytes(byteBuffer, 0, clamped);
        write(byteBuffer, clamped);// w  w w.j  a va2  s  .c o m
        int read;
        while ((read = read(byteBuffer)) > 0) {
            if (ByteBuf.writableBytes() >= read) {
                ByteBuf.writeBytes(byteBuffer, 0, read);
            } else {
                ByteBuf newBuffer = getNewBufferInstance(ctx, nextSize);
                nextSize *= 2;
                if (consumedBuffers == null) {
                    consumedBuffers = new ArrayList<>(16);
                }
                consumedBuffers.add(ByteBuf);
                ByteBuf = newBuffer;
                ByteBuf.writeBytes(byteBuffer, 0, read);
            }
        }
    }
    if (consumedBuffers == null) {
        return ByteBuf;
    }

    consumedBuffers.add(ByteBuf);
    return Unpooled.wrappedBuffer(consumedBuffers.toArray(DUMMY_ARRAY));
}