io.netty.buffer.PooledByteBufAllocator Java Examples

The following examples show how to use io.netty.buffer.PooledByteBufAllocator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BedrockSession.java    From Protocol with Apache License 2.0 6 votes vote down vote up
private byte[] generateTrailer(ByteBuf buf) {
    VoxelwindHash hash = hashLocal.get();
    ByteBuf counterBuf = null;
    ByteBuf keyBuf = null;
    try {
        counterBuf = PooledByteBufAllocator.DEFAULT.directBuffer(8);
        keyBuf = PooledByteBufAllocator.DEFAULT.directBuffer(agreedKey.getEncoded().length);
        counterBuf.writeLongLE(this.sentEncryptedPacketCount.getAndIncrement());
        keyBuf.writeBytes(this.agreedKey.getEncoded());

        hash.update(counterBuf);
        hash.update(buf);
        hash.update(keyBuf);
        byte[] digested = hash.digest();
        return Arrays.copyOf(digested, 8);
    } finally {
        if (counterBuf != null) {
            counterBuf.release();
        }
        if (keyBuf != null) {
            keyBuf.release();
        }
    }
}
 
Example #2
Source File: PduCodec.java    From herddb with Apache License 2.0 6 votes vote down vote up
public static ByteBuf write(long messageId, String tableSpace, List<KeyValue> records) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
            .directBuffer(
                    VERSION_SIZE
                            + FLAGS_SIZE
                            + TYPE_SIZE
                            + MSGID_SIZE
                            + tableSpace.length()
                            + records.size() * 512);
    byteBuf.writeByte(VERSION_3);
    byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
    byteBuf.writeByte(Pdu.TYPE_PUSH_TXLOGCHUNK);
    byteBuf.writeLong(messageId);
    ByteBufUtils.writeString(byteBuf, tableSpace);

    byteBuf.writeInt(records.size());
    for (KeyValue kv : records) {
        ByteBufUtils.writeArray(byteBuf, kv.key);
        ByteBufUtils.writeArray(byteBuf, kv.value);
    }

    return byteBuf;

}
 
Example #3
Source File: Fixtures.java    From tchannel-java with MIT License 6 votes vote down vote up
public static CallResponseFrame callResponse(long id,
                                             boolean moreFragments,
                                             Map<String, String> headers,
                                             ByteBuf payload) {
    CallResponseFrame callResponseFrame = new CallResponseFrame(
            id,
            moreFragments ? (byte) 1 : (byte) 0,
            ResponseCode.OK,
            new Trace(0, 0, 0, (byte) 0x00),
            headers,
            ChecksumType.NoChecksum,
            0,
            null
    );

    ByteBuf byteBuf = callResponseFrame.encodeHeader(PooledByteBufAllocator.DEFAULT);
    callResponseFrame.setPayload(Unpooled.wrappedBuffer(byteBuf, payload));

    checkState(byteBuf.refCnt() == 1);
    return callResponseFrame;
}
 
Example #4
Source File: TransportServerSupport.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
protected ServerBootstrap newBootstrap(ChannelHandler channelHandler, EventLoopGroup acceptEventGroup, EventLoopGroup ioEventGroup) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .group(acceptEventGroup, ioEventGroup)
            .childHandler(channelHandler)
            .option(ChannelOption.SO_REUSEADDR, serverConfig.isReuseAddress())
            .option(ChannelOption.SO_RCVBUF, serverConfig.getSocketBufferSize())
            .option(ChannelOption.SO_BACKLOG, serverConfig.getBacklog())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_SNDBUF, serverConfig.getSocketBufferSize())
            .childOption(ChannelOption.TCP_NODELAY, serverConfig.isTcpNoDelay())
            .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.isKeepAlive())
            .childOption(ChannelOption.SO_LINGER, serverConfig.getSoLinger())
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    return serverBootstrap;
}
 
