Example usage for io.netty.buffer UnpooledByteBufAllocator DEFAULT

List of usage examples for io.netty.buffer UnpooledByteBufAllocator DEFAULT

Introduction

In this page you can find the example usage for io.netty.buffer UnpooledByteBufAllocator DEFAULT.

Prototype

UnpooledByteBufAllocator DEFAULT

To view the source code for io.netty.buffer UnpooledByteBufAllocator DEFAULT.

Click Source Link

Document

Default instance which uses leak-detection for direct buffers.

Usage

From source file:org.ebayopensource.scc.cache.NettyResponseSerializerTest.java

License:Apache License

@Test
public void testSerialize() {
    NettyResponseSerializer serializer = new NettyResponseSerializer();

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK);
    CacheResponse cacheRes = serializer.serialize(response);
    assertNotNull(cacheRes);//from  ww w  . j av a2 s .  c om
    assertEquals(HttpVersion.HTTP_1_0.toString(), cacheRes.getProtocalVersion());
    assertEquals(HttpResponseStatus.OK.code(), cacheRes.getCode());
    assertEquals(0, cacheRes.getContent().length);
    assertTrue(cacheRes.getHeaders().get(0).getKey().equals("Content-Length"));
    assertTrue(cacheRes.getTrailingHeaders().isEmpty());

    ByteBuf content = new EmptyByteBuf(ByteBufAllocator.DEFAULT);
    response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, content);
    cacheRes = serializer.serialize(response);
    assertEquals(0, cacheRes.getContent().length);

    content = UnpooledByteBufAllocator.DEFAULT.buffer();
    content.writeBytes("Hello, World!".getBytes());
    response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, content);
    cacheRes = serializer.serialize(response);
    assertEquals("Hello, World!", new String(cacheRes.getContent()));

    HttpHeaders headers = response.headers();
    headers.add("header1", "value1");

    HttpHeaders trailingHeaders = response.trailingHeaders();
    trailingHeaders.add("tHeader2", "value2");

    cacheRes = serializer.serialize(response);
    Entry<String, String> header = cacheRes.getHeaders().get(0);
    assertEquals("header1", header.getKey());
    assertEquals("value1", header.getValue());

    Entry<String, String> tHeader = cacheRes.getTrailingHeaders().get(0);
    assertEquals("tHeader2", tHeader.getKey());
    assertEquals("value2", tHeader.getValue());
}

From source file:org.ebayopensource.scc.cache.RequestKeyGeneratorTest.java

License:Apache License

@Test
public void testURIMatchOnly() throws IOException {
    AppConfiguration appConfig = new AppConfiguration(new ConfigLoader(),
            "./src/test/resources/testuserconfig.json");
    appConfig.init();/*from  w  w w .j ava 2s  .c  o m*/
    RequestKeyGenerator keyGen = new RequestKeyGenerator(appConfig);

    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer();
    buffer.writeBytes("{\"fromDate\":1464251112185,\"toDate\":1464337512185}".getBytes());
    DefaultFullHttpRequest req1 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "http://test.ebay.com/v1/s1", buffer);

    String key1 = keyGen.generateKey(req1);

    buffer = UnpooledByteBufAllocator.DEFAULT.buffer();
    buffer.writeBytes("{\"fromDate\":1464251113750,\"toDate\":1464337513750}".getBytes());
    DefaultFullHttpRequest req2 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "http://test.ebay.com/v1/s1", buffer);

    String key2 = keyGen.generateKey(req2);
    assertEquals(key1, key2);

    HttpHeaders.setContentLength(req2, 758);
    key2 = keyGen.generateKey(req2);
    assertEquals(key1, key2);

    appConfig.put("uriMatchOnly", null);
    keyGen = new RequestKeyGenerator(appConfig);
    key1 = keyGen.generateKey(req1);
    key2 = keyGen.generateKey(req2);

    assertNotEquals(key1, key2);
}

From source file:org.elasticsearch.http.nio.PagedByteBuf.java

License:Apache License

private PagedByteBuf(byte[] array, Runnable releasable) {
    super(UnpooledByteBufAllocator.DEFAULT, array, array.length);
    this.releasable = releasable;
}

From source file:org.elasticsearch.http.nio.PagedByteBuf.java

License:Apache License

static ByteBuf byteBufFromPages(InboundChannelBuffer.Page[] pages) {
    int componentCount = pages.length;
    if (componentCount == 0) {
        return Unpooled.EMPTY_BUFFER;
    } else if (componentCount == 1) {
        return byteBufFromPage(pages[0]);
    } else {//  w ww  . j a  v  a2s  .  c  o  m
        int maxComponents = Math.max(16, componentCount);
        final List<ByteBuf> components = new ArrayList<>(componentCount);
        for (InboundChannelBuffer.Page page : pages) {
            components.add(byteBufFromPage(page));
        }
        return new CompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, false, maxComponents, components);
    }
}

From source file:org.hornetq.amqp.test.minimalserver.MinimalServer.java

License:Apache License

