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:HelloWorldHttp1Handler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (HttpHeaderUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//from   w w  w . j  a va  2  s. c  o  m
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, Values.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:alluxio.network.protocol.RPCMessageEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, RPCMessage in, List<Object> out) throws Exception {
    RPCRequest.Type type = in.getType();

    long bodyBytes = 0;
    DataBuffer payload = null;/*from   w w w. j  a  va 2s . co  m*/

    if (in.hasPayload()) {
        payload = in.getPayloadDataBuffer();
        bodyBytes = payload.getLength();
    }

    int lengthBytes = Longs.BYTES;
    int typeBytes = type.getEncodedLength();
    int messageBytes = in.getEncodedLength();

    int headerBytes = lengthBytes + typeBytes + messageBytes;
    long frameBytes = headerBytes + bodyBytes;

    // Write the header info into a buffer.
    // The format is: [frame length][message type][message][(optional) data]
    ByteBuf buffer = ctx.alloc().buffer();
    buffer.writeLong(frameBytes);
    type.encode(buffer);
    in.encode(buffer);

    // Output the header buffer.
    out.add(buffer);

    if (payload != null && bodyBytes > 0) {
        Object output = payload.getNettyOutput();
        Preconditions.checkArgument(output instanceof ByteBuf || output instanceof FileRegion,
                "The payload must be a ByteBuf or a FileRegion.");
        out.add(output);
    }

}

From source file:at.yawk.dbus.protocol.codec.BodyEncoder.java

@Override
protected void encode(ChannelHandlerContext ctx, DbusMessage msg, List<Object> out) throws Exception {
    MessageHeader header = msg.getHeader();
    // note: we still modify the header below
    out.add(header);/*from w  ww .  j  ava  2  s.c  o  m*/

    MessageBody body = msg.getBody();
    if (body != null && !body.getArguments().isEmpty()) {
        List<TypeDefinition> types = new ArrayList<>(body.getArguments().size());
        ByteBuf bodyBuffer = ctx.alloc().buffer().order(Local.OUTBOUND_ORDER);
        AlignableByteBuf aligned = AlignableByteBuf.fromAlignedBuffer(bodyBuffer, 8);
        for (DbusObject arg : body.getArguments()) {
            types.add(arg.getType());
            arg.serialize(aligned);
        }

        header.addHeader(HeaderField.SIGNATURE, SignatureObject.create(types));
        header.setMessageBodyLength(bodyBuffer.readableBytes());
        out.add(bodyBuffer);
        log.trace("Body: {}", body);
    }
    log.trace("Header: {}", header);
}

From source file:blazingcache.network.netty.DataMessageEncoder.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    Message m = (Message) msg;//  w w w.  ja va  2 s . c  o m
    ByteBuf encoded = ctx.alloc().buffer();
    DodoMessageUtils.encodeMessage(encoded, m);
    ctx.writeAndFlush(encoded, promise);
}

From source file:c5db.client.codec.WebsocketProtostuffEncoder.java

License:Apache License

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

    final LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput();
    Call.getSchema().writeTo(lcpo, call);
    final long size = lcpo.buffer.size();

    if (size < MAX_SIZE) {
        ByteBuf byteBuf = channelHandlerContext.alloc().buffer((int) size);
        lcpo.buffer.finish().stream().forEach(byteBuf::writeBytes);
        final BinaryWebSocketFrame frame = new BinaryWebSocketFrame(byteBuf);
        objects.add(frame);/*from w w  w. j a va 2 s  . c om*/
    } else {
        long remaining = size;
        boolean first = true;
        ByteBuf byteBuf = channelHandlerContext.alloc().buffer((int) size);
        lcpo.buffer.finish().stream().forEach(byteBuf::writeBytes);

        while (remaining > 0) {

            WebSocketFrame frame;
            if (remaining > MAX_SIZE) {
                final ByteBuf slice = byteBuf.copy((int) (size - remaining), (int) MAX_SIZE);
                if (first) {
                    frame = new BinaryWebSocketFrame(false, 0, slice);
                    first = false;
                } else {
                    frame = new ContinuationWebSocketFrame(false, 0, slice);
                }
                remaining -= MAX_SIZE;
            } else {
                frame = new ContinuationWebSocketFrame(true, 0,
                        byteBuf.copy((int) (size - remaining), (int) remaining));
                remaining = 0;
            }
            objects.add(frame);
        }
    }
}