Example #5
Source File: UDPServerSocket.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        if (Epoll.isAvailable()) {
            bootstrap = new Bootstrap()
                    .channel(EpollDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this)
                    .group(new EpollEventLoopGroup());
            this.logger.info("Epoll is available. EpollEventLoop will be used.");
        } else {
            bootstrap = new Bootstrap()
                    .group(new NioEventLoopGroup())
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this);
            this.logger.info("Epoll is unavailable. Reverting to NioEventLoop.");
        }
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example #6
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJceksStoreWithExplicitEnabledProtocolsOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    // Try and disable all but the one we really want but for now expect that this one plus SSLv2Hello
    // is going to come back until the netty code can successfully disable them all.
    TransportOptions options = createJceksSslOptions(ENABLED_PROTOCOLS);

    SslContext context = TransportSupport.createOpenSslContext(options);
    assertNotNull(context);

    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);
    assertNotNull(engine);

    assertArrayEquals("Enabled protocols not as expected", ENABLED_OPENSSL_PROTOCOLS, engine.getEnabledProtocols());
}
 
Example #7
Source File: NettyMultipartRequestTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link NettyMultipartRequest} with the given {@code headers} and {@code parts}.
 * @param headers the {@link HttpHeaders} that need to be added to the request.
 * @param parts the files that will form the parts of the request.
 * @return a {@link NettyMultipartRequest} containing all the {@code headers} and {@code parts}.
 * @throws Exception
 */
private NettyMultipartRequest createRequest(HttpHeaders headers, InMemoryFile[] parts) throws Exception {
  HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  HttpPostRequestEncoder encoder = createEncoder(httpRequest, parts);
  NettyMultipartRequest request =
      new NettyMultipartRequest(encoder.finalizeRequest(), new MockChannel(), NETTY_METRICS, Collections.emptySet(),
          Long.MAX_VALUE);
  assertTrue("Request channel is not open", request.isOpen());
  while (!encoder.isEndOfInput()) {
    // Sending null for ctx because the encoder is OK with that.
    request.addContent(encoder.readChunk(PooledByteBufAllocator.DEFAULT));
  }
  return request;
}
 
Example #8
Source File: RedisEncoderBenchmark.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
    byte[] bytes = new byte[256];
    content = Unpooled.buffer(bytes.length);
    content.writeBytes(bytes);
    ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());

    List<RedisMessage> rList = new ArrayList<RedisMessage>(arraySize);
    for (int i = 0; i < arraySize; ++i) {
        rList.add(new FullBulkStringRedisMessage(testContent));
    }
    redisArray = new ArrayRedisMessage(rList);
    encoder = new RedisEncoder();
    context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
            UnpooledByteBufAllocator.DEFAULT, encoder) {
        @Override
        protected void handleException(Throwable t) {
            handleUnexpectedException(t);
        }
    };
}
 
Example #9
Source File: AbstractSslEngineThroughputBenchmark.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Setup(Level.Iteration)
public final void setup() throws Exception {
    ByteBufAllocator allocator = new PooledByteBufAllocator(true);
    initEngines(allocator);
    initHandshakeBuffers();

    wrapDstBuffer = allocateBuffer(clientEngine.getSession().getPacketBufferSize() << 2);
    wrapSrcBuffer = allocateBuffer(messageSize);

    byte[] bytes = new byte[messageSize];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);
    wrapSrcBuffer.put(bytes);
    wrapSrcBuffer.flip();

    // Complete the initial TLS handshake.
    if (!doHandshake()) {
        throw new IllegalStateException();
    }
    doSetup();
}
 
Example #10
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJksStoreWithExplicitDisabledCiphersOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    // Discover the default enabled ciphers
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createOpenSSLEngineDirectly(options);
    String[] ciphers = directEngine.getEnabledCipherSuites();
    assertTrue("There were no initial ciphers to choose from!", ciphers.length > 0);

    // Pull out one to disable specifically
    String[] disabledCipher = new String[] { ciphers[ciphers.length - 1] };
    String[] trimmedCiphers = Arrays.copyOf(ciphers, ciphers.length - 1);
    options.setDisabledCipherSuites(disabledCipher);
    SslContext context = TransportSupport.createOpenSslContext(options);
    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);

    // verify the option took effect
    assertNotNull(engine);
    assertArrayEquals("Enabled ciphers not as expected", trimmedCiphers, engine.getEnabledCipherSuites());
}
 
Example #11
Source File: AbstractRedisProxyServerTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public ChannelFuture connect() throws Exception {

        startServer();
        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                });
        return b.connect("127.0.0.1", config.frontendTcpPort());
    }
 
