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:alluxio.network.protocol.databuffer.DataNettyBuffer.java

License:Apache License

/**
* Constructor for creating a DataNettyBuffer, by passing a Netty ByteBuf.
* This way we avoid one copy from ByteBuf to another ByteBuffer,
* and making sure the buffer would not be recycled.
* IMPORTANT: {@link #release()} must be called after
* reading is finished. Otherwise the memory space for the ByteBuf might never be reclaimed.
*
* @param bytebuf The ByteBuf having the data
* @param length The length of the underlying ByteBuffer data
*//* w w  w  . ja v a  2 s. com*/
public DataNettyBuffer(ByteBuf bytebuf, long length) {
    // throws exception if there are multiple nioBuffers, or reference count is not 1
    Preconditions.checkArgument(bytebuf.nioBufferCount() == 1,
            "Number of nioBuffers of this bytebuf is %s (1 expected).", bytebuf.nioBufferCount());
    Preconditions.checkArgument(bytebuf.refCnt() == 1, "Reference count of this bytebuf is %s (1 expected).",
            bytebuf.refCnt());

    // increase the bytebuf reference count so it would not be recycled by Netty
    bytebuf.retain();
    mNettyBuf = bytebuf;
    mBuffer = bytebuf.nioBuffer();
    mLength = length;
}

From source file:com.couchbase.client.core.cluster.SubdocumentMessageTest.java

License:Apache License

@Test
public void shouldApplyAllMultiMutationsAndReleaseCommandFragments() {
    ByteBuf counterFragment = Unpooled.copiedBuffer("-404", CharsetUtil.UTF_8);
    counterFragment.retain(2);/*from  w w  w  .  ja va2s. c o  m*/

    ByteBuf stringFragment = Unpooled.copiedBuffer("\"mutated\"", CharsetUtil.UTF_8);
    stringFragment.retain(2);

    ByteBuf arrayInsertedFragment = Unpooled.copiedBuffer("\"inserted\"", CharsetUtil.UTF_8);
    ByteBuf arrayFirstFragment = Unpooled.copiedBuffer("\"first\"", CharsetUtil.UTF_8);
    ByteBuf arrayLastFragment = Unpooled.copiedBuffer("\"last\"", CharsetUtil.UTF_8);
    ByteBuf uniqueFragment = Unpooled.copiedBuffer("\"unique\"", CharsetUtil.UTF_8);

    MutationCommand[] commands = new MutationCommand[] {
            new MutationCommand(Mutation.COUNTER, "counter", counterFragment, false),
            new MutationCommand(Mutation.COUNTER, "another.counter", counterFragment, true),
            new MutationCommand(Mutation.COUNTER, "another.counter", counterFragment, false),
            new MutationCommand(Mutation.DICT_ADD, "sub.value2", stringFragment),
            new MutationCommand(Mutation.DICT_UPSERT, "sub.value3", stringFragment),
            new MutationCommand(Mutation.REPLACE, "value", stringFragment),
            new MutationCommand(Mutation.ARRAY_INSERT, "sub.array[1]", arrayInsertedFragment),
            new MutationCommand(Mutation.ARRAY_PUSH_FIRST, "sub.array", arrayFirstFragment),
            new MutationCommand(Mutation.ARRAY_PUSH_LAST, "sub.array", arrayLastFragment),
            new MutationCommand(Mutation.ARRAY_ADD_UNIQUE, "sub.array", uniqueFragment),
            new MutationCommand(Mutation.DELETE, "sub.value") };

    SubMultiMutationRequest request = new SubMultiMutationRequest(testSubKey, bucket(), commands);
    MultiMutationResponse response = cluster().<MultiMutationResponse>send(request).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, response.status());
    assertEquals(Unpooled.EMPTY_BUFFER, response.content());
    assertEquals(-1, response.firstErrorIndex());
    assertEquals(ResponseStatus.SUCCESS, response.firstErrorStatus());

    assertEquals(0, stringFragment.refCnt());
    assertEquals(0, counterFragment.refCnt());
    assertEquals(0, arrayInsertedFragment.refCnt());
    assertEquals(0, arrayFirstFragment.refCnt());
    assertEquals(0, arrayLastFragment.refCnt());
    assertEquals(0, uniqueFragment.refCnt());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < commands.length; i++) {
        MutationCommand command = commands[i];
        MultiResult result = response.responses().get(i);
        assertEquals(command.path(), result.path());
        assertEquals(command.mutation(), result.operation());

        sb.append('\n').append(result);
        ReferenceCountUtil.releaseLater(result.value());
    }
    if (sb.length() > 1)
        sb.deleteCharAt(0);

    String expectedResponse = "COUNTER(counter): SUCCESS = -404" + "\nCOUNTER(another.counter): SUCCESS = -404"
            + "\nCOUNTER(another.counter): SUCCESS = -808" +
            //values below have no content
            "\nDICT_ADD(sub.value2): SUCCESS" + "\nDICT_UPSERT(sub.value3): SUCCESS"
            + "\nREPLACE(value): SUCCESS" + "\nARRAY_INSERT(sub.array[1]): SUCCESS"
            + "\nARRAY_PUSH_FIRST(sub.array): SUCCESS" + "\nARRAY_PUSH_LAST(sub.array): SUCCESS"
            + "\nARRAY_ADD_UNIQUE(sub.array): SUCCESS" + "\nDELETE(sub.value): SUCCESS";
    assertEquals(expectedResponse, sb.toString());

    String expected = "{\"value\":\"mutated\"," + "\"sub\":{" +
    //                "\"value\":\"subStringValue\"," + //DELETED
            "\"array\":[\"first\",\"array1\",\"inserted\",2,true,\"last\",\"unique\"]"
            + ",\"value2\":\"mutated\"" + ",\"value3\":\"mutated\"}," + "\"counter\":-404,"
            + "\"another\":{\"counter\":-808}}";
    assertMutation(testSubKey, expected);
}

