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:uk.co.thinkofdeath.prismarine.network.NetworkManager.java

License:Apache License

/**
 * Start listening on the specified address & port. The initial handler for
 * each connection will be created from the supplier
 *
 * @param address/*  ww w. ja  v a  2s  .  c o m*/
 *         the address of the server
 * @param port
 *         the port of the server
 * @param initialHandler
 *         the supplier which creates the initial packet handler
 */
public void listen(String address, int port, Supplier<PacketHandler> initialHandler) {
    // Listening == Server
    incomingPacketType = ProtocolDirection.SERVERBOUND;
    if (isOnlineMode()) {
        // Encryption is only enabled in online mode
        logger.info("Generating encryption keys");
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(1024);
            networkKeyPair = generator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            logger.info("Failed to generate encryption keys");
            throw new RuntimeException(e);
        }
    }

    logger.log(Level.INFO, "Starting on {0}:{1,number,#}", new Object[] { address, port });

    final EventLoopGroup group = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(group).channel(NioServerSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ConnectionInitializer(this, initialHandler))
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    channel = bootstrap.bind(address, port).channel();
    channel.closeFuture().addListener(future -> group.shutdownGracefully());

}

From source file:uk.co.thinkofdeath.thinkcraft.bukkit.web.ServerChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast("timeout", new ReadTimeoutHandler(15));
    pipeline.addLast("codec-http", new HttpServerCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("handler", new HTTPHandler(plugin));
    pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/server"));
    pipeline.addLast("packet-decoder", new PacketDecoder());
    pipeline.addLast("packet-encoder", new PacketEncoder());
    pipeline.addLast("packet-handler", new ClientHandler(socketChannel, plugin));

    socketChannel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    plugin.getWebHandler().getChannelGroup().add(socketChannel);
}

From source file:xyz.kvantum.server.implementation.ResponseTask.java

License:Apache License