Example #12
Source File: PduCodec.java    From herddb with Apache License 2.0 6 votes vote down vote up
public static ByteBuf write(long messageId, byte[] token) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
            .directBuffer(
                    VERSION_SIZE
                            + FLAGS_SIZE
                            + TYPE_SIZE
                            + MSGID_SIZE
                            + 1 + (token != null ? token.length : 0));
    byteBuf.writeByte(VERSION_3);
    byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
    byteBuf.writeByte(Pdu.TYPE_SASL_TOKEN_MESSAGE_TOKEN);
    byteBuf.writeLong(messageId);
    if (token == null) {
        byteBuf.writeByte(NULLABLE_FIELD_ABSENT);
    } else {
        byteBuf.writeByte(NULLABLE_FIELD_PRESENT);
        ByteBufUtils.writeArray(byteBuf, token);
    }
    return byteBuf;
}
 
Example #13
Source File: HelloWebServer.java    From crow-benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException {
try {
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));
    b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
    b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
    b.childOption(ChannelOption.SO_REUSEADDR, true);
    b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

    Channel ch = b.bind(port).sync().channel();
    ch.closeFuture().sync();
} finally {
    loupGroup.shutdownGracefully().sync();
}
   }
 
Example #14
Source File: BGPDispatcherImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer<?> initializer) {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    if (Epoll.isAvailable()) {
        serverBootstrap.channel(EpollServerSocketChannel.class);
        serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        serverBootstrap.channel(NioServerSocketChannel.class);
    }
    final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
    serverBootstrap.childHandler(serverChannelHandler);

    serverBootstrap.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WATER_MARK);

    // Make sure we are doing round-robin processing
    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, RECV_ALLOCATOR);

    if (serverBootstrap.config().group() == null) {
        serverBootstrap.group(this.bossGroup, this.workerGroup);
    }
    return serverBootstrap;
}
 
Example #15
Source File: LZ4CompressionCodec.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuf compress(ByteBuf uncompressed, int headerLen) {
    checkNotNull(uncompressed);
    checkArgument(uncompressed.readableBytes() > 0);

    int uncompressedLen = uncompressed.readableBytes();
    int maxLen = compressor.maxCompressedLength(uncompressedLen);

    // get the source bytebuffer
    ByteBuffer uncompressedNio = uncompressed.nioBuffer(uncompressed.readerIndex(), uncompressedLen);
    ByteBuf compressed = PooledByteBufAllocator.DEFAULT.buffer(
            maxLen + headerLen, maxLen + headerLen);
    ByteBuffer compressedNio = compressed.nioBuffer(headerLen, maxLen);

    int compressedLen = compressor.compress(
            uncompressedNio, uncompressedNio.position(), uncompressedLen,
            compressedNio, compressedNio.position(), maxLen);
    compressed.writerIndex(compressedLen + headerLen);

    return compressed;
}
 
Example #16
Source File: NetworkManager.java    From Ogar2-Server with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    try {
        ch.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException ex) {
        // IP_TOS not supported by platform, ignore
    }
    ch.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    ch.pipeline().addLast(new HttpServerCodec());
    ch.pipeline().addLast(new HttpObjectAggregator(65536));
    ch.pipeline().addLast(new WebSocketHandler());
    ch.pipeline().addLast(new PacketDecoder());
    ch.pipeline().addLast(new PacketEncoder());
    ch.pipeline().addLast(new ClientHandler(server));
}
 
Example #17
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJksStoreWithExplicitEnabledAndDisabledCiphersOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    // Discover the default enabled ciphers
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createOpenSSLEngineDirectly(options);
    String[] ciphers = directEngine.getEnabledCipherSuites();
    assertTrue("There werent enough initial ciphers to choose from!", ciphers.length > 1);

    // Pull out two to enable, and one to disable specifically
    String cipher1 = ciphers[0];
    String cipher2 = ciphers[1];
    String[] enabledCiphers = new String[] { cipher1, cipher2 };
    String[] disabledCipher = new String[] { cipher1 };
    String[] remainingCipher = new String[] { cipher2 };
    options.setEnabledCipherSuites(enabledCiphers);
    options.setDisabledCipherSuites(disabledCipher);
    SslContext context = TransportSupport.createOpenSslContext(options);
    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);

    // verify the option took effect, that the disabled ciphers were removed from the enabled list.
    assertNotNull(engine);
    assertArrayEquals("Enabled ciphers not as expected", remainingCipher, engine.getEnabledCipherSuites());
}
 