From source file:com.couchbase.client.core.cluster.SubdocumentMessageTest.java

License:Apache License

@Test
public void shouldFailSomeMultiMutationsAndReleaseCommandFragments() {
    ByteBuf counterFragment = Unpooled.copiedBuffer("-404", CharsetUtil.UTF_8);
    counterFragment.retain();/* w ww .  ja v  a 2  s  . c om*/

    ByteBuf stringFragment = Unpooled.copiedBuffer("\"mutated\"", CharsetUtil.UTF_8);
    stringFragment.retain(2);

    ByteBuf arrayInsertedFragment = Unpooled.copiedBuffer("\"inserted\"", CharsetUtil.UTF_8);
    ByteBuf arrayFirstFragment = Unpooled.copiedBuffer("\"first\"", CharsetUtil.UTF_8);
    ByteBuf arrayLastFragment = Unpooled.copiedBuffer("\"last\"", CharsetUtil.UTF_8);
    ByteBuf uniqueFragment = Unpooled.copiedBuffer("\"unique\"", CharsetUtil.UTF_8);

    SubMultiMutationRequest request = new SubMultiMutationRequest(testSubKey, bucket(),
            new MutationCommand(Mutation.COUNTER, "counter", counterFragment, false),
            new MutationCommand(Mutation.COUNTER, "another.counter", counterFragment, true),
            new MutationCommand(Mutation.DICT_ADD, "sub.value2", stringFragment),
            new MutationCommand(Mutation.DICT_UPSERT, "sub.value3", stringFragment),
            new MutationCommand(Mutation.REPLACE, "value", stringFragment),
            //this one fails
            new MutationCommand(Mutation.ARRAY_INSERT, "sub.array[5]", arrayInsertedFragment),
            new MutationCommand(Mutation.ARRAY_PUSH_FIRST, "sub.array", arrayFirstFragment),
            new MutationCommand(Mutation.ARRAY_PUSH_LAST, "sub.array", arrayLastFragment),
            new MutationCommand(Mutation.ARRAY_ADD_UNIQUE, "sub.array", uniqueFragment),
            //this one would also fail, but server stops at first failure
            new MutationCommand(Mutation.DELETE, "path.not.found"));
    MultiMutationResponse response = cluster().<MultiMutationResponse>send(request).toBlocking().single();
    assertEquals(ResponseStatus.SUBDOC_MULTI_PATH_FAILURE, response.status());
    assertEquals(Unpooled.EMPTY_BUFFER, response.content());
    assertEquals(5, response.firstErrorIndex());
    assertEquals(ResponseStatus.SUBDOC_PATH_NOT_FOUND, response.firstErrorStatus());
    assertEquals(0, response.responses().size());

    assertEquals(0, stringFragment.refCnt());
    assertEquals(0, counterFragment.refCnt());
    assertEquals(0, arrayInsertedFragment.refCnt());
    assertEquals(0, arrayFirstFragment.refCnt());
    assertEquals(0, arrayLastFragment.refCnt());
    assertEquals(0, uniqueFragment.refCnt());

    //no mutation happened
    String expected = jsonContent;
    assertMutation(testSubKey, expected);
}

From source file:com.couchbase.client.core.cluster.SubdocumentMessageTest.java

License:Apache License

