Example usage for io.netty.buffer PooledByteBufAllocator PooledByteBufAllocator

List of usage examples for io.netty.buffer PooledByteBufAllocator PooledByteBufAllocator

Introduction

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

Prototype

public PooledByteBufAllocator() 

Source Link

Usage

From source file:be.ordina.msdashboard.aggregators.index.IndexesAggregatorTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void shouldReturnThreeNodes() throws InterruptedException {
    when(discoveryClient.getServices()).thenReturn(Collections.singletonList("service"));
    ServiceInstance instance = Mockito.mock(ServiceInstance.class);
    when(discoveryClient.getInstances("service")).thenReturn(Collections.singletonList(instance));

    when(instance.getServiceId()).thenReturn("service");
    when(instance.getUri()).thenReturn(URI.create("http://localhost:8089/service"));

    HttpClientResponse<ByteBuf> response = Mockito.mock(HttpClientResponse.class);
    when(RxNetty.createHttpRequest(any(HttpClientRequest.class))).thenReturn(Observable.just(response));

    when(response.getStatus()).thenReturn(HttpResponseStatus.OK);
    ByteBuf byteBuf = (new PooledByteBufAllocator()).directBuffer();
    ByteBufUtil.writeUtf8(byteBuf, "source");
    when(response.getContent()).thenReturn(Observable.just(byteBuf));

    Node node = new NodeBuilder().withId("service").build();

    when(indexToNodeConverter.convert("service", "http://localhost:8089/service", "source"))
            .thenReturn(Observable.just(node));

    TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
    indexesAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
    //testSubscriber.assertNoErrors();

    List<Node> nodes = testSubscriber.getOnNextEvents();
    assertThat(nodes).hasSize(1);/*from  w w w. jav  a 2 s  .  co m*/

    assertThat(nodes.get(0).getId()).isEqualTo("service");
}

From source file:com.streamsets.pipeline.lib.udp.UDPConsumingServer.java

License:Apache License

@Override
protected Bootstrap bootstrap(boolean enableEpoll) {
    if (enableEpoll) {
        // Direct buffers required for Epoll
        enableDirectBuffers();/*from  www .j a  va 2 s . com*/
        EventLoopGroup group = new EpollEventLoopGroup(numThreads);
        groups.add(group);
        return new Bootstrap().group(group).channel(EpollDatagramChannel.class).handler(handler)
                .option(EpollChannelOption.SO_REUSEADDR, true).option(EpollChannelOption.SO_REUSEPORT, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    } else {
        disableDirectBuffers();
        EventLoopGroup group = new NioEventLoopGroup(numThreads);
        groups.add(group);
        return new Bootstrap().group(group).channel(NioDatagramChannel.class).handler(handler)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator()); // use on-heap buffers
    }
}

From source file:com.streamsets.pipeline.stage.origin.udp.UDPConsumingServer.java

License:Apache License

public void listen() throws Exception {
    group = new NioEventLoopGroup();
    for (SocketAddress address : addresses) {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).handler(new UDPConsumingServerHandler(udpConsumer))
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator()); // use on-heap buffers
        LOG.info("Starting server on address {}", address);
        ChannelFuture channelFuture = b.bind(address).sync();
        channelFutures.add(channelFuture);
    }//  ww  w  .j  a  v a 2s .co  m
}

From source file:com.weibo.api.motan.transport.netty4.http.NettyHttpRequestHandlerTest.java

License:Apache License

private FullHttpRequest buildHttpRequest(String requestPath) throws Exception {
    PooledByteBufAllocator allocator = new PooledByteBufAllocator();
    ByteBuf buf = allocator.buffer(0);//  w ww .  java2  s  .co m
    FullHttpRequest httpReqeust = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestPath,
            buf);
    return httpReqeust;
}

From source file:com.weibo.api.motan.transport.netty4.yar.YarMessageHandlerWarpperTest.java

License:Apache License

private FullHttpRequest buildHttpRequest(YarRequest yarRequest, String requestPath) throws Exception {
    PooledByteBufAllocator allocator = new PooledByteBufAllocator();
    ByteBuf buf = allocator.buffer(2048, 1024 * 1024);
    if (yarRequest != null) {
        buf.writeBytes(YarProtocol.toProtocolBytes(yarRequest));
    }/*from  w w w. j a  v a  2 s. c  om*/
    FullHttpRequest httpReqeust = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestPath,
            buf);
    return httpReqeust;
}

From source file:fixio.FixClient.java

License:Apache License

