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:io.gomint.proxprox.network.AbstractConnection.java

License:BSD License

/**
 * Handles compressed batch packets directly by decoding their payload.
 *
 * @param buffer The buffer containing the batch packet's data (except packet ID)
 * @return decompressed and decrypted data
 *//*from w  w  w.j  av a 2s  .c  om*/
byte[] handleBatchPacket(PacketBuffer buffer) {
    // Encrypted?
    byte[] input = new byte[buffer.getRemaining()];
    System.arraycopy(buffer.getBuffer(), buffer.getPosition(), input, 0, input.length);
    if (this.encryptionHandler != null) {
        input = this.encryptionHandler.isEncryptionFromServerEnabled()
                ? this.encryptionHandler.decryptInputFromServer(input)
                : this.encryptionHandler.decryptInputFromClient(input);
        if (input == null) {
            // Decryption error
            disconnect("Checksum of encrypted packet was wrong");
            return null;
        }
    }

    ByteBuf inBuf = PooledByteBufAllocator.DEFAULT.directBuffer(input.length);
    inBuf.writeBytes(input);

    ByteBuf outBuf = PooledByteBufAllocator.DEFAULT.directBuffer(8192); // We will write at least once so ensureWrite will realloc to 8192 so or so

    try {
        this.decompressor.process(inBuf, outBuf);
    } catch (DataFormatException e) {
        LOGGER.error("Failed to decompress batch packet", e);
        outBuf.release();
        return null;
    } finally {
        inBuf.release();
    }

    byte[] data = new byte[outBuf.readableBytes()];
    outBuf.readBytes(data);
    outBuf.release();
    return data;
}

From source file:io.gomint.proxprox.network.EncryptionHandler.java

License:BSD License

private byte[] calcHash(byte[] input, byte[] key, AtomicLong counter) {
    Hash digest = getSHA256();/*from  w  w  w. j a va 2  s .c  o m*/
    if (digest == null) {
        return new byte[8];
    }

    ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer(8 + input.length + key.length);
    buf.writeLongLE(counter.getAndIncrement());
    buf.writeBytes(input);
    buf.writeBytes(key);
    digest.update(buf);
    buf.release();
    return digest.digest();
}

From source file:io.gomint.proxprox.network.EncryptionHandler.java

License:BSD License

private byte[] hashSHA256(byte[]... message) {
    Hash digest = getSHA256();/*from   w  ww.ja  v a 2s .c om*/
    if (digest == null) {
        return null;
    }

    ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer();
    for (byte[] bytes : message) {
        buf.writeBytes(bytes);
    }

    digest.update(buf);
    buf.release();
    return digest.digest();
}

From source file:io.grpc.benchmarks.driver.LoadClient.java

License:Apache License