@Test
public void shouldFailAllMultiMutationsAndReleaseCommandFragments() {
    ByteBuf counterFragment = Unpooled.copiedBuffer("-404", CharsetUtil.UTF_8);
    ByteBuf stringFragment = Unpooled.copiedBuffer("\"mutated\"", CharsetUtil.UTF_8);
    ByteBuf arrayFirstFragment = Unpooled.copiedBuffer("\"first\"", CharsetUtil.UTF_8);

    SubMultiMutationRequest request = new SubMultiMutationRequest(testInsertionSubKey, bucket(),
            new MutationCommand(Mutation.COUNTER, "counter", counterFragment, false),
            new MutationCommand(Mutation.DICT_UPSERT, "sub.value3", stringFragment),
            new MutationCommand(Mutation.ARRAY_PUSH_FIRST, "sub.array", arrayFirstFragment),
            new MutationCommand(Mutation.DELETE, "some.paht"));
    MultiMutationResponse response = cluster().<MultiMutationResponse>send(request).toBlocking().single();
    assertEquals(ResponseStatus.NOT_EXISTS, response.status());
    assertEquals(Unpooled.EMPTY_BUFFER, response.content());
    assertEquals(-1, response.firstErrorIndex());
    assertEquals(ResponseStatus.FAILURE, response.firstErrorStatus());
    assertEquals(0, response.responses().size());

    assertEquals(0, stringFragment.refCnt());
    assertEquals(0, counterFragment.refCnt());
    assertEquals(0, arrayFirstFragment.refCnt());
}

From source file:com.couchbase.client.core.config.refresher.CarrierRefresherTest.java

License:Apache License

@Test
public void shouldProposeConfigFromTaintedPoller() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    BucketConfig config = mock(BucketConfig.class);

    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.provider(provider);/*  www  .j  av a  2 s. co m*/

    when(config.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();
    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "localhost:8091", ports));
    when(config.nodes()).thenReturn(nodeInfos);

    final AtomicReference<ByteBuf> bufRef = new AtomicReference<ByteBuf>(null);
    when(cluster.send(any(GetBucketConfigRequest.class)))
            .thenAnswer(new Answer<Observable<GetBucketConfigResponse>>() {
                @Override
                public Observable<GetBucketConfigResponse> answer(InvocationOnMock invocation)
                        throws Throwable {
                    ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8);
                    ByteBuf oldContent = bufRef.getAndSet(content);
                    if (oldContent != null) {
                        assertEquals(0, oldContent.refCnt());
                    }
                    GetBucketConfigResponse response = new GetBucketConfigResponse(ResponseStatus.SUCCESS,
                            KeyValueStatus.SUCCESS.code(), "bucket", content,
                            InetAddress.getByName("localhost"));
                    return Observable.just(response);
                }
            });

    refresher.markTainted(config);

    Thread.sleep(1500);

    verify(provider, times(1)).proposeBucketConfig("bucket", "{\"config\": true}");
    assertEquals(0, bufRef.get().refCnt());
}

From source file:com.couchbase.client.core.config.refresher.CarrierRefresherTest.java

License:Apache License

@Test
public void shouldNotProposeInvalidConfigFromTaintedPoller() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    BucketConfig config = mock(BucketConfig.class);

    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.provider(provider);//  w  w  w  .  j  av  a 2 s  .c  o m

    when(config.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();
    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "localhost:8091", ports));
    when(config.nodes()).thenReturn(nodeInfos);

    ByteBuf content = Unpooled.copiedBuffer("", CharsetUtil.UTF_8);
    when(cluster.send(any(GetBucketConfigRequest.class)))
            .thenReturn(Observable.just((CouchbaseResponse) new GetBucketConfigResponse(ResponseStatus.FAILURE,
                    KeyValueStatus.ERR_NOT_FOUND.code(), "bucket", content,
                    InetAddress.getByName("localhost"))));

    refresher.markTainted(config);

    Thread.sleep(1500);

    verify(provider, never()).proposeBucketConfig("bucket", "");
    assertEquals(0, content.refCnt());
}

From source file:com.couchbase.client.core.config.refresher.CarrierRefresherTest.java

License:Apache License

@Test
public void shouldRefreshWithValidClusterConfig() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.registerBucket("bucket", "");
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    refresher.provider(provider);/*ww w  .  j a va 2 s . c o  m*/

    ClusterConfig clusterConfig = mock(ClusterConfig.class);
    BucketConfig bucketConfig = mock(BucketConfig.class);
    when(bucketConfig.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();
    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "localhost:8091", ports));
    when(bucketConfig.nodes()).thenReturn(nodeInfos);
    Map<String, BucketConfig> bucketConfigs = new HashMap<String, BucketConfig>();
    bucketConfigs.put("bucket", bucketConfig);

    when(clusterConfig.bucketConfigs()).thenReturn(bucketConfigs);

    ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8);
    when(cluster.send(any(GetBucketConfigRequest.class)))
            .thenReturn(Observable.just((CouchbaseResponse) new GetBucketConfigResponse(ResponseStatus.SUCCESS,
                    KeyValueStatus.SUCCESS.code(), "bucket", content, InetAddress.getByName("localhost"))));

    refresher.refresh(clusterConfig);

    Thread.sleep(200);

    verify(provider, times(1)).proposeBucketConfig("bucket", "{\"config\": true}");
    assertEquals(0, content.refCnt());
}

