Example usage for io.netty.buffer Unpooled EMPTY_BUFFER

List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled EMPTY_BUFFER.

Prototype

ByteBuf EMPTY_BUFFER

To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.

Click Source Link

Document

A buffer whose capacity is 0 .

Usage

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldNotReleaseStoreRequestContentOnRetry() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);/*from  w ww .  j  a v  a  2s  .c o m*/
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    UpsertRequest requestMock = mock(UpsertRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldReleaseAppendRequestContentOnSuccess() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);/*ww w  .  j  a  v  a2  s . c  om*/
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);

    AppendRequest requestMock = mock(AppendRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(0, requestContent.refCnt());
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldNotReleaseAppendRequestContentOnRetry() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);/*from   w  ww  .  j ava2 s .co  m*/
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    AppendRequest requestMock = mock(AppendRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldReleasePrependRequestContentOnSuccess() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);/*from w  ww.j a  v  a  2 s. c om*/
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(0, requestContent.refCnt());
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldNotReleasePrependRequestContentOnRetry() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);/*from   www .ja  v a2  s . c o m*/
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test(expected = CouchbaseException.class)
public void shouldFailWhenOpaqueDoesNotMatch() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);/*  w  ww  .  j  a  v a  2s.com*/
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);
    response.setOpaque(1);

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    AsyncSubject<CouchbaseResponse> responseSubject = AsyncSubject.<CouchbaseResponse>create();
    when(requestMock.observable()).thenReturn(responseSubject);
    when(requestMock.content()).thenReturn(requestContent);
    when(requestMock.opaque()).thenReturn(3);
    requestQueue.add(requestMock);

    channel.writeInbound(response);
    assertEquals(0, content.refCnt());
    responseSubject.toBlocking().single();
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldFireKeepAlive() throws Exception {
    final AtomicInteger keepAliveEventCounter = new AtomicInteger();
    final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference();

    KeyValueHandler testHandler = new KeyValueHandler(mock(AbstractEndpoint.class), eventSink, requestQueue,
            false) {//w ww .java 2s  .  c  o  m

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            super.channelRegistered(ctx);
            ctxRef.compareAndSet(null, ctx);
        }

        @Override
        protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
            assertEquals(1, keepAliveEventCounter.incrementAndGet());
        }

        @Override
        protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
            assertEquals(2, keepAliveEventCounter.incrementAndGet());
        }

        @Override
        protected CoreEnvironment env() {
            return DefaultCoreEnvironment.create();
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(testHandler);

    //test idle event triggers a k/v keepAlive request and hook is called
    testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT);

    assertEquals(1, keepAliveEventCounter.get());
    assertTrue(requestQueue.peek() instanceof KeyValueHandler.KeepAliveRequest);
    KeyValueHandler.KeepAliveRequest keepAliveRequest = (KeyValueHandler.KeepAliveRequest) requestQueue.peek();

    //test responding to the request with memcached response is interpreted into a KeepAliveResponse, hook is called
    DefaultFullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(new byte[] {},
            Unpooled.EMPTY_BUFFER);
    response.setOpaque(keepAliveRequest.opaque());
    response.setStatus(KeyValueStatus.ERR_NO_MEM.code());

    channel.writeInbound(response);
    KeyValueHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable()
            .cast(KeyValueHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single();

    assertEquals(2, keepAliveEventCounter.get());
    assertEquals(ResponseStatus.OUT_OF_MEMORY, keepAliveResponse.status());
}

