Search in sources :

Example 91 with ByteBuf

use of io.netty.buffer.ByteBuf in project rest.li by linkedin.

the class TestRAPClientCodec method testResponseDecoder.

@Test(dataProvider = "responseData")
public void testResponseDecoder(int status, String entity, HttpHeaders headers, String[] cookies) {
    final EmbeddedChannel ch = new EmbeddedChannel(new RAPClientCodec());
    ByteBuf content = Unpooled.copiedBuffer(entity, CHARSET);
    FullHttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), content);
    nettyResponse.headers().set(headers);
    for (String cookie : cookies) {
        nettyResponse.headers().add(HttpHeaderNames.SET_COOKIE, cookie);
    }
    ch.writeInbound(nettyResponse);
    RestResponse response = (RestResponse) ch.readInbound();
    Assert.assertEquals(response.getStatus(), status);
    Assert.assertEquals(response.getEntity().asString(CHARSET), entity);
    assertList(response.getCookies(), nettyResponse.headers().getAll(HttpConstants.RESPONSE_COOKIE_HEADER_NAME));
    for (Map.Entry<String, String> header : nettyResponse.headers()) {
        if (!header.getKey().equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
            List<String> values = response.getHeaderValues(header.getKey());
            Assert.assertNotNull(values);
            Assert.assertTrue(values.contains(header.getValue()));
        }
    }
    // make sure the incoming ByteBuf is released
    Assert.assertEquals(content.refCnt(), 0);
    ch.finish();
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) RestResponse(com.linkedin.r2.message.rest.RestResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteString(com.linkedin.data.ByteString) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 92 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class Rfc5425Encoder method encode.

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
    if (byteBuf.isReadable()) {
        int length = byteBuf.readableBytes();
        String headerString = length + " ";
        ByteBuf header = ByteBufAllocator.DEFAULT.buffer(headerString.getBytes(Charset.forName("UTF8")).length);
        header.writeBytes(headerString.getBytes(Charset.forName("UTF8")));
        Unpooled.buffer();
        byteBuf.retain();
        out.add(Unpooled.wrappedBuffer(header, byteBuf));
    }
}
Also used : ByteBuf(io.netty.buffer.ByteBuf)

Example 93 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class Rfc5425FrameDecoder method decode.

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (currentFramelength == null) {
        // find index of the first space, it should be after the length field
        int index = indexOf(in, Unpooled.wrappedBuffer(new byte[] { ' ' }));
        // Read part until the first space, if we have found one
        StringBuffer lengthbuffer = new StringBuffer();
        if (index > -1) {
            ByteBuf byteBuf = in.readBytes(index);
            byte[] dest = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(dest);
            lengthbuffer.append(new String(dest));
        }
        int length;
        try {
            // add one because we have to take in account the space after
            // the length field
            length = Integer.parseInt(lengthbuffer.toString()) + 1;
        } catch (NumberFormatException e) {
            length = -1;
        }
        // retry next time
        if (length < 0) {
            in.resetReaderIndex();
            return;
        }
        currentFramelength = length;
    }
    // Buffer does not contain enough data yet, wait until it does
    if (in.readableBytes() < currentFramelength) {
        return;
    }
    // read the message
    int lengthToRead = currentFramelength;
    currentFramelength = null;
    out.add(in.readBytes(lengthToRead));
}
Also used : ByteBuf(io.netty.buffer.ByteBuf)

Example 94 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class NettyRfc5425LongMessageTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    context().getRegistry(JndiRegistry.class).bind("rfc5426FrameDecoder", new Rfc5425FrameDecoder());
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            context.setTracing(true);
            DataFormat syslogDataFormat = new SyslogDataFormat();
            // we setup a Syslog listener on a random port.
            from(uri).unmarshal(syslogDataFormat).process(new Processor() {

                @Override
                public void process(Exchange ex) {
                    assertTrue(ex.getIn().getBody() instanceof SyslogMessage);
                }
            }).to("mock:syslogReceiver").marshal(syslogDataFormat).to("mock:syslogReceiver2");
            // Here we need to turn the request body into ByteBuf
            from("direct:start").convertBodyTo(ByteBuf.class).to(uri);
        }
    };
}
Also used : JndiRegistry(org.apache.camel.impl.JndiRegistry) Exchange(org.apache.camel.Exchange) Rfc5425FrameDecoder(org.apache.camel.component.syslog.netty.Rfc5425FrameDecoder) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) DataFormat(org.apache.camel.spi.DataFormat) ByteBuf(io.netty.buffer.ByteBuf)

Example 95 with ByteBuf

use of io.netty.buffer.ByteBuf in project pulsar by yahoo.

the class PersistentMessageFinderTest method createMessageWrittenToLedger.

public static byte[] createMessageWrittenToLedger(String msg) throws Exception {
    PulsarApi.MessageMetadata.Builder messageMetadataBuilder = PulsarApi.MessageMetadata.newBuilder();
    messageMetadataBuilder.setPublishTime(System.currentTimeMillis());
    messageMetadataBuilder.setProducerName("createMessageWrittenToLedger");
    messageMetadataBuilder.setSequenceId(1);
    PulsarApi.MessageMetadata messageMetadata = messageMetadataBuilder.build();
    ByteBuf data = UnpooledByteBufAllocator.DEFAULT.heapBuffer().writeBytes(msg.getBytes());
    int msgMetadataSize = messageMetadata.getSerializedSize();
    int payloadSize = data.readableBytes();
    int totalSize = 4 + msgMetadataSize + payloadSize;
    ByteBuf headers = PooledByteBufAllocator.DEFAULT.heapBuffer(totalSize, totalSize);
    ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(headers);
    headers.writeInt(msgMetadataSize);
    messageMetadata.writeTo(outStream);
    ByteBuf headersAndPayload = DoubleByteBuf.get(headers, data);
    byte[] byteMessage = headersAndPayload.nioBuffer().array();
    headersAndPayload.release();
    return byteMessage;
}
Also used : PulsarApi(com.yahoo.pulsar.common.api.proto.PulsarApi) DoubleByteBuf(com.yahoo.pulsar.common.api.DoubleByteBuf) ByteBuf(io.netty.buffer.ByteBuf) ByteBufCodedOutputStream(com.yahoo.pulsar.common.util.protobuf.ByteBufCodedOutputStream)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)1557 Test (org.junit.Test)668 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)162 IOException (java.io.IOException)99 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)89 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)81 Test (org.testng.annotations.Test)68 InetSocketAddress (java.net.InetSocketAddress)60 Channel (io.netty.channel.Channel)57 ChannelFuture (io.netty.channel.ChannelFuture)56 ArrayList (java.util.ArrayList)55 Map (java.util.Map)45 ChannelPromise (io.netty.channel.ChannelPromise)41 AtomicReference (java.util.concurrent.atomic.AtomicReference)36 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)35 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 HashMap (java.util.HashMap)34 CountDownLatch (java.util.concurrent.CountDownLatch)34 RecyclableDuplicateByteBuf (io.netty.buffer.RecyclableDuplicateByteBuf)32 EventLoopGroup (io.netty.channel.EventLoopGroup)32