LoadClient(Control.ClientConfig config) throws Exception {
    log.log(Level.INFO, "Client Config \n" + config.toString());
    this.config = config;
    // Create the channels
    channels = new ManagedChannel[config.getClientChannels()];
    for (int i = 0; i < config.getClientChannels(); i++) {
        channels[i] = Utils.newClientChannel(Epoll.isAvailable() ? Transport.NETTY_EPOLL : Transport.NETTY_NIO,
                Utils.parseSocketAddress(config.getServerTargets(i % config.getServerTargetsCount())),
                config.hasSecurityParams(),
                config.hasSecurityParams() && config.getSecurityParams().getUseTestCa(),
                config.hasSecurityParams() ? config.getSecurityParams().getServerHostOverride() : null,
                Utils.DEFAULT_FLOW_CONTROL_WINDOW, false);
    }/*from  w  w  w.  j av  a  2  s . c  o  m*/

    // Create a stub per channel
    if (config.getClientType() == Control.ClientType.ASYNC_CLIENT) {
        asyncStubs = new BenchmarkServiceGrpc.BenchmarkServiceStub[channels.length];
        for (int i = 0; i < channels.length; i++) {
            asyncStubs[i] = BenchmarkServiceGrpc.newStub(channels[i]);
        }
    } else {
        blockingStubs = new BenchmarkServiceGrpc.BenchmarkServiceBlockingStub[channels.length];
        for (int i = 0; i < channels.length; i++) {
            blockingStubs[i] = BenchmarkServiceGrpc.newBlockingStub(channels[i]);
        }
    }

    // Determine no of threads
    if (config.getClientType() == Control.ClientType.SYNC_CLIENT) {
        threadCount = config.getOutstandingRpcsPerChannel() * config.getClientChannels();
    } else {
        threadCount = config.getAsyncClientThreads() == 0 ? Runtime.getRuntime().availableProcessors()
                : config.getAsyncClientThreads();
    }
    // Use a fixed sized pool of daemon threads.
    fixedThreadPool = Executors.newFixedThreadPool(threadCount,
            new DefaultThreadFactory("client-worker", true));

    // Create the load distribution
    switch (config.getLoadParams().getLoadCase()) {
    case CLOSED_LOOP:
        distribution = null;
        break;
    case LOAD_NOT_SET:
        distribution = null;
        break;
    case POISSON:
        // Mean of exp distribution per thread is <no threads> / <offered load per second>
        distribution = new ExponentialDistribution(
                threadCount / config.getLoadParams().getPoisson().getOfferedLoad());
        break;
    default:
        throw new IllegalArgumentException("Scenario not implemented");
    }

    // Create payloads
    switch (config.getPayloadConfig().getPayloadCase()) {
    case SIMPLE_PARAMS: {
        Payloads.SimpleProtoParams simpleParams = config.getPayloadConfig().getSimpleParams();
        simpleRequest = Utils.makeRequest(Messages.PayloadType.COMPRESSABLE, simpleParams.getReqSize(),
                simpleParams.getRespSize());
        break;
    }
    case BYTEBUF_PARAMS: {
        PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
        genericRequest = alloc.buffer(config.getPayloadConfig().getBytebufParams().getRespSize());
        if (genericRequest.capacity() > 0) {
            genericRequest.writerIndex(genericRequest.capacity() - 1);
        }
        break;
    }
    default: {
        // Not implemented yet
        throw new IllegalArgumentException("Scenario not implemented");
    }
    }

    List<OperatingSystemMXBean> beans = ManagementFactory.getPlatformMXBeans(OperatingSystemMXBean.class);
    if (!beans.isEmpty()) {
        osBean = beans.get(0);
    } else {
        osBean = null;
    }

    // Create the histogram recorder
    recorder = new Recorder((long) config.getHistogramParams().getMaxPossible(), 3);
}

From source file:io.grpc.benchmarks.driver.LoadServer.java

License:Apache License