Example #18
Source File: DFClusterManager.java    From dfactor with MIT License 5 votes vote down vote up
private int _sendToNode(String srcActor, String dstNode, String dstActor, String dstMethod, 
			int sessionId, int userCmd, byte[] userData, int userDataType){
	DFNode node = null;
	_lockNodeRead.lock();
	try{
		node = _mapNode.get(dstNode);
	}finally{
		_lockNodeRead.unlock();
	}
	if(node != null){
		//
		DMCluster.UserMsgHead.Builder bd = DMCluster.UserMsgHead.newBuilder();
		bd.setSrcNode(_selfNodeName).setSrcType(_selfNodeType)
		.setSessionId(sessionId)
		.setSrcActor(srcActor).setDstActor(dstActor);
		if(dstMethod != null){
			bd.setDstMethod(dstMethod);
		}
		byte[] bufHead = bd.build().toByteArray();
		int headLen = bufHead.length;
		int dataLen = 0;
		if(userData != null){
			dataLen = userData.length;
		}
		//cmd(2) + headLen(2) + head(N) + userCmd(4) + userDataType(1) +  userData(N)
		int msgLen = 2 + headLen + 4 + 1 + dataLen;
		ByteBuf buf = PooledByteBufAllocator.DEFAULT.ioBuffer(msgLen);
		buf.writeShort(DMCmd.UserMsg);
		buf.writeShort(headLen);
		buf.writeBytes(bufHead);
		buf.writeInt(userCmd);
		buf.writeByte(userDataType);
		if(userData != null){
			buf.writeBytes(userData);
		}
		node.channel.write(buf);
		return 0;
	}
	return 1;
}
 
Example #19
Source File: NewProxyConnectionHandler.java    From HttpProxy with MIT License 5 votes vote down vote up
/**
 * 当本channel被关闭时,及时关闭对应的另一个channel
 * 出现异常和正常关闭都会导致本channel被关闭
 *
 * @param ctx
 * @throws Exception
 */
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (localChannel != null && localChannel.isActive()) {
        localChannel.writeAndFlush(PooledByteBufAllocator.DEFAULT.buffer()).addListener(future -> {
            localChannel.close().addListener(future1 -> {
                logger.info("返回0字节:webserver关闭连接,因此关闭到browser连接");
            });
        });
    }
    super.channelInactive(ctx);
}
 
Example #20
Source File: Markers.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
public static ByteBuf newReplicatedSubscriptionsSnapshotResponse(String snapshotId, String replyToCluster,
        String cluster, long ledgerId, long entryId) {
    ReplicatedSubscriptionsSnapshotResponse.Builder builder = ReplicatedSubscriptionsSnapshotResponse.newBuilder();
    builder.setSnapshotId(snapshotId);

    MessageIdData.Builder msgIdBuilder = MessageIdData.newBuilder();
    msgIdBuilder.setLedgerId(ledgerId);
    msgIdBuilder.setEntryId(entryId);

    ClusterMessageId.Builder clusterMessageIdBuilder = ClusterMessageId.newBuilder();
    clusterMessageIdBuilder.setCluster(cluster);
    clusterMessageIdBuilder.setMessageId(msgIdBuilder);

    builder.setCluster(clusterMessageIdBuilder);
    ReplicatedSubscriptionsSnapshotResponse response = builder.build();

    int size = response.getSerializedSize();

    ByteBuf payload = PooledByteBufAllocator.DEFAULT.buffer(size);
    ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(payload);
    try {
        response.writeTo(outStream);
        return newMessage(MarkerType.REPLICATED_SUBSCRIPTION_SNAPSHOT_RESPONSE, Optional.of(replyToCluster),
                payload);
    } finally {
        msgIdBuilder.recycle();
        clusterMessageIdBuilder.recycle();
        payload.release();
        builder.recycle();
        response.recycle();
        outStream.recycle();
    }
}
 
