Example usage for io.netty.buffer ByteBuf capacity

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

Introduction

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

Prototype

public abstract int capacity();

Source Link

Document

Returns the number of bytes (octets) this buffer can contain.

Usage

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

License:Apache License

public ByteBufLineReader(ByteBufInputChannel channel, ByteBuf buf) {
    this.readBytes = 0;
    this.channel = channel;
    this.buffer = buf;
    this.bufferSize = buf.capacity();
}

From source file:org.apache.tajo.tuple.memory.ResizableMemoryBlock.java

License:Apache License

public ResizableMemoryBlock(ByteBuf buffer) {
    this(buffer, new ResizableLimitSpec(buffer.capacity()));
}

From source file:org.apache.tinkerpop.gremlin.driver.handler.NioGremlinRequestEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext channelHandlerContext, final Object msg,
        final ByteBuf byteBuf) throws Exception {
    final RequestMessage requestMessage = (RequestMessage) msg;
    try {// w ww  . j a v  a 2 s . c  om
        if (binaryEncoding) {
            // wrap the serialized message/payload inside of a "frame".  this works around the problem where
            // the length of the payload is not encoded into the general protocol.  that length isn't needed
            // for websockets because under that protocol, the message is wrapped in a "websocket frame". this
            // is not the optimal way to deal with this really, but it does prevent a protocol change in this
            // immediate moment trying to get the NioChannelizer working.
            final ByteBuf bytes = serializer.serializeRequestAsBinary(requestMessage,
                    channelHandlerContext.alloc());
            byteBuf.writeInt(bytes.capacity());
            byteBuf.writeBytes(bytes);
        } else {
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            final byte[] bytes = textSerializer.serializeRequestAsString(requestMessage)
                    .getBytes(CharsetUtil.UTF_8);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    } catch (Exception ex) {
        logger.warn(String.format(
                "An error occurred during serialization of this request [%s] - it could not be sent to the server.",
                requestMessage), ex);
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.ser.AbstractGryoMessageSerializerV1d0.java

License:Apache License

@Override
public ResponseMessage deserializeResponse(final ByteBuf msg) throws SerializationException {
    try {/*from www.  j av  a  2 s.  c o  m*/
        final Kryo kryo = kryoThreadLocal.get();
        final byte[] payload = new byte[msg.capacity()];
        msg.readBytes(payload);
        try (final Input input = new Input(payload)) {
            final UUID requestId = kryo.readObjectOrNull(input, UUID.class);
            final int status = input.readShort();
            final String statusMsg = input.readString();
            final Map<String, Object> statusAttributes = (Map<String, Object>) kryo.readClassAndObject(input);
            final Object result = kryo.readClassAndObject(input);
            final Map<String, Object> metaAttributes = (Map<String, Object>) kryo.readClassAndObject(input);

            return ResponseMessage.build(requestId).code(ResponseStatusCode.getFromValue(status))
                    .statusMessage(statusMsg).statusAttributes(statusAttributes).result(result)
                    .responseMetaData(metaAttributes).create();
        }
    } catch (Exception ex) {
        logger.warn("Response [{}] could not be deserialized by {}.", msg,
                GryoMessageSerializerV1d0.class.getName());
        throw new SerializationException(ex);
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.ser.AbstractGryoMessageSerializerV3d0.java

License:Apache License

@Override
public ResponseMessage deserializeResponse(final ByteBuf msg) throws SerializationException {
    try {/*from ww  w  .j a  v  a  2  s .  c  om*/
        final Kryo kryo = kryoThreadLocal.get();
        final byte[] payload = new byte[msg.capacity()];
        msg.readBytes(payload);
        try (final Input input = new Input(payload)) {
            return kryo.readObject(input, ResponseMessage.class);
        }
    } catch (Exception ex) {
        logger.warn("Response [{}] could not be deserialized by {}.", msg,
                GryoMessageSerializerV1d0.class.getName());
        throw new SerializationException(ex);
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.NioGremlinResponseEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final ResponseMessage responseMessage,
        final ByteBuf byteBuf) throws Exception {
    final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get();
    final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get();

    try {/*from  ww w.ja  v a  2 s .c om*/
        if (!responseMessage.getStatus().getCode().isSuccess())
            errorMeter.mark();

        if (useBinary) {
            final ByteBuf bytes = serializer.serializeResponseAsBinary(responseMessage, ctx.alloc());
            byteBuf.writeInt(bytes.capacity());
            byteBuf.writeBytes(bytes);
            bytes.release();
        } else {
            // the expectation is that the GremlinTextRequestDecoder will have placed a MessageTextSerializer
            // instance on the channel.
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            final byte[] bytes = textSerializer.serializeResponseAsString(responseMessage)
                    .getBytes(CharsetUtil.UTF_8);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    } catch (Exception ex) {
        errorMeter.mark();
        logger.warn("The result [{}] in the request {} could not be serialized and returned.",
                responseMessage.getResult(), responseMessage.getRequestId(), ex);
        final String errorMessage = String.format("Error during serialization: %s",
                ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
        final ResponseMessage error = ResponseMessage.build(responseMessage.getRequestId())
                .statusMessage(errorMessage).code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION).create();
        if (useBinary) {
            final ByteBuf bytes = serializer.serializeResponseAsBinary(error, ctx.alloc());
            byteBuf.writeInt(bytes.capacity());
            byteBuf.writeBytes(bytes);
            bytes.release();
        } else {
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            final byte[] bytes = textSerializer.serializeResponseAsString(error).getBytes(CharsetUtil.UTF_8);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.NioGremlinResponseFrameEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final Frame frame, final ByteBuf byteBuf)
        throws Exception {
    if (frame.getMsg() instanceof ByteBuf) {
        final ByteBuf bytes = (ByteBuf) frame.getMsg();
        byteBuf.writeInt(bytes.capacity());
        byteBuf.writeBytes(bytes);// w  w  w  .j av a 2  s .c  om
        bytes.release();
    } else if (frame.getMsg() instanceof String) {
        final byte[] bytes = ((String) frame.getMsg()).getBytes(CharsetUtil.UTF_8);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}

From source file:org.atmosphere.nettosphere.ChunkedWriter.java

License:Apache License

@Override
public void close(final AtmosphereResponse response) throws IOException {
    if (!channel.isOpen() || doneProcessing.get())
        return;/*from  ww  w  .ja va 2s .com*/

    ByteBuf writeBuffer = writeHeadersForHttp(response);
    if (writeBuffer.capacity() > 0 && response != null) {
        try {
            lock.writeLock().lock();
            channel.writeAndFlush(writeBuffer).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    prepareForClose(response);
                }
            });
            channel.flush();
        } finally {
            lock.writeLock().unlock();
        }
    } else {
        try {
            lock.writeLock().lock();
            prepareForClose(response);
        } finally {
            lock.writeLock().unlock();
        }
    }
}

From source file:org.atmosphere.nettosphere.ChunkedWriter.java

License:Apache License

void _close(AtmosphereResponse response) throws UnsupportedEncodingException {
    if (!doneProcessing.getAndSet(true) && channel.isOpen()) {
        ByteBuf writeBuffer = writeHeaders(response);

        if (writeBuffer.capacity() != 0) {
            writeBuffer = Unpooled.wrappedBuffer(writeBuffer, END);
        } else {/*w  w w . j  av  a  2  s  .  c  om*/
            writeBuffer = Unpooled.buffer(ENDCHUNK.length).writeBytes(ENDCHUNK);
        }

        channel.writeAndFlush(writeBuffer).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                logger.trace("Async Closing Done {}", channel);
                if (!keepAlive) {
                    channel.close().awaitUninterruptibly();
                }
            }
        });

    }
}

From source file:org.atmosphere.nettosphere.ChunkedWriter.java

License:Apache License

@Override
public AsyncIOWriter asyncWrite(final AtmosphereResponse response, byte[] data, int offset, int length)
        throws IOException {

    // Client will close the connection if we don't reject empty bytes.
    if (length == 0) {
        logger.trace("Data is empty {} => {}", data, length);
        return this;
    }/*from w w w .ja  v a  2  s .c  o m*/

    ByteBuf writeBuffer = writeHeaders(response);
    if (headerWritten.get()) {
        if (writeBuffer.capacity() != 0) {
            writeBuffer = Unpooled.wrappedBuffer(writeBuffer,
                    Unpooled.wrappedBuffer(Integer.toHexString(length - offset).getBytes("UTF-8")), DELIMITER);
        } else {
            writeBuffer = Unpooled.wrappedBuffer(Integer.toHexString(length - offset).getBytes("UTF-8"),
                    CHUNK_DELIMITER);
        }
    }

    writeBuffer = Unpooled.wrappedBuffer(writeBuffer, Unpooled.wrappedBuffer(data, offset, length));
    if (headerWritten.get()) {
        writeBuffer.writeBytes(CHUNK_DELIMITER);
    }

    try {
        lock.writeLock().lock();

        // We got closed, so we throw an IOException so the message get cached.
        if (doneProcessing.get() && !response.resource().getAtmosphereConfig().framework().isDestroyed()) {
            throw Utils.ioExceptionForChannel(channel, response.uuid());
        }

        channel.writeAndFlush(writeBuffer);
    } catch (IOException ex) {
        logger.warn("", ex);
        throw ex;
    } finally {
        lock.writeLock().unlock();
    }
    lastWrite = System.currentTimeMillis();
    return this;
}