Example usage for io.netty.buffer ByteBuf refCnt

List of usage examples for io.netty.buffer ByteBuf refCnt

Introduction

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

Prototype

int refCnt();

Source Link

Document

Returns the reference count of this object.

Usage

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

License:Apache License

@Test
public void writeUncompressed() throws Exception {
    ByteBuf buf = GrpcTestUtil.requestByteBuf();
    ByteBufHttpData framed = framer.writePayload(buf);
    assertThat(framed.array()).isEqualTo(GrpcTestUtil.uncompressedFrame(GrpcTestUtil.requestByteBuf()));
    assertThat(buf.refCnt()).isEqualTo(0);
    framed.release();//from   w  ww .  java 2 s . c  o m
}

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

License:Apache License

@Test
public void compressed() throws Exception {
    framer.setCompressor(new Gzip());
    framer.setMessageCompression(true);/*from   w w w  .j a  va  2s .  c  o m*/
    ByteBuf buf = GrpcTestUtil.requestByteBuf();
    ByteBufHttpData framed = framer.writePayload(buf);
    assertThat(framed.array()).isEqualTo(GrpcTestUtil.compressedFrame(GrpcTestUtil.requestByteBuf()));
    assertThat(buf.refCnt()).isEqualTo(0);
    framed.release();
}

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

License:Apache License

@Test
public void emptyNotCompressed() throws Exception {
    framer.setCompressor(new Gzip());
    framer.setMessageCompression(true);/*  w w  w. ja  va 2  s.co  m*/
    ByteBuf buf = GrpcTestUtil.protoByteBuf(SimpleRequest.getDefaultInstance());
    assertThat(buf.readableBytes()).isEqualTo(0);
    ByteBufHttpData framed = framer.writePayload(buf);
    assertThat(framed.array()).isEqualTo(
            GrpcTestUtil.uncompressedFrame(GrpcTestUtil.protoByteBuf(SimpleRequest.getDefaultInstance())));
    assertThat(buf.refCnt()).isEqualTo(0);
    framed.release();
}

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

License:Apache License

@Test
public void deserializeRequest_byteBuf() throws Exception {
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(GrpcTestUtil.REQUEST_MESSAGE.getSerializedSize());
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.writeBytes(GrpcTestUtil.REQUEST_MESSAGE.toByteArray());
    SimpleRequest request = marshaller.deserializeRequest(new ByteBufOrStream(buf));
    assertThat(request).isEqualTo(GrpcTestUtil.REQUEST_MESSAGE);
    assertThat(buf.refCnt()).isEqualTo(0);
}

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

License:Apache License

@Test
public void deserializeRequest_wrappedByteBuf() throws Exception {
    marshaller = new GrpcMessageMarshaller<>(ByteBufAllocator.DEFAULT, GrpcSerializationFormats.PROTO,
            TestServiceGrpc.getUnaryCallMethod(),
            MessageMarshaller.builder().register(SimpleRequest.getDefaultInstance())
                    .register(SimpleResponse.getDefaultInstance()).build(),
            true);/*  ww  w  .  ja v  a  2s. c om*/
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(GrpcTestUtil.REQUEST_MESSAGE.getSerializedSize());
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.writeBytes(GrpcTestUtil.REQUEST_MESSAGE.toByteArray());
    SimpleRequest request = marshaller.deserializeRequest(new ByteBufOrStream(buf));
    assertThat(request).isEqualTo(GrpcTestUtil.REQUEST_MESSAGE);
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.release();
}

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

License:Apache License

@Test
public void deserializeResponse_bytebuf() throws Exception {
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(GrpcTestUtil.RESPONSE_MESSAGE.getSerializedSize());
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.writeBytes(GrpcTestUtil.RESPONSE_MESSAGE.toByteArray());
    SimpleResponse response = marshaller.deserializeResponse(new ByteBufOrStream(buf));
    assertThat(response).isEqualTo(GrpcTestUtil.RESPONSE_MESSAGE);
    assertThat(buf.refCnt()).isEqualTo(0);
}

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

License:Apache License

@Test
public void deserializeResponse_wrappedByteBuf() throws Exception {
    marshaller = new GrpcMessageMarshaller<>(ByteBufAllocator.DEFAULT, GrpcSerializationFormats.PROTO,
            TestServiceGrpc.getUnaryCallMethod(),
            MessageMarshaller.builder().register(SimpleRequest.getDefaultInstance())
                    .register(SimpleResponse.getDefaultInstance()).build(),
            true);/* w ww .  j  a  v a  2  s .co m*/
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(GrpcTestUtil.RESPONSE_MESSAGE.getSerializedSize());
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.writeBytes(GrpcTestUtil.RESPONSE_MESSAGE.toByteArray());
    SimpleResponse response = marshaller.deserializeResponse(new ByteBufOrStream(buf));
    assertThat(response).isEqualTo(GrpcTestUtil.RESPONSE_MESSAGE);
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.release();
}

From source file:com.linecorp.armeria.server.encoding.HttpEncodedResponseTest.java

License:Apache License

@Test
public void testLeak() {
    final ByteBuf buf = Unpooled.buffer();
    buf.writeCharSequence("foo", StandardCharsets.UTF_8);

    final HttpResponse orig = HttpResponse.of(AggregatedHttpMessage.of(HttpStatus.OK,
            MediaType.PLAIN_TEXT_UTF_8, new ByteBufHttpData(buf, true)));
    final HttpEncodedResponse encoded = new HttpEncodedResponse(orig, HttpEncodingType.DEFLATE,
            mediaType -> true, 1);/*from ww  w.j a  v a  2 s  . com*/

    // Drain the stream.
    encoded.subscribe(NoopSubscriber.get(), ImmediateEventExecutor.INSTANCE);

    // 'buf' should be released.
    assertThat(buf.refCnt()).isZero();
}