Example #21
Source File: HttpObjectEncoderBenchmark.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
    byte[] bytes = new byte[256];
    content = Unpooled.buffer(bytes.length);
    content.writeBytes(bytes);
    ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
    HttpHeaders headersWithChunked = new DefaultHttpHeaders(false);
    headersWithChunked.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    HttpHeaders headersWithContentLength = new DefaultHttpHeaders(false);
    headersWithContentLength.add(HttpHeaderNames.CONTENT_LENGTH, testContent.readableBytes());

    fullRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", testContent,
            headersWithContentLength, EmptyHttpHeaders.INSTANCE);
    contentLengthRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index",
            headersWithContentLength);
    chunkedRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", headersWithChunked);
    lastContent = new DefaultLastHttpContent(testContent, false);

    encoder = new HttpRequestEncoder();
    context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
            UnpooledByteBufAllocator.DEFAULT, encoder) {
        @Override
        protected void handleException(Throwable t) {
            handleUnexpectedException(t);
        }
    };
}
 
Example #22
Source File: PduCodec.java    From herddb with Apache License 2.0 5 votes vote down vote up
private static ByteBuf write(long messageId, String error, boolean notLeader, boolean missingPreparedStatement, boolean sqlIntegrityConstraintViolation) {
    if (error == null) {
        error = "";
    }
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
            .directBuffer(
                    VERSION_SIZE
                            + FLAGS_SIZE
                            + TYPE_SIZE
                            + MSGID_SIZE
                            + ONE_BYTE
                            + error.length());
    byteBuf.writeByte(VERSION_3);
    byteBuf.writeByte(Pdu.FLAGS_ISRESPONSE);
    byteBuf.writeByte(Pdu.TYPE_ERROR);
    byteBuf.writeLong(messageId);
    byte flags = FLAG_NONE;
    if (notLeader) {
        flags = (byte) (flags | FLAG_NOT_LEADER);
    }
    if (missingPreparedStatement) {
        flags = (byte) (flags | FLAG_MISSING_PREPARED_STATEMENT);
    }
    if (sqlIntegrityConstraintViolation) {
        flags = (byte) (flags | FLAG_DUPLICATEPRIMARY_KEY_ERROR);
    }
    byteBuf.writeByte(flags);
    ByteBufUtils.writeString(byteBuf, error);
    return byteBuf;
}
 
Example #23
Source File: ByteBufLeakTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Bean
public DataBufferFactory dataBufferFactory() {
    return new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT) {
        // This method will be called when emitting string from Mono/Flux.
        @Override
        public NettyDataBuffer allocateBuffer(int initialCapacity) {
            final NettyDataBuffer buffer = super.allocateBuffer(initialCapacity);
            // Keep allocated buffers.
            allocatedBuffers.offer(buffer);
            return buffer;
        }
    };
}
 
Example #24
Source File: Kcp.java    From jkcp with Apache License 2.0 5 votes vote down vote up
/**
 * change MTU size, default is 1400
 *
 * @param mtu
 * @return
 */
public int setMtu(int mtu) {
    if (mtu < 50 || mtu < IKCP_OVERHEAD) {
        return -1;
    }
    ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer((mtu + IKCP_OVERHEAD) * 3);
    this.mtu = mtu;
    mss = mtu - IKCP_OVERHEAD;
    if (buffer != null) {
        buffer.release();
    }
    this.buffer = buf;
    return 0;
}
 
Example #25
Source File: PduCodec.java    From herddb with Apache License 2.0 5 votes vote down vote up
public static ByteBuf write(
        long messageId, String tableSpace, String tableName,
        List<byte[]> indexesDefinition
) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
            .directBuffer(
                    VERSION_SIZE
                            + FLAGS_SIZE
                            + TYPE_SIZE
                            + MSGID_SIZE
                            + tableSpace.length()
                            + tableName.length()
                            + (indexesDefinition == null ? 0 : (indexesDefinition.size() * 64)));
    byteBuf.writeByte(VERSION_3);
    byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
    byteBuf.writeByte(Pdu.TYPE_TABLE_RESTORE_FINISHED);
    byteBuf.writeLong(messageId);

    ByteBufUtils.writeString(byteBuf, tableSpace);
    ByteBufUtils.writeString(byteBuf, tableName);

    if (indexesDefinition == null) {
        byteBuf.writeInt(0);
    } else {
        byteBuf.writeInt(indexesDefinition.size());
        for (int i = 0; i < indexesDefinition.size(); i++) {
            ByteBufUtils.writeArray(byteBuf, indexesDefinition.get(i));
        }
    }

    return byteBuf;

}
 