From source file:c5db.codec.WebsocketProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Response response, List<Object> objects)
        throws IOException {
    final LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput();
    Response.getSchema().writeTo(lcpo, response);
    final long size = lcpo.buffer.size();

    ByteBuf byteBuf = channelHandlerContext.alloc().buffer((int) size);
    lcpo.buffer.finish().stream().forEach(byteBuf::writeBytes);

    if (size < MAX_SIZE) {
        final BinaryWebSocketFrame frame = new BinaryWebSocketFrame(byteBuf);
        objects.add(frame);/* w  ww.j  a  v a  2s .  co m*/
    } else {
        long remaining = size;
        boolean first = true;
        while (remaining > 0) {
            WebSocketFrame frame;
            if (remaining > MAX_SIZE) {
                final ByteBuf slice = byteBuf.copy((int) (size - remaining), (int) MAX_SIZE);
                if (first) {
                    frame = new BinaryWebSocketFrame(false, 0, slice);
                    first = false;
                } else {
                    frame = new ContinuationWebSocketFrame(false, 0, slice);
                }
                remaining -= MAX_SIZE;
            } else {
                frame = new ContinuationWebSocketFrame(true, 0,
                        byteBuf.copy((int) (size - remaining), (int) remaining));
                remaining = 0;
            }
            objects.add(frame);
        }
    }
}

From source file:client.DiscardClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    this.ctx = ctx;

    // Initialize the message.
    content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);

    // Send the initial messages.
    generateTraffic();/*w ww  .j  ava 2 s.c o  m*/
}

From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    AggregatedFullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;//from  w ww.  java2s .  co m
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        if (is100ContinueExpected(m)) {
            if (HttpHeaders.getContentLength(m, 0) > maxContentLength) {
                tooLongFrameFound = true;
                final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain());
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        }
                    }
                });
                if (closeOnExpectationFailed) {
                    future.addListener(ChannelFutureListener.CLOSE);
                }
                ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
                return;
            }
            ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header,
                    ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null);
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header,
                    Unpooled.compositeBuffer(maxCumulationBufferComponents), null);
        } else {
            throw new Error();
        }

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.setTrailingHeaders(trailer.trailingHeaders());
            } else {
                currentMessage.setTrailingHeaders(new DefaultHttpHeaders());
            }

            // Set the 'Content-Length' header. If one isn't already set.
            // This is important as HEAD responses will use a 'Content-Length' header which
            // does not match the actual body, but the number of bytes that would be
            // transmitted if a GET would have been used.
            //
            // See rfc2616 14.13 Content-Length
            if (!isContentLengthSet(currentMessage)) {
                currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(content.readableBytes()));
            }
            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    RecyclableArrayList out = RecyclableArrayList.newInstance();
    try {/*from  ww  w.  j  a v  a 2s  .  c  om*/
        if (msg instanceof ByteBuf) {
            ByteBuf data = (ByteBuf) msg;
            if (cumulation == null) {
                cumulation = data;
                try {
                    callDecode(ctx, cumulation, out);
                } finally {
                    if (cumulation != null && !cumulation.isReadable()) {
                        cumulation.release();
                        cumulation = null;
                    }
                }
            } else {
                try {
                    if (cumulation.writerIndex() > cumulation.maxCapacity() - data.readableBytes()) {
                        ByteBuf oldCumulation = cumulation;
                        cumulation = ctx.alloc().buffer(oldCumulation.readableBytes() + data.readableBytes());
                        cumulation.writeBytes(oldCumulation);
                        oldCumulation.release();
                    }
                    cumulation.writeBytes(data);
                    callDecode(ctx, cumulation, out);
                } finally {
                    if (cumulation != null) {
                        if (!cumulation.isReadable()) {
                            cumulation.release();
                            cumulation = null;
                        } else {
                            cumulation.discardSomeReadBytes();
                        }
                    }
                    data.release();
                }
            }
        } else {
            out.add(msg);
        }
    } catch (DecoderException e) {
        throw e;
    } catch (Throwable t) {
        throw new DecoderException(t);
    } finally {
        if (out.isEmpty()) {
            decodeWasNull = true;
        }

        List<Object> results = new ArrayList<Object>();
        for (Object result : out) {
            results.add(result);
        }
        ctx.fireChannelRead(results);

        out.recycle();
    }
}

From source file:com.addthis.hydra.query.web.AbstractBufferingHttpBundleEncoder.java

License:Apache License

protected void flushStringBuilder(ChannelHandlerContext ctx) {
    if (sendBuffer.length() > 0) {
        ByteBuf msg = encodeString(ctx.alloc(), sendBuffer);
        sendBuffer.setLength(0);/*  w  ww.  ja va  2 s  .  c o  m*/
        ctx.writeAndFlush(new DefaultHttpContent(msg), ctx.voidPromise());
    }
}