From source file:com.linkedin.r2.transport.http.client.TestRAPClientCodec.java

License:Apache License

@Test(dataProvider = "responseData")
public void testResponseDecoder(int status, String entity, HttpHeaders headers, String[] cookies) {
    final EmbeddedChannel ch = new EmbeddedChannel(new RAPClientCodec());

    ByteBuf content = Unpooled.copiedBuffer(entity, CHARSET);
    FullHttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(status), content);
    nettyResponse.headers().set(headers);
    for (String cookie : cookies) {
        nettyResponse.headers().add(HttpHeaderNames.SET_COOKIE, cookie);
    }/*from ww w .  j  a v  a2s . c  o  m*/

    ch.writeInbound(nettyResponse);
    RestResponse response = (RestResponse) ch.readInbound();

    Assert.assertEquals(response.getStatus(), status);
    Assert.assertEquals(response.getEntity().asString(CHARSET), entity);
    assertList(response.getCookies(),
            nettyResponse.headers().getAll(HttpConstants.RESPONSE_COOKIE_HEADER_NAME));

    for (Map.Entry<String, String> header : nettyResponse.headers()) {
        if (!header.getKey().equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
            List<String> values = response.getHeaderValues(header.getKey());
            Assert.assertNotNull(values);
            Assert.assertTrue(values.contains(header.getValue()));
        }
    }
    // make sure the incoming ByteBuf is released
    Assert.assertEquals(content.refCnt(), 0);

    ch.finish();
}

From source file:com.netflix.prana.http.api.ProxyHandler.java

License:Apache License

@Override
public Observable<Void> handle(final HttpServerRequest<ByteBuf> serverRequest,
        final HttpServerResponse<ByteBuf> serverResponse) {
    String vip = Utils.forQueryParam(serverRequest.getQueryParameters(), "vip");
    String path = Utils.forQueryParam(serverRequest.getQueryParameters(), "path");
    if (Strings.isNullOrEmpty(vip)) {
        serverResponse.getHeaders().set("Content-Type", "application/xml");
        serverResponse.writeString(ERROR_RESPONSE);
        logger.error("VIP is empty");
        return serverResponse.close();
    }//ww  w  . java  2s. c o m

    if (path == null) {
        path = "";
    }

    final LoadBalancingHttpClient<ByteBuf, ByteBuf> client = getClient(vip);
    final HttpClientRequest<ByteBuf> req = HttpClientRequest.create(serverRequest.getHttpMethod(), path);
    populateRequestHeaders(serverRequest, req);

    final UnicastDisposableCachingSubject<ByteBuf> cachedContent = UnicastDisposableCachingSubject.create();
    /**
     * Why do we retain here?
     * After the onNext on the content returns, RxNetty releases the sent ByteBuf. This ByteBuf is kept out of
     * the scope of the onNext for consumption of the client in the route. The client when eventually writes
     * this ByteBuf over the wire expects the ByteBuf to be usable (i.e. ref count => 1). If this retain() call
     * is removed, the ref count will be 0 after the onNext on the content returns and hence it will be unusable
     * by the client in the route.
     */
    serverRequest.getContent().map(new Func1<ByteBuf, ByteBuf>() {
        @Override
        public ByteBuf call(ByteBuf byteBuf) {
            return byteBuf.retain();
        }
    }).subscribe(cachedContent); // Caches data if arrived before client writes it out, else passes through

    req.withContentSource(cachedContent);

    return client.submit(req).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() {
        @Override
        public Observable<Void> call(final HttpClientResponse<ByteBuf> response) {
            serverResponse.setStatus(response.getStatus());
            List<Map.Entry<String, String>> headers = response.getHeaders().entries();
            for (Map.Entry<String, String> header : headers) {
                serverResponse.getHeaders().add(header.getKey(), header.getValue());
            }
            return response.getContent().map(new Func1<ByteBuf, ByteBuf>() {
                @Override
                public ByteBuf call(ByteBuf byteBuf) {
                    return byteBuf.retain();
                }
            }).map(new Func1<ByteBuf, Void>() {
                @Override
                public Void call(ByteBuf byteBuf) {
                    serverResponse.write(byteBuf);
                    return null;
                }
            });
        }
    }).onErrorResumeNext(new Func1<Throwable, Observable<Void>>() {
        @Override
        public Observable<Void> call(Throwable throwable) {
            serverResponse.getHeaders().set("Content-Type", "application/xml");
            serverResponse.writeString(ERROR_RESPONSE);
            return Observable.just(null);
        }
    }).doOnCompleted(new Action0() {
        @Override
        public void call() {
            serverResponse.close();
            cachedContent.dispose(new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf byteBuf) {
                    /**
                     * Why do we release here?
                     *
                     * All ByteBuf which were never consumed are disposed and sent here. This means that the
                     * client in the route never consumed this ByteBuf. Before sending this ByteBuf to the
                     * content subject, we do a retain (see above for reason) expecting the client in the route
                     * to release it when written over the wire. In this case, though, the client never consumed
                     * it and hence never released corresponding to the retain done by us.
                     */
                    if (byteBuf.refCnt() > 1) { // 1 refCount will be from the subject putting into the cache.
                        byteBuf.release();
                    }
                }
            });
        }
    });
}