LoadServer(Control.ServerConfig config) throws Exception {
    log.log(Level.INFO, "Server Config \n" + config.toString());
    port = config.getPort() == 0 ? Utils.pickUnusedPort() : config.getPort();
    ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
    int asyncThreads = config.getAsyncServerThreads() == 0 ? Runtime.getRuntime().availableProcessors()
            : config.getAsyncServerThreads();
    // The concepts of sync & async server are quite different in the C impl and the names
    // chosen for the enum are based on that implementation. We use 'sync' to mean
    // the direct executor case in Java even though the service implementations are always
    // fully async.
    switch (config.getServerType()) {
    case ASYNC_SERVER: {
        serverBuilder.executor(getExecutor(asyncThreads));
        break;/*from   w w  w. j  a  v  a2s .  c om*/
    }
    case SYNC_SERVER: {
        serverBuilder.directExecutor();
        break;
    }
    case ASYNC_GENERIC_SERVER: {
        serverBuilder.executor(getExecutor(asyncThreads));
        // Create buffers for the generic service
        PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
        genericResponse = alloc.buffer(config.getPayloadConfig().getBytebufParams().getRespSize());
        if (genericResponse.capacity() > 0) {
            genericResponse.writerIndex(genericResponse.capacity() - 1);
        }
        break;
    }
    default: {
        throw new IllegalArgumentException();
    }
    }
    if (config.hasSecurityParams()) {
        File cert = TestUtils.loadCert("server1.pem");
        File key = TestUtils.loadCert("server1.key");
        serverBuilder.useTransportSecurity(cert, key);
    }
    benchmarkService = new AsyncServer.BenchmarkServiceImpl();
    if (config.getServerType() == Control.ServerType.ASYNC_GENERIC_SERVER) {
        serverBuilder.addService(ServerServiceDefinition
                .builder(new ServiceDescriptor(BenchmarkServiceGrpc.SERVICE_NAME,
                        GENERIC_STREAMING_PING_PONG_METHOD))
                .addMethod(GENERIC_STREAMING_PING_PONG_METHOD, new GenericServiceCallHandler()).build());
    } else {
        serverBuilder.addService(benchmarkService);
    }
    server = serverBuilder.build();

    List<OperatingSystemMXBean> beans = ManagementFactory.getPlatformMXBeans(OperatingSystemMXBean.class);
    if (!beans.isEmpty()) {
        osBean = beans.get(0);
    } else {
        osBean = null;
    }
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void setChildOpts(ServerBootstrap boot) {
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    setChildUserOpt(boot, ChannelOption.TCP_NODELAY, tcpNoDelay);
    setChildUserOpt(boot, ChannelOption.SO_RCVBUF, soReceiveBufferSize);
    setChildUserOpt(boot, ChannelOption.SO_SNDBUF, soSendBuffer);
}

From source file:io.maelstorm.server.ServerInit.java

License:Open Source License

public void start(String configFile, RequestHandler handler) throws Exception {
    LOG.info("Starting.");
    AppendableCharSequenceAddon.configure();
    try {/* ww  w. j  a  v  a 2s .c o  m*/
        System.in.close(); // Release a FD we don't need.
    } catch (Exception e) {
        LOG.warn("Failed to close stdin", e);
    }
    Properties prop = getProperties(configFile);
    requestDistributor = handler;
    requestDistributor.setInitializer(this);
    String os = System.getProperty("os.name").toLowerCase(Locale.UK).trim();
    if (os.startsWith("linux")) {
        bossGroup = (null == bossGroup) ? new EpollEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new EpollEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    } else {
        bossGroup = (null == bossGroup) ? new NioEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new NioEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    }

    String[] servers = prop.getProperty("servers").split(",");
    for (String server : servers) {

        try {
            controller = new ServerBootstrap();
            controller.group(bossGroup, workerGroup);
            if (os.startsWith("linux")) {
                controller.channel(EpollServerSocketChannel.class);
                controller.option(EpollChannelOption.TCP_CORK, true);
            } else {
                controller.channel(NioServerSocketChannel.class);
            }
            controller.childHandler(new PipelineFactory(handler, getPipelineConfig(prop, server)));
            controller.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    getInt(prop, server, "connectTimeoutMillis"));
            controller.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1 * 1024);
            controller.option(ChannelOption.SO_KEEPALIVE, getBoolean(prop, server, "SOKeepalive"));
            controller.option(ChannelOption.SO_REUSEADDR, true);
            controller.option(ChannelOption.TCP_NODELAY, true);
            controller.option(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10);
            controller.childOption(ChannelOption.SO_KEEPALIVE, true);
            controller.childOption(ChannelOption.SO_REUSEADDR, true);
            controller.childOption(ChannelOption.TCP_NODELAY, true);
            controller.childOption(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.SO_RCVBUF, 6291456);

            final InetSocketAddress addr = new InetSocketAddress(getInt(prop, server, "port"));
            ChannelFuture future = controller.bind(addr).sync();
            if (future.isSuccess())
                LOG.info("Server Ready to serve on " + addr);
            else
                throw new Exception("Address already in use");
        } catch (Throwable t) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("Initialization failed", t);
        }
    }
}

From source file:io.mycat.netty.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();

    final ProtocolHandler handshakeHandler = newHandshakeHandler(userExecutor);
    final ProtocolHandler protocolHandler = newProtocolHandler(userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }// w  ww.  j ava  2 s.co  m

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ handshakeHandler,
                    protocolHandler);
        }
    });

    return b;
}

From source file:io.reactivesocket.tcp.rxnetty.TcpDuplexConnection.java

License:Apache License

@Override
public void addOutput(Publisher<Frame> o, Completable callback) {
    rx.Observable<ByteBuf> byteBufObservable = RxReactiveStreams.toObservable(o).map(frame -> {
        ByteBuffer byteBuffer = frame.getByteBuffer();
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer(byteBuffer.capacity());
        byteBuf.writeBytes(byteBuffer);/*from w w w  .  j  a va2 s  . co m*/

        return byteBuf;
    });

    connection.writeAndFlushOnEach(byteBufObservable).doOnCompleted(callback::success)
            .doOnError(callback::error).subscribe();
}

From source file:io.reactivex.netty.client.AbstractClientBuilder.java

License:Apache License

public B defaultChannelOptions() {
    return channelOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}