From source file:com.couchbase.client.core.endpoint.search.SearchHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(ChannelHandlerContext ctx, SearchRequest msg) throws Exception {
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof UpsertSearchIndexRequest) {
        httpMethod = HttpMethod.PUT;/*  w ww . j a v a  2 s .c  o m*/
    } else if (msg instanceof RemoveSearchIndexRequest) {
        httpMethod = HttpMethod.DELETE;
    } else if (msg instanceof SearchQueryRequest) {
        httpMethod = HttpMethod.POST;
    }

    ByteBuf content;
    if (msg instanceof UpsertSearchIndexRequest) {
        content = Unpooled.copiedBuffer(((UpsertSearchIndexRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof SearchQueryRequest) {
        content = Unpooled.copiedBuffer(((SearchQueryRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof UpsertSearchIndexRequest || msg instanceof SearchQueryRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());
    return request;
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ViewRequest msg) throws Exception {
    if (msg instanceof KeepAliveRequest) {
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.HEAD, "/",
                Unpooled.EMPTY_BUFFER);
        request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
        return request;
    }/* ww  w . ja va  2 s .  c om*/

    StringBuilder path = new StringBuilder();

    HttpMethod method = HttpMethod.GET;
    ByteBuf content = null;
    if (msg instanceof ViewQueryRequest) {
        ViewQueryRequest queryMsg = (ViewQueryRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.design() : queryMsg.design());
        if (queryMsg.spatial()) {
            path.append("/_spatial/");
        } else {
            path.append("/_view/");
        }
        path.append(queryMsg.view());

        int queryLength = queryMsg.query() == null ? 0 : queryMsg.query().length();
        int keysLength = queryMsg.keys() == null ? 0 : queryMsg.keys().length();
        boolean hasQuery = queryLength > 0;
        boolean hasKeys = keysLength > 0;

        if (hasQuery || hasKeys) {
            if (queryLength + keysLength < MAX_GET_LENGTH) {
                //the query is short enough for GET
                //it has query, query+keys or keys only
                if (hasQuery) {
                    path.append("?").append(queryMsg.query());
                    if (hasKeys) {
                        path.append("&keys=").append(encodeKeysGet(queryMsg.keys()));
                    }
                } else {
                    //it surely has keys if not query
                    path.append("?keys=").append(encodeKeysGet(queryMsg.keys()));
                }
            } else {
                //the query is too long for GET, use the keys as JSON body
                if (hasQuery) {
                    path.append("?").append(queryMsg.query());
                }
                String keysContent = encodeKeysPost(queryMsg.keys());

                //switch to POST
                method = HttpMethod.POST;
                //body is "keys" but in JSON
                content = ctx.alloc().buffer(keysContent.length());
                content.writeBytes(keysContent.getBytes(CHARSET));
            }
        }
    } else if (msg instanceof GetDesignDocumentRequest) {
        GetDesignDocumentRequest queryMsg = (GetDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
    } else if (msg instanceof UpsertDesignDocumentRequest) {
        method = HttpMethod.PUT;
        UpsertDesignDocumentRequest queryMsg = (UpsertDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
        content = Unpooled.copiedBuffer(queryMsg.body(), CHARSET);
    } else if (msg instanceof RemoveDesignDocumentRequest) {
        method = HttpMethod.DELETE;
        RemoveDesignDocumentRequest queryMsg = (RemoveDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
    } else {
        throw new IllegalArgumentException("Unknown incoming ViewRequest type " + msg.getClass());
    }

    if (content == null) {
        content = Unpooled.buffer(0);
    }
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, path.toString(),
            content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));
    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());

    return request;
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java

License:Apache License

/**
 * Parse out the info portion from the header part of the query response.
 *
 * This includes the total rows, but also debug info if attached.
 *//*from  w ww  . j  a v  a  2  s . com*/
private void parseViewInfo() {
    int rowsStart = -1;
    for (int i = responseContent.readerIndex(); i < responseContent.writerIndex() - 2; i++) {
        byte curr = responseContent.getByte(i);
        byte f1 = responseContent.getByte(i + 1);
        byte f2 = responseContent.getByte(i + 2);

        if (curr == '"' && f1 == 'r' && f2 == 'o') {
            rowsStart = i;
            break;
        }
    }

    if (rowsStart == -1) {
        return;
    }

    ByteBuf info = responseContent.readBytes(rowsStart - responseContent.readerIndex());
    int closingPointer = info.forEachByteDesc(new ByteBufProcessor() {
        @Override
        public boolean process(byte value) throws Exception {
            return value != ',';
        }
    });

    if (closingPointer > 0) {
        info.setByte(closingPointer, '}');
        viewInfoObservable.onNext(info);
    } else {
        viewInfoObservable.onNext(Unpooled.EMPTY_BUFFER);
    }
    viewInfoObservable.onCompleted();
    viewParsingState = QUERY_STATE_ROWS;
}