public ChannelFuture connect(SocketAddress serverAddress) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    bossEventLoopGroup = new NioEventLoopGroup();
    workerEventLoopGroup = new NioEventLoopGroup(8);
    b.group(bossEventLoopGroup).channel(NioSocketChannel.class).remoteAddress(serverAddress)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
            .handler(new FixInitiatorChannelInitializer<SocketChannel>(workerEventLoopGroup,
                    sessionSettingsProvider, messageSequenceProvider, getFixApplication()))
            .validate();//w  w w .  ja v  a 2 s  . c  o m

    channel = b.connect().sync().channel();
    LOGGER.info("FixClient is started and connected to {}", channel.remoteAddress());
    return channel.closeFuture();
}

From source file:fixio.FixServer.java

License:Apache License

public void start() throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(8);
    final ServerBootstrap bootstrap = new ServerBootstrap();
    final FixAcceptorChannelInitializer<SocketChannel> channelInitializer = new FixAcceptorChannelInitializer<>(
            workerGroup, authenticator, getFixApplication());

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
            .localAddress(new InetSocketAddress(port)).childHandler(channelInitializer).validate();

    ChannelFuture f = bootstrap.bind().sync();
    LOGGER.info("FixServer is started at {}", f.channel().localAddress());
    channel = f.channel();/*from   w w  w  .j av a  2s.c  o m*/
}

From source file:io.urmia.job.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {

    boolean autoRegister = ArgumentParseUtil.isAutoRegister(args);
    String zkURL = ArgumentParseUtil.getZooKeeperURL(args);

    log.info("starting with zk at: {}, auto register: {}", zkURL, autoRegister);

    ns = new ZkNamingServiceImpl(zkURL, AZ);

    Optional<ServiceInstance<NodeType>> meOpt = ns.whoAmI(NodeType.JDS, autoRegister);

    if (!meOpt.isPresent()) {
        System.err.println("unable to find my instance. use auto register or cli-admin to add my node");
        System.exit(1);/*w w w  .  j av a 2  s .co  m*/
        return;
    }

    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    EventLoopGroup bossGroup = new NioEventLoopGroup(/*1*/);

    try {
        me = meOpt.get();

        log.info("my service instance: {}", me);

        BoneCPConfig boneCPConfig = getBoneCPConfig(ns);

        ns.register(me);

        int port = me.getPort();

        CuratorFramework client = CuratorFrameworkFactory.newClient(zkURL,
                new ExponentialBackoffRetry(1000, 3));
        client.start();

        JdbcPool pool = new JdbcPool.BoneCPJdbcPool(boneCPConfig);

        MetadataRepository repository = new PsqlMetadataRepositoryImpl(pool);

        MetadataService mds = new DefaultMetadataServiceImpl(repository);

        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.AUTO_READ, true)
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
                .childHandler(new JobApiServerInitializer(client, mds));

        Channel ch = b.bind(port).sync().channel();
        log.info("Job API Server (JDS) at port: {}", port);

        ch.closeFuture().sync();
    } finally {
        ns.deregister(me);
        bossGroup.shutdownGracefully();
        //workerGroup.shutdownGracefully();
    }
}

From source file:org.ebayopensource.scc.filter.NettyRequestProxyFilterTest.java

License:Apache License

@Test
public void testFilterRequest() throws IOException {
    AppConfiguration appConfig = new AppConfiguration(new ConfigLoader(), null);
    appConfig.init();//from  w ww .  j a v a 2  s .c  om

    PolicyManager policyManager = mock(PolicyManager.class);
    NettyRequestProxyFilter filter = new NettyRequestProxyFilter(policyManager, appConfig);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class));
    assertNull(filter.filterRequest(mock(HttpRequest.class), ctx));

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "http://test.ebay.com/s/");
    when(policyManager.cacheIsNeededFor(any(CacheDecisionObject.class))).thenReturn(false);
    assertNull(filter.filterRequest(req, ctx));

    when(policyManager.cacheIsNeededFor(any(CacheDecisionObject.class))).thenReturn(true);
    CacheManager cm = mock(CacheManager.class);
    when(policyManager.getCacheManager()).thenReturn(cm);
    assertNull(filter.filterRequest(req, ctx));

    FullHttpResponse resp = mock(FullHttpResponse.class);
    HttpHeaders respHeaders = mock(HttpHeaders.class);
    when(resp.headers()).thenReturn(respHeaders);
    when(respHeaders.get(any(CharSequence.class))).thenReturn("100");
    when(cm.get(anyString())).thenReturn(resp);
    Channel channel = mock(Channel.class);
    SocketChannelConfig config = mock(SocketChannelConfig.class);
    when(channel.config()).thenReturn(config);
    when(ctx.channel()).thenReturn(channel);
    req.headers().add("h1", "v1");

    when(resp.content()).thenReturn(new EmptyByteBuf(new PooledByteBufAllocator()))
            .thenReturn(Unpooled.copiedBuffer("Hello".getBytes()));
    assertEquals(resp, filter.filterRequest(req, ctx));
    assertEquals(resp, filter.filterRequest(req, ctx));
}