@SuppressWarnings("ALL")
private void sendResponse(final ChannelHandlerContext context) {
    final Timer.Context timer = KvantumServerHandler.TIMER_SEND_RESPONSE.time();

    ///*ww  w  .  j  a va2s .co  m*/
    // Determine whether or not the response should be compressed
    //
    workerContext.determineGzipStatus();

    //
    // Get the generated body
    //
    ResponseBody body = workerContext.getBody();

    // Make sure that the generated response is valid (not null)
    Assert.notNull(body);
    Assert.notNull(body.getHeader());

    // Retrieve an Md5Handler from the handler pool
    // final Md5Handler md5Handler = SimpleServer.md5HandlerPool.getNullable();
    // Generate the md5 checksum
    // TODO: Re-enable this final String checksum = md5Handler.generateChecksum( bytes );
    // Update the headers to include the md5 checksum
    // body.getHeader().set( Header.HEADER_CONTENT_MD5, checksum );
    // body.getHeader().set( Header.HEADER_ETAG, checksum );
    // Return the md5 handler to the pool
    // SimpleServer.md5HandlerPool.add( md5Handler );

    //
    // Add a Last-Modified if it isn't already present in the response
    //
    if (!body.getHeader().get(Header.HEADER_LAST_MODIFIED).isPresent()) {
        body.getHeader().set(Header.HEADER_LAST_MODIFIED, TimeUtil.getHTTPTimeStamp());
    }

    //
    // Output debug messages
    //
    if (CoreConfig.debug) {
        DebugTree.builder().name("Response Information")
                .entry("Address", workerContext.getSocketContext().getAddress())
                .entry("Headers", body.getHeader().getHeaders()).build().collect().forEach(Logger::debug);
    }

    //
    // Get the respone stream
    //
    final KvantumOutputStream responseStream = workerContext.getResponseStream(); // body.getResponseStream();
    final boolean hasKnownLength = responseStream instanceof KnownLengthStream;

    //
    // Fetch the GZIP handler, if applicable
    //
    final GzipHandler gzipHandler;
    if (workerContext.isGzip()) {
        gzipHandler = SimpleServer.gzipHandlerPool.getNullable();
    } else {
        gzipHandler = null;
    }

    boolean shouldWriteBody;
    if (workerContext.getRequest().getQuery().getMethod().hasBody()) {
        shouldWriteBody = true;
    } else {
        shouldWriteBody = false;
        body.getHeader().set(Header.HEADER_CONTENT_LENGTH, "0");
    }

    //
    // Send either the transfer encoding or content length, important for keep-alive
    //
    if (shouldWriteBody && hasKnownLength) {
        //
        // If the length is known, we compress before writing
        //
        if (workerContext.isGzip()) {
            byte[] bytes = ((KnownLengthStream) responseStream).getAll();
            try {
                bytes = gzipHandler.compress(bytes);
            } catch (final IOException e) {
                new KvantumException("( GZIP ) Failed to compress the bytes").printStackTrace();
            }
            ((KnownLengthStream) responseStream).replaceBytes(bytes);
        }
        body.getHeader().set(Header.HEADER_CONTENT_LENGTH,
                AsciiString.of(((KnownLengthStream) responseStream).getLength()));
    } else {
        body.getHeader().set(Header.HEADER_TRANSFER_ENCODING, "chunked");
    }

    //
    // Determine whether to keep the connection alive
    //
    final boolean keepAlive;
    if (workerContext.getRequest().getHeaders().getOrDefault(KvantumServerHandler.CONNECTION, CLOSE)
            .equalsIgnoreCase(KEEP_ALIVE)
            && !body.getHeader().get(Header.HEADER_CONNECTION).orElse(KEEP_ALIVE).equals(CLOSE)) {
        if (CoreConfig.debug) {
            Logger.debug("Request " + workerContext.getRequest() + " requested keep-alive...");
        }
        keepAlive = true;
        //
        // Apply "connection: keep-alive" and "content-length: n" headers to
        // make sure that the client keeps the connection open
        //
        body.getHeader().set(Header.HEADER_CONNECTION, KEEP_ALIVE);
    } else {
        keepAlive = false;
        body.getHeader().set(Header.HEADER_CONNECTION, CLOSE);
    }

    //
    // Alocate a byte buffer
    //
    final Timer.Context timerWriteToClient = KvantumServerHandler.TIMER_WRITE_TO_CLIENT.time();

    final ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(Buffer.out);

    //
    // Write the header
    //
    buf.writeBytes(body.getHeader().getFormat().getValue());
    buf.writeBytes(KvantumServerHandler.SPACE);
    buf.writeBytes(body.getHeader().getStatus().getValue());
    buf.writeBytes(KvantumServerHandler.NEW_LINE);
    for (final Map.Entry<HeaderOption, AsciiString> entry : body.getHeader().getHeaders().entries()) {
        buf.writeBytes(entry.getKey().getBytes());
        buf.writeBytes(KvantumServerHandler.COLON_SPACE);
        buf.writeBytes(entry.getValue().getValue());
        buf.writeBytes(KvantumServerHandler.NEW_LINE);
    }
    // Print one empty line to indicate that the header sending is finished, this is important as the content
    // would otherwise be classed as headers, which really isn't optimal <3
    buf.writeBytes(KvantumServerHandler.NEW_LINE);

    //
    // Write the header to the client
    //
    context.write(buf);

    long actualLength = 0L;

    if (shouldWriteBody) {
        if (CoreConfig.debug) {
            Logger.debug("Using direct write from memory: {}", hasKnownLength);
        }

        //
        // Write the response
        //
        byte[] buffer = ThreadCache.CHUNK_BUFFER.get();
        while (!responseStream.isFinished()) {
            //
            // Read as much data as possible from the respone stream
            //
            int read = responseStream.read(buffer);
            if (read != -1) {
                //
                // If the length is known, write data directly
                //
                if (hasKnownLength) {
                    context.write(Unpooled.wrappedBuffer(buffer, 0, read));
                    context.flush().newSucceededFuture().awaitUninterruptibly();
                    actualLength += read;
                } else {
                    //
                    // If the length isn't known, we first compress (if applicable) and then write using
                    // the chunked transfer encoding format
                    //
                    final ByteBuf result;

                    if (workerContext.isGzip()) {
                        try {
                            result = gzipHandler.compress(buffer, read);
                            actualLength += result.readableBytes();
                        } catch (final IOException e) {
                            new KvantumException("( GZIP ) Failed to compress the bytes").printStackTrace();
                            continue;
                        }
                    } else {
                        result = Unpooled.wrappedBuffer(buffer, 0, read);
                    }

                    actualLength += read;

                    context.write(AsciiString.of(Integer.toHexString(read)).getValue());
                    context.write(KvantumServerHandler.CRLF);
                    context.write(result);
                    context.write(KvantumServerHandler.CRLF);
                    //
                    // When using this mode we need to make sure that everything is written, so the
                    // client doesn't time out
                    //
                    context.flush().newSucceededFuture().awaitUninterruptibly();
                }
            }
        }

        //
        // If we're using the chunked encoding format
        // write the end chunk
        //
        if (!hasKnownLength) {
            context.write(KvantumServerHandler.END_CHUNK);
        }
    } /* shouldWriteToClient */ else if (CoreConfig.debug) {
        Logger.debug("Skipping body, because method {} does not require body",
                workerContext.getRequest().getQuery().getMethod());
    }

    timerWriteToClient.stop();

    //
    // Return the GZIP handler to the pool
    //
    if (gzipHandler != null) {
        SimpleServer.gzipHandlerPool.add(gzipHandler);
    }

    //
    // Invalidate request to make sure that it isn't handled anywhere else, again (wouldn't work)
    //
    workerContext.getRequest().setValid(false);

    //
    // Intialize a finalized response builder (used for logging)
    //
    final FinalizedResponse.FinalizedResponseBuilder finalizedResponse = FinalizedResponse.builder();

    //
    // Safety measure taken to make sure that IPs are not logged
    // in production mode. This is is to ensure GDPR compliance
    //
    if (CoreConfig.hideIps) {
        finalizedResponse.address(HIDDEN_IP);
    } else {
        finalizedResponse.address(this.workerContext.getSocketContext().getIP());
    }

    finalizedResponse.authorization(this.workerContext.getRequest().getAuthorization().orElse(null))
            .length((int) actualLength).status(body.getHeader().getStatus().toString())
            .query(this.workerContext.getRequest().getQuery()).timeFinished(System.currentTimeMillis()).build();

    ServerImplementation.getImplementation().getEventBus().throwEvent(finalizedResponse.build(), true);

    //
    // Make sure everything is written and either close the connection
    // or the channel (depending on whether keep-alive is used or not)
    //
    final ChannelFuture future = context.flush().newSucceededFuture();
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }

    timer.stop();
}

