Example usage for io.netty.buffer PooledByteBufAllocator DEFAULT

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

Introduction

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

Prototype

PooledByteBufAllocator DEFAULT

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

Click Source Link

Usage

From source file:com.linecorp.armeria.internal.DefaultHttpRequestTest.java

License:Apache License

/**
 * The aggregation future must be completed even if the request being aggregated has been aborted.
 *//*from w ww . j av  a 2s  .  c om*/
@Test
public void abortedAggregation() {
    final Thread mainThread = Thread.currentThread();
    final DefaultHttpRequest req = new DefaultHttpRequest(HttpHeaders.of(HttpMethod.GET, "/foo"));
    final CompletableFuture<AggregatedHttpMessage> future;

    // Practically same execution, but we need to test the both case due to code duplication.
    if (executorSpecified) {
        if (withPooledObjects) {
            future = req.aggregateWithPooledObjects(CommonPools.workerGroup().next(),
                    PooledByteBufAllocator.DEFAULT);
        } else {
            future = req.aggregate(CommonPools.workerGroup().next());
        }
    } else {
        if (withPooledObjects) {
            future = req.aggregateWithPooledObjects(PooledByteBufAllocator.DEFAULT);
        } else {
            future = req.aggregate();
        }
    }

    final AtomicReference<Thread> callbackThread = new AtomicReference<>();

    assertThatThrownBy(() -> {
        final CompletableFuture<AggregatedHttpMessage> f = future
                .whenComplete((unused, cause) -> callbackThread.set(Thread.currentThread()));
        req.abort();
        f.join();
    }).hasCauseInstanceOf(AbortedStreamException.class);

    assertThat(callbackThread.get()).isNotSameAs(mainThread);
}

From source file:com.linecorp.armeria.internal.DefaultHttpResponseTest.java

License:Apache License

/**
 * The aggregation future must be completed even if the response being aggregated has been aborted.
 *///from   w  w  w .  j  a v a2  s. co m
@Test
public void abortedAggregation() {
    final Thread mainThread = Thread.currentThread();
    final HttpResponseWriter res = HttpResponse.streaming();
    final CompletableFuture<AggregatedHttpMessage> future;

    // Practically same execution, but we need to test the both case due to code duplication.
    if (executorSpecified) {
        if (withPooledObjects) {
            future = res.aggregateWithPooledObjects(CommonPools.workerGroup().next(),
                    PooledByteBufAllocator.DEFAULT);
        } else {
            future = res.aggregate(CommonPools.workerGroup().next());
        }
    } else {
        if (withPooledObjects) {
            future = res.aggregateWithPooledObjects(PooledByteBufAllocator.DEFAULT);
        } else {
            future = res.aggregate();
        }
    }

    final AtomicReference<Thread> callbackThread = new AtomicReference<>();

    assertThatThrownBy(() -> {
        final CompletableFuture<AggregatedHttpMessage> f = future
                .whenComplete((unused, cause) -> callbackThread.set(Thread.currentThread()));
        res.abort();
        f.join();
    }).hasCauseInstanceOf(AbortedStreamException.class);

    assertThat(callbackThread.get()).isNotSameAs(mainThread);
}

From source file:com.linecorp.armeria.internal.grpc.NettyWritableBufferAllocator.java

License:Apache License

@Override
public WritableBuffer allocate(int capacityHint) {
    capacityHint = Math.min(MAX_BUFFER, Math.max(MIN_BUFFER, capacityHint));
    return new NettyWritableBuffer(PooledByteBufAllocator.DEFAULT.buffer(capacityHint, capacityHint));
}

From source file:com.mastfrog.netty.http.client.HttpClient.java

License:Open Source License

@SuppressWarnings("unchecked")
private synchronized Bootstrap start(HostAndPort hostAndPort) {
    if (bootstrap == null) {
        bootstrap = new Bootstrap();
        bootstrap.group(group);/*from   w ww . j  a  va 2 s.c  om*/
        bootstrap.handler(new Initializer(hostAndPort, handler, null, false, maxChunkSize, maxInitialLineLength,
                maxHeadersSize, compress));
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        bootstrap.option(ChannelOption.SO_REUSEADDR, false);
        if (timeout != null) {
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) timeout.getMillis());
        }
        for (ChannelOptionSetting<?> setting : settings) {
            option(bootstrap, setting);
        }
        bootstrap.channelFactory(new NioChannelFactory());
    }
    return bootstrap;
}

From source file:com.mastfrog.netty.http.client.HttpClient.java

License:Open Source License

private ByteBufAllocator alloc() {
    for (ChannelOptionSetting<?> setting : this.settings) {
        if (setting.option().equals(ChannelOption.ALLOCATOR)) {
            return (ByteBufAllocator) setting.value();
        }//  www  . ja  va2  s. com
    }
    return PooledByteBufAllocator.DEFAULT;
}

From source file:com.mongodb.connection.netty.NettyBufferProvider.java

License:Apache License

public NettyBufferProvider() {
    allocator = PooledByteBufAllocator.DEFAULT;
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void writeAsync(final List<ByteBuf> buffers, final AsyncCompletionHandler<Void> handler) {
    CompositeByteBuf composite = PooledByteBufAllocator.DEFAULT.compositeBuffer();
    for (ByteBuf cur : buffers) {
        io.netty.buffer.ByteBuf byteBuf = ((NettyByteBuf) cur).asByteBuf();
        composite.addComponent(byteBuf.retain());
        composite.writerIndex(composite.writerIndex() + byteBuf.writerIndex());
    }//from  w  ww  .ja v  a 2s .com

    channel.writeAndFlush(composite).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handler.failed(future.cause());
            } else {
                handler.completed(null);
            }
        }
    });
}

From source file:com.mongodb.connection.netty.NettyStreamFactory.java

License:Apache License

/**
 * Construct a new instance of the factory with a default allocator and event loop group.
 *
 * @param settings the socket settings/*  w ww. j av  a 2 s . c o m*/
 * @param sslSettings the SSL settings
 */
public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSettings) {
    this(settings, sslSettings, new NioEventLoopGroup(), PooledByteBufAllocator.DEFAULT);
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*w  w  w .  j a va 2 s . c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroup, new NioEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .childOption(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
                    //
                    .childOption(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)

                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (NettySystemConfig.NettyPooledByteBufAllocatorEnable) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
        ;
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override/*from  w  w  w  .  j  a va  2  s.  c om*/
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}