Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

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 {//from w ww. j av a2 s  .co  m
        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.handler.WebSocketGremlinRequestEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext channelHandlerContext, final RequestMessage requestMessage,
        final List<Object> objects) throws Exception {
    try {//w  w  w. j av a2s  .co m
        if (binaryEncoding) {
            final ByteBuf encodedMessage = serializer.serializeRequestAsBinary(requestMessage,
                    channelHandlerContext.alloc());
            objects.add(new BinaryWebSocketFrame(encodedMessage));
        } else {
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            objects.add(new TextWebSocketFrame(textSerializer.serializeRequestAsString(requestMessage)));
        }
    } 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.server.handler.GremlinResponseFrameEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final ResponseMessage o, final List<Object> objects)
        throws Exception {
    final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get();
    final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get();
    final Session session = ctx.channel().attr(StateKey.SESSION).get();

    try {/* www  . ja v  a  2s  .  c om*/
        if (!o.getStatus().getCode().isSuccess())
            errorMeter.mark();

        if (useBinary) {
            final Frame serialized;

            // if the request came in on a session then the serialization must occur in that same thread, except
            // in the case of an error where we can free the session executor from having to do that job. the
            // problem here is that if the session executor is used in the case of an error and the executor is
            // blocked by parallel requests then there is no thread available to serialize the result and send
            // back the response as the workers get all tied up behind the session executor.
            if (null == session || !o.getStatus().getCode().isSuccess())
                serialized = new Frame(serializer.serializeResponseAsBinary(o, ctx.alloc()));
            else
                serialized = new Frame(session.getExecutor()
                        .submit(() -> serializer.serializeResponseAsBinary(o, ctx.alloc())).get());

            objects.add(serialized);
        } else {
            // the expectation is that the GremlinTextRequestDecoder will have placed a MessageTextSerializer
            // instance on the channel.
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;

            final Frame serialized;

            // if the request came in on a session then the serialization must occur that same thread except
            // in the case of errors for reasons described above.
            if (null == session || !o.getStatus().getCode().isSuccess())
                serialized = new Frame(textSerializer.serializeResponseAsString(o));
            else
                serialized = new Frame(
                        session.getExecutor().submit(() -> textSerializer.serializeResponseAsString(o)).get());

            objects.add(serialized);
        }
    } catch (Exception ex) {
        errorMeter.mark();
        logger.warn("The result [{}] in the request {} could not be serialized and returned.", o.getResult(),
                o.getRequestId(), ex);
        final String errorMessage = String.format("Error during serialization: %s",
                ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
        final ResponseMessage error = ResponseMessage.build(o.getRequestId()).statusMessage(errorMessage)
                .code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION).create();
        if (useBinary) {
            objects.add(serializer.serializeResponseAsBinary(error, ctx.alloc()));
        } else {
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            objects.add(textSerializer.serializeResponseAsString(error));
        }
    }
}

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 {//  ww w  .j ava2  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.WsGremlinBinaryRequestDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final BinaryWebSocketFrame frame,
        final List<Object> objects) throws Exception {
    final ByteBuf messageBytes = frame.content();
    final byte len = messageBytes.readByte();
    if (len <= 0) {
        objects.add(RequestMessage.INVALID);
        return;/*from   w ww .ja  v  a2 s  . c o  m*/
    }

    final ByteBuf contentTypeBytes = channelHandlerContext.alloc().buffer(len);
    try {
        messageBytes.readBytes(contentTypeBytes);
        final String contentType = contentTypeBytes.toString(UTF8);
        final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_SERIALIZER);

        // it's important to re-initialize these channel attributes as they apply globally to the channel. in
        // other words, the next request to this channel might not come with the same configuration and mixed
        // state can carry through from one request to the next
        channelHandlerContext.channel().attr(StateKey.SESSION).set(null);
        channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
        channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(true);

        try {
            objects.add(serializer.deserializeRequest(messageBytes.discardReadBytes()));
        } catch (SerializationException se) {
            objects.add(RequestMessage.INVALID);
        }
    } finally {
        contentTypeBytes.release();
    }
}

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

License:Apache License