Example #26
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSslEngineFromPkcs12StoreWithExplicitEnabledProtocolsOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    TransportOptions options = createPkcs12SslOptions(ENABLED_PROTOCOLS);

    SslContext context = TransportSupport.createOpenSslContext(options);
    assertNotNull(context);

    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);
    assertNotNull(engine);

    assertArrayEquals("Enabled protocols not as expected", ENABLED_OPENSSL_PROTOCOLS, engine.getEnabledProtocols());
}
 
Example #27
Source File: CopyByteBufHandlerTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void copiesAndReleasesPooledByteBuf() {
    ByteBufAllocator pooledAllocator = PooledByteBufAllocator.DEFAULT;
    ByteBufAllocator unpooledAllocator = UnpooledByteBufAllocator.DEFAULT;
    CopyByteBufHandler handler = new CopyByteBufHandler(unpooledAllocator);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    ArgumentCaptor<ByteBuf> valueCapture = ArgumentCaptor.forClass(ByteBuf.class);
    doReturn(ctx).when(ctx).fireChannelRead(valueCapture.capture());

    ByteBuf pooledBuf = pooledAllocator.buffer(4);
    assertThat(pooledBuf.alloc(), is(pooledAllocator));
    try {
        assertThat(writeAscii(pooledBuf, "test"), is(4));
        handler.channelRead(ctx, pooledBuf);
        assertThat(pooledBuf.refCnt(), is(0));

        ByteBuf unpooledBuf = valueCapture.getValue();
        assertThat(unpooledBuf, is(not(sameInstance(pooledBuf))));
        assertThat(unpooledBuf.alloc(), is(unpooledAllocator));
        assertThat(unpooledBuf.toString(US_ASCII), equalTo("test"));
    } finally {
        if (pooledBuf.refCnt() > 0) {
            pooledBuf.release();
        }
    }
}
 
Example #28
Source File: IdentityCompressionCodec.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf compress(ByteBuf uncompressed, int headerLen) {
    checkNotNull(uncompressed);
    checkArgument(uncompressed.readableBytes() >= 0);
    if (headerLen == 0) {
        return uncompressed.retain();
    } else {
        CompositeByteBuf composited = PooledByteBufAllocator.DEFAULT.compositeBuffer(2);
        composited.addComponent(PooledByteBufAllocator.DEFAULT.buffer(headerLen, headerLen));
        composited.addComponent(uncompressed.retain());
        return composited;
    }
}
 
Example #29
Source File: ObjectEncodingHandlerSerializationImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private ByteBuf objectToByteBuf(Object obj) throws EncodingException {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
    try {
        ByteBufOutputStream bos = new ByteBufOutputStream(byteBuf);
        ObjectOutputStream outputStream = new ObjectOutputStream(bos);
        outputStream.writeObject(obj);
        outputStream.close();
        return byteBuf;
    } catch (Exception e) {
        ReferenceCountUtil.safeRelease(byteBuf);
        throw new EncodingException(RsocketErrorCode.message("RST-700500", obj.getClass().getName(), "byte[]"), e);
    }
}
 
Example #30
Source File: NettyServer.java    From hermes with Apache License 2.0 5 votes vote down vote up
public ChannelFuture start(int port) {
	ServerBootstrap b = new ServerBootstrap();
	b.group(m_bossGroup, m_workerGroup)//
	      .channel(NioServerSocketChannel.class)//
	      .childHandler(new ChannelInitializer<SocketChannel>() {
		      @Override
		      public void initChannel(SocketChannel ch) throws Exception {
			      ch.pipeline().addLast(
			            new DefaultNettyChannelOutboundHandler(),//
			            new NettyDecoder(), //
			            new MagicNumberAndLengthPrepender(), //
			            new NettyEncoder(), //
			            new IdleStateHandler(0, 0, m_config.getClientMaxIdleSeconds()),//
			            new DefaultServerChannelInboundHandler(lookup(CommandProcessorManager.class), m_config
			                  .getClientMaxIdleSeconds()));
		      }
	      }).option(ChannelOption.SO_BACKLOG, 128) // TODO set tcp options
	      .childOption(ChannelOption.SO_KEEPALIVE, true)//
	      .childOption(ChannelOption.SO_REUSEADDR, true)//
	      .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
	      .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024)//
	      .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024)//
	;

	// Bind and start to accept incoming connections.
	ChannelFuture f = b.bind(port);

	return f;
}