From source file:z.offheap.buffer.BufferTest3.java

License:Open Source License

@Test
public void sanitycheck() {
    System.out.println("start to sanity check...");

    ByteBuffer buffer = Buffer.create(5 * 8);

    ByteBuf nettyBuf = PooledByteBufAllocator.DEFAULT.directBuffer(5 * 8);

    buffer.clear().write((byte) 1).skipWriteTo(4).networkOrder().writeShortN((short) 2).writeIntN(12345)
            .write((byte) 123).writeCharN('[').writeFloatN(3.14159f).writeDoubleN(1.9999d).writeLongN(-2L)
            .write((byte) -1).writeCharN(']').writeIntN(Integer.MIN_VALUE);
    //4+2+4+1+2+4+8+8+1+2
    //8+8+8+8+4 -> 5*Long

    nettyBuf.clear().writeByte(1).writeByte(0).writeByte(0).writeByte(0).writeShort(2).writeInt(12345)
            .writeByte(123).writeChar('[').writeFloat(3.14159f).writeDouble(1.9999d).writeLong(-2L)
            .writeByte(-1).writeChar(']').writeInt(Integer.MIN_VALUE);

    long r1 = buffer.networkOrder().readLongN();
    long r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));//from w w w .j a  v  a 2 s.co  m

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    buffer.close();
}

From source file:z.offheap.buffer.contrast.ContrastTestNettyByteBuf.java

License:Open Source License

@Test
public void testNettyByteBuf() throws Exception {
    long s, t, sum = 0;

    ByteBuf bn = PooledByteBufAllocator.DEFAULT.directBuffer(16);

    //warm-up//from www .j av a  2 s . co  m
    for (int i = 0; i < WARMUP_COUNT; i++) {
        doWithNettyByteBuf(bn, i);
    }

    //================================netty contrast
    System.gc();
    Thread.sleep(3000L);

    s = System.nanoTime();
    for (int i = 0; i < COUNT; i++) {
        sum += doWithNettyByteBuf(bn, i);
    }
    t = System.nanoTime() - s;
    System.out.printf("Netty ByteBuf: time cost of %,d times OP in %,d nanoseconds with sum %d\n", COUNT, t,
            sum);
}

From source file:z.offheap.contrast.netty.NettyBufferTest.java

License:Open Source License

public static void main(String[] args) {
    // A new dynamic buffer is created.  Internally, the actual buffer is created
    // lazily to avoid potentially wasted memory space.
    ByteBuf b = PooledByteBufAllocator.DEFAULT.directBuffer();

    // When the first write attempt is made, the internal buffer is created with
    // the specified initial capacity (4).
    long s = System.nanoTime();
    for (int i = 0; i < 256; i++) {
        b.writeByte(i);/*  w ww . jav a  2s .  co  m*/
    }
    long duration = System.nanoTime() - s;
    System.out.println("initial 256:   " + duration + " nanoseconds!");

    //
    s = System.nanoTime();
    b.writeByte(1);
    duration = System.nanoTime() - s;
    System.out.println("write to 257:  " + duration + " nanoseconds!");

    //
    for (int i = 0; i < 255; i++) {
        b.writeByte(i);
    }

    s = System.nanoTime();
    b.writeByte(1);
    duration = System.nanoTime() - s;
    System.out.println("write to 513:  " + duration + " nanoseconds!");
    //
    for (int i = 0; i < 511; i++) {
        b.writeByte(i);
    }

    s = System.nanoTime();
    b.writeByte(1);
    duration = System.nanoTime() - s;

    System.out.println("write to 1025: " + duration + " nanoseconds!");

    //
    int total = 256 * 1024;
    ByteBuf b2 = PooledByteBufAllocator.DEFAULT.directBuffer();
    s = System.nanoTime();
    for (int i = 0; i < total; i++) {
        b2.writeByte(i);
    }
    duration = System.nanoTime() - s;

    System.out.println("write 256KB data into pool direct buffer dynamically: "
            + TimeUnit.NANOSECONDS.toMillis(duration) + " millis!");

    total = 256 * 1024;
    ByteBuf b3 = Unpooled.buffer();
    s = System.nanoTime();
    for (int i = 0; i < total; i++) {
        b3.writeByte(i);
    }
    duration = System.nanoTime() - s;

    //the single shot performance is unstable for unpooled
    System.out.println("write 256KB data into unpooled buffer dynamically: "
            + TimeUnit.NANOSECONDS.toMillis(duration) + " millis!");
}