public synchronized void start(String host, int port, final boolean sasl) throws Exception {
    this.host = host;
    this.port = port;
    this.sasl = sasl;

    if (channelClazz != null) {
        // Already started
        return;/*from w w w  .jav  a  2  s .c om*/
    }

    int threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    channelClazz = NioServerSocketChannel.class;
    eventLoopGroup = new NioEventLoopGroup(threadsToUse, new SimpleServerThreadFactory("simple-server", true,
            Thread.currentThread().getContextClassLoader()));

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("amqp-handler", new ProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT);

    channelGroup = new DefaultChannelGroup("hornetq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("hornetq-acceptor-channels", GlobalEventExecutor.INSTANCE);
    startServerChannels();

}

From source file:org.hornetq.utils.ChannelBufferWrapperTest.java

License:Apache License

@Test
public void testUnwrap() {
    ByteBuf buff = UnpooledByteBufAllocator.DEFAULT.heapBuffer(100);

    ByteBuf wrapped = buff;//from  ww w.ja v  a2 s.  c om

    for (int i = 0; i < 10; i++) {
        wrapped = Unpooled.unreleasableBuffer(wrapped);
    }

    // If this starts to loop forever it means that Netty has changed
    // the semantic of Unwrap call and it's returning itself
    Assert.assertEquals(buff, ChannelBufferWrapper.unwrap(wrapped));

    // does it work with itself as well?
    Assert.assertEquals(buff, ChannelBufferWrapper.unwrap(buff));
}

From source file:org.neo4j.bolt.v1.transport.socket.ChunkedOutputTest.java

License:Open Source License

@Before
public void setup() {
    when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ch.writeAndFlush(any(), any(ChannelPromise.class))).thenAnswer(new Answer<Object>() {
        @Override/*from w  ww  .j a  v a2s  .com*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            ByteBuf byteBuf = (ByteBuf) invocation.getArguments()[0];
            writtenData.limit(writtenData.position() + byteBuf.readableBytes());
            byteBuf.readBytes(writtenData);
            return null;
        }
    });
    this.out = new ChunkedOutput(ch, 16);
}

From source file:org.neo4j.bolt.v1.transport.socket.Chunker.java

License:Open Source License

public static byte[] chunk(int maxChunkSize, byte[][] messages) throws IOException {
    final ByteBuffer outputBuffer = ByteBuffer.allocate(1024 * 8);

    Channel ch = mock(Channel.class);
    when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ch.writeAndFlush(any(), any(ChannelPromise.class))).then(new Answer<Object>() {
        @Override//  ww w  .j a  v a2  s.c o  m
        public Object answer(InvocationOnMock inv) throws Throwable {
            ByteBuf buf = (ByteBuf) inv.getArguments()[0];
            outputBuffer.limit(outputBuffer.position() + buf.readableBytes());
            buf.readBytes(outputBuffer);
            buf.release();
            return null;
        }
    });

    ChunkedOutput out = new ChunkedOutput(ch, maxChunkSize + 2 /* for chunk header */ );

    for (byte[] message : messages) {
        out.writeBytes(message, 0, message.length);
        out.onMessageComplete();
    }
    out.flush();
    out.close();

    byte[] bytes = new byte[outputBuffer.limit()];
    outputBuffer.position(0);
    outputBuffer.get(bytes);
    return bytes;
}

From source file:org.neo4j.bolt.v1.transport.socket.FragmentedMessageDeliveryTest.java

License:Open Source License

private void testPermutation(byte[] unfragmented, ByteBuf[] fragments) throws IOException {
    // Given/*from  w  w  w .j  av a  2  s .c  om*/
    // System.out.println( "Testing fragmentation:" + describeFragments( fragments ) );
    Session sess = mock(Session.class);

    Channel ch = mock(Channel.class);
    when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(ch);

    BoltProtocolV1 protocol = new BoltProtocolV1(sess, ch, NullLogService.getInstance());

    // When data arrives split up according to the current permutation
    for (ByteBuf fragment : fragments) {
        fragment.readerIndex(0).retain();
        protocol.handle(ctx, fragment);
    }

    // Then the session should've received the specified messages, and the protocol should be in a nice clean state
    try {
        verify(sess).run(eq("Mjlnir"), any(Map.class), any(), any(Session.Callback.class));
    } catch (AssertionError e) {
        throw new AssertionError("Failed to handle fragmented delivery.\n" + "Messages: "
                + Arrays.toString(messages) + "\n" + "Chunk size: " + chunkSize + "\n"
                + "Serialized data delivered in fragments: " + describeFragments(fragments) + "\n"
                + "Unfragmented data: " + HexPrinter.hex(unfragmented) + "\n", e);
    } finally {
        protocol.close(); // To avoid buffer leak errors
    }
}

From source file:org.neo4j.bolt.v1.transport.socket.SocketTransportHandlerTest.java

License:Open Source License

@Test
public void shouldCloseSessionOnChannelClose() throws Throwable {
    // Given//from  w ww  . j  a  v a  2 s . c  o  m
    Session session = mock(Session.class);
    Channel ch = mock(Channel.class);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(ch);

    when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);

    SocketTransportHandler handler = new SocketTransportHandler(protocolChooser(session),
            NullLogProvider.getInstance());

    // And Given a session has been established
    handler.channelRead(ctx, handshake());

    // When
    handler.channelInactive(ctx);

    // Then
    verify(session).close();
}