From source file:com.couchbase.client.core.config.refresher.CarrierRefresherTest.java

License:Apache License

@Test
public void shouldNotRefreshWithInvalidClusterConfig() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.registerBucket("bucket", "");
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    refresher.provider(provider);//from www.  j a  va 2  s. c o m

    ClusterConfig clusterConfig = mock(ClusterConfig.class);
    BucketConfig bucketConfig = mock(BucketConfig.class);
    when(bucketConfig.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();

    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "localhost:8091", ports));
    when(bucketConfig.nodes()).thenReturn(nodeInfos);
    Map<String, BucketConfig> bucketConfigs = new HashMap<String, BucketConfig>();
    bucketConfigs.put("bucket", bucketConfig);

    when(clusterConfig.bucketConfigs()).thenReturn(bucketConfigs);

    ByteBuf content = Unpooled.copiedBuffer("", CharsetUtil.UTF_8);
    when(cluster.send(any(GetBucketConfigRequest.class)))
            .thenReturn(Observable.just((CouchbaseResponse) new GetBucketConfigResponse(ResponseStatus.FAILURE,
                    KeyValueStatus.ERR_NOT_FOUND.code(), "bucket", content,
                    InetAddress.getByName("localhost"))));

    refresher.refresh(clusterConfig);

    Thread.sleep(200);

    verify(provider, never()).proposeBucketConfig("bucket", "");
    assertEquals(0, content.refCnt());
}

From source file:com.couchbase.client.core.config.refresher.CarrierRefresherTest.java

License:Apache License

@Test
public void shouldFallbackToNextOnRefreshWhenFirstFails() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.registerBucket("bucket", "");
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    refresher.provider(provider);//from ww  w  .  ja va2 s.  co m

    ClusterConfig clusterConfig = mock(ClusterConfig.class);
    BucketConfig bucketConfig = mock(BucketConfig.class);
    when(bucketConfig.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();

    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "1.2.3.4:8091", ports));
    nodeInfos.add(new DefaultNodeInfo(null, "2.3.4.5:8091", ports));
    when(bucketConfig.nodes()).thenReturn(nodeInfos);
    Map<String, BucketConfig> bucketConfigs = new HashMap<String, BucketConfig>();
    bucketConfigs.put("bucket", bucketConfig);

    when(clusterConfig.bucketConfigs()).thenReturn(bucketConfigs);

    ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8);
    Observable<CouchbaseResponse> goodResponse = Observable
            .just((CouchbaseResponse) new GetBucketConfigResponse(ResponseStatus.SUCCESS,
                    KeyValueStatus.SUCCESS.code(), "bucket", content, InetAddress.getByName("1.2.3.4")));
    Observable<CouchbaseResponse> badResponse = Observable.error(new CouchbaseException("Woops.."));
    when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(badResponse, goodResponse);

    refresher.refresh(clusterConfig);

    Thread.sleep(1500);

    verify(provider, times(1)).proposeBucketConfig("bucket", "{\"config\": true}");
    assertEquals(0, content.refCnt());
}

From source file:com.couchbase.client.core.config.refresher.CarrierRefresherTest.java

License:Apache License

@Test
public void shouldFallbackToNextOnPollWhenFirstFails() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    BucketConfig config = mock(BucketConfig.class);

    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.provider(provider);//from  w  ww.ja va2s . c  om

    when(config.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();

    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "1.2.3.4:8091", ports));
    nodeInfos.add(new DefaultNodeInfo(null, "2.3.4.5:8091", ports));
    when(config.nodes()).thenReturn(nodeInfos);

    ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8);
    Observable<CouchbaseResponse> goodResponse = Observable
            .just((CouchbaseResponse) new GetBucketConfigResponse(ResponseStatus.SUCCESS,
                    KeyValueStatus.SUCCESS.code(), "bucket", content, InetAddress.getByName("1.2.3.4")));
    Observable<CouchbaseResponse> badResponse = Observable.error(new CouchbaseException("Failure"));
    when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(badResponse, goodResponse);
    refresher.markTainted(config);

    Thread.sleep(1500);

    verify(provider, times(1)).proposeBucketConfig("bucket", "{\"config\": true}");
    assertEquals(0, content.refCnt());
}