@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final CloseWebSocketFrame frame,
        final List<Object> objects) throws Exception {
    final ByteBuf messageBytes = frame.content();
    final byte len = messageBytes.readByte();
    if (len <= 0) {
        objects.add(RequestMessage.INVALID);
        return;/*from w w  w .  j  ava2s  .  c om*/
    }

    final ByteBuf contentTypeBytes = channelHandlerContext.alloc().buffer(len);
    try {
        messageBytes.readBytes(contentTypeBytes);
        final String contentType = contentTypeBytes.toString(UTF8);
        final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_SERIALIZER);

        // it's important to re-initialize these channel attributes as they apply globally to the channel. in
        // other words, the next request to this channel might not come with the same configuration and mixed
        // state can carry through from one request to the next
        channelHandlerContext.channel().attr(StateKey.SESSION).set(null);
        channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
        channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(true);

        try {
            objects.add(serializer.deserializeRequest(messageBytes.discardReadBytes()));
        } catch (SerializationException se) {
            objects.add(RequestMessage.INVALID);
        }
    } finally {
        contentTypeBytes.release();
    }
}

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

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final ResponseMessage o, final List<Object> objects)
        throws Exception {
    final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get();
    final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get();
    final Session session = ctx.channel().attr(StateKey.SESSION).get();

    try {/*from   w ww.  j a  va2 s. c o m*/
        if (!o.getStatus().getCode().isSuccess())
            errorMeter.mark();

        if (useBinary) {
            final ByteBuf serialized;

            // if the request came in on a session then the serialization must occur in that same thread.
            if (null == session)
                serialized = serializer.serializeResponseAsBinary(o, ctx.alloc());
            else
                serialized = session.getExecutor()
                        .submit(() -> serializer.serializeResponseAsBinary(o, ctx.alloc())).get();

            objects.add(new BinaryWebSocketFrame(serialized));
        } else {
            // the expectation is that the GremlinTextRequestDecoder will have placed a MessageTextSerializer
            // instance on the channel.
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;

            final String serialized;

            // if the request came in on a session then the serialization must occur in that same thread.
            if (null == session)
                serialized = textSerializer.serializeResponseAsString(o);
            else
                serialized = session.getExecutor().submit(() -> textSerializer.serializeResponseAsString(o))
                        .get();

            objects.add(new TextWebSocketFrame(true, 0, serialized));
        }
    } catch (Exception ex) {
        errorMeter.mark();
        logger.warn("The result [{}] in the request {} could not be serialized and returned.", o.getResult(),
                o.getRequestId(), ex);
        final String errorMessage = String.format("Error during serialization: %s",
                ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
        final ResponseMessage error = ResponseMessage.build(o.getRequestId()).statusMessage(errorMessage)
                .code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION).create();
        if (useBinary) {
            objects.add(new BinaryWebSocketFrame(serializer.serializeResponseAsBinary(error, ctx.alloc())));
        } else {
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            objects.add(new TextWebSocketFrame(textSerializer.serializeResponseAsString(error)));
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.op.AbstractOpProcessor.java

License:Apache License

protected static Frame makeFrame(final ChannelHandlerContext ctx, final RequestMessage msg,
        final MessageSerializer serializer, final boolean useBinary, final List<Object> aggregate,
        final ResponseStatusCode code, final Map<String, Object> responseMetaData) throws Exception {
    try {//from w ww .j  a  va2  s  .co m
        if (useBinary) {
            return new Frame(serializer.serializeResponseAsBinary(ResponseMessage.build(msg).code(code)
                    .responseMetaData(responseMetaData).result(aggregate).create(), ctx.alloc()));
        } else {
            // the expectation is that the GremlinTextRequestDecoder will have placed a MessageTextSerializer
            // instance on the channel.
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            return new Frame(textSerializer.serializeResponseAsString(ResponseMessage.build(msg).code(code)
                    .responseMetaData(responseMetaData).result(aggregate).create()));
        }
    } catch (Exception ex) {
        logger.warn("The result [{}] in the request {} could not be serialized and returned.", aggregate,
                msg.getRequestId(), ex);
        final String errorMessage = String.format("Error during serialization: %s",
                ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
        final ResponseMessage error = ResponseMessage.build(msg.getRequestId()).statusMessage(errorMessage)
                .code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION).create();
        ctx.writeAndFlush(error);
        throw ex;
    }
}

From source file:org.asynchttpclient.netty.request.body.BodyChunkedInput.java

License:Open Source License

@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {

    if (endOfInput)
        return null;

    ByteBuf buffer = ctx.alloc().buffer(chunkSize);
    Body.BodyState state = body.transferTo(buffer);
    switch (state) {
    case STOP:/*from w  ww . j  a v a  2s  .c  o  m*/
        endOfInput = true;
        return buffer;
    case SUSPEND:
        // this will suspend the stream in ChunkedWriteHandler
        buffer.release();
        return null;
    case CONTINUE:
        return buffer;
    default:
        throw new IllegalStateException("Unknown state: " + state);
    }
}

From source file:org.beaconmc.network.socket.pipeline.PacketCompression.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects)
        throws Exception {

    ByteBuf prefixByteBuf = channelHandlerContext.alloc().buffer(5);
    PacketSerializer prefixPacketSerializer = new PacketSerializer(prefixByteBuf);
    ByteBuf contentByteBuf;//from  w  ww  .  j  a va 2s. com

    if (byteBuf.readableBytes() >= threshold) {

        int index = byteBuf.readerIndex();
        int length = byteBuf.readableBytes();

        byte[] source = new byte[length];
        byteBuf.readBytes(source);
        this.deflater.setInput(source);
        this.deflater.finish();

        byte[] compressed = new byte[length];
        int compressedLength = this.deflater.deflate(compressed);
        this.deflater.reset();

        if (compressedLength == 0) {
            throw new IllegalStateException("Failed to compress packet");
        } else if (compressedLength >= length) {
            prefixPacketSerializer.writeVarInt(0);
            byteBuf.readerIndex(index);
            byteBuf.retain();
            contentByteBuf = byteBuf;
        } else {
            prefixPacketSerializer.writeVarInt(length);
            contentByteBuf = Unpooled.wrappedBuffer(compressed, 0, compressedLength);
        }
    } else {
        prefixPacketSerializer.writeVarInt(0);
        byteBuf.retain();
        contentByteBuf = byteBuf;
    }
    objects.add(Unpooled.wrappedBuffer(prefixPacketSerializer.getByteBuf(), contentByteBuf));
}