Example usage for io.netty.buffer Unpooled copiedBuffer

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

Introduction

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

Prototype

private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) 

Source Link

Usage

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldDecodeListDesignDocumentsResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CharsetUtil.UTF_8));

    GetDesignDocumentsRequest requestMock = mock(GetDesignDocumentsRequest.class);
    requestQueue.add(requestMock);/*from w w w  .j a va  2s .com*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    GetDesignDocumentsResponse event = (GetDesignDocumentsResponse) eventSink.responseEvents().get(0)
            .getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.content());
    assertTrue(requestQueue.isEmpty());
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldPushSubsequentChunks() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("config", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("\n\n\n\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);/*from  ww  w .  j  a v a  2 s.  c om*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();
    assertEquals("config", configs.toBlocking().first());
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldPushMixedSizeChunksCorrectly() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("conf", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("ig\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);/*from ww w.ja  v  a2s .co m*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();

    final CountDownLatch latch = new CountDownLatch(2);
    configs.forEach(new Action1<String>() {
        @Override
        public void call(String config) {
            assertTrue(config.equals("config") || config.equals("new"));
            latch.countDown();
        }
    });

    HttpContent responseChunk3 = new DefaultHttpContent(Unpooled.copiedBuffer("\n\n\nne", CharsetUtil.UTF_8));
    HttpContent responseChunk4 = new DefaultHttpContent(Unpooled.copiedBuffer("w\n\n\n\n", CharsetUtil.UTF_8));

    channel.writeInbound(responseChunk3, responseChunk4);
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldResetStateIfStreamCloses() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("conf", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("ig\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);/*from ww w .jav a2 s  .  c o m*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();

    final CountDownLatch latch = new CountDownLatch(3);
    configs.subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            assertTrue(false);
        }

        @Override
        public void onNext(String config) {
            assertTrue(config.equals("config") || config.equals("new"));
            latch.countDown();
        }
    });

    HttpContent responseChunk3 = new DefaultHttpContent(Unpooled.copiedBuffer("\n\n\nne", CharsetUtil.UTF_8));
    HttpContent responseChunk4 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer("w\n\n\n\n", CharsetUtil.UTF_8));

    channel.writeInbound(responseChunk3, responseChunk4);
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldCloseStreamIfChannelDies() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("conf", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("ig\n\n\n\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);/*w ww  .jav  a  2 s.  c om*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();

    final CountDownLatch latch = new CountDownLatch(1);
    configs.subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(String s) {

        }
    });

    channel.pipeline().remove(handler);
    channel.disconnect().awaitUninterruptibly();
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}

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

License:Apache License

/**
 * Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs.
 *
 * @param ctx the handler context.//from   w w w  .  jav  a 2s . c o m
 * @param msg the incoming message to investigate.
 * @throws Exception if something goes wrong during negotiation.
 */
private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
    if (saslClient.isComplete()) {
        checkIsAuthed(msg);
        return;
    }

    byte[] response = new byte[msg.content().readableBytes()];
    msg.content().readBytes(response);
    byte[] evaluatedBytes = saslClient.evaluateChallenge(response);

    if (evaluatedBytes != null) {
        ByteBuf content;

        // This is needed against older server versions where the protocol does not
        // align on cram and plain, the else block is used for all the newer cram-sha*
        // mechanisms.
        //
        // Note that most likely this is only executed in the CRAM-MD5 case only, but
        // just to play it safe keep it for both mechanisms.
        if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
            String[] evaluated = new String(evaluatedBytes).split(" ");
            content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
        } else {
            content = Unpooled.wrappedBuffer(evaluatedBytes);
        }

        FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest(
                selectedMechanism.getBytes(CharsetUtil.UTF_8), Unpooled.EMPTY_BUFFER, content);
        stepRequest.setOpcode(SASL_STEP_OPCODE).setKeyLength((short) selectedMechanism.length())
                .setTotalBodyLength(content.readableBytes() + selectedMechanism.length());

        ChannelFuture future = ctx.writeAndFlush(stepRequest);
        future.addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                if (!future.isSuccess()) {
                    LOGGER.warn("Error during SASL Auth negotiation phase.", future);
                }
            }
        });
    } else {
        throw new AuthenticationException("SASL Challenge evaluation returned null.");
    }
}

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

License:Apache License

@Test
public void shouldDecodeSuccessfulGet() {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content.copy());/*w w  w  . j a v  a  2 s. c  o  m*/
    response.setCAS(123456789L);
    response.setExtras(Unpooled.buffer().writeInt(123));
    response.setExtrasLength((byte) 4);

    GetRequest requestMock = mock(GetRequest.class);
    when(requestMock.bucket()).thenReturn(BUCKET);
    requestQueue.add(requestMock);
    channel.writeInbound(response);

    assertEquals(1, eventSink.responseEvents().size());
    GetResponse event = (GetResponse) eventSink.responseEvents().get(0).getMessage();
    assertEquals(123456789L, event.cas());
    assertEquals(123, event.flags());
    assertEquals("content", event.content().toString(CHARSET));
    assertEquals(BUCKET, event.bucket());
}

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

License:Apache License

@Test
public void shouldDecodeNotFoundGet() {
    ByteBuf content = Unpooled.copiedBuffer("Not Found", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content.copy());/*from w w w.ja  v a2 s . c o m*/
    response.setStatus(BinaryMemcacheResponseStatus.KEY_ENOENT);

    GetRequest requestMock = mock(GetRequest.class);
    when(requestMock.bucket()).thenReturn(BUCKET);
    requestQueue.add(requestMock);
    channel.writeInbound(response);

    assertEquals(1, eventSink.responseEvents().size());
    GetResponse event = (GetResponse) eventSink.responseEvents().get(0).getMessage();
    assertEquals(0, event.cas());
    assertEquals(0, event.flags());
    assertEquals("Not Found", event.content().toString(CHARSET));
    assertEquals(BUCKET, event.bucket());
}

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

License:Apache License

@Test
public void shouldDecodeReplicaGetResponse() {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content.copy());/*w w  w . j a  v a  2  s.com*/
    response.setCAS(123456789L);
    response.setExtras(Unpooled.buffer().writeInt(123));
    response.setExtrasLength((byte) 4);

    ReplicaGetRequest requestMock = mock(ReplicaGetRequest.class);
    when(requestMock.bucket()).thenReturn(BUCKET);
    requestQueue.add(requestMock);
    channel.writeInbound(response);

    assertEquals(1, eventSink.responseEvents().size());
    GetResponse event = (GetResponse) eventSink.responseEvents().get(0).getMessage();
    assertEquals(123456789L, event.cas());
    assertEquals(123, event.flags());
    assertEquals("content", event.content().toString(CHARSET));
    assertEquals(BUCKET, event.bucket());
}

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

License:Apache License

@Test
public void shouldEncodeInsertRequest() {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);

    InsertRequest request = new InsertRequest("key", content.copy(), "bucket");
    request.partition((short) 512);
    channel.writeOutbound(request);// w  ww . j  a  v a2  s  .  co  m
    FullBinaryMemcacheRequest outbound = (FullBinaryMemcacheRequest) channel.readOutbound();
    assertNotNull(outbound);
    assertEquals("key", new String(outbound.getKey(), CHARSET));
    assertEquals("key".length(), outbound.getKeyLength());
    assertEquals(512, outbound.getReserved());
    assertEquals(KeyValueHandler.OP_INSERT, outbound.getOpcode());
    assertEquals(8, outbound.getExtrasLength());
    assertEquals(0, outbound.getExtras().readInt());
    assertEquals(0, outbound.getExtras().readInt());
    assertEquals(18, outbound.getTotalBodyLength());
    assertEquals(0, outbound.getCAS());
    assertEquals("content", outbound.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.releaseLater(outbound);

    request = new InsertRequest("key", content.copy(), 10, 0, "bucket");
    request.partition((short) 512);
    channel.writeOutbound(request);
    outbound = (FullBinaryMemcacheRequest) channel.readOutbound();
    assertNotNull(outbound);
    assertEquals("key", new String(outbound.getKey(), CHARSET));
    assertEquals("key".length(), outbound.getKeyLength());
    assertEquals(512, outbound.getReserved());
    assertEquals(KeyValueHandler.OP_INSERT, outbound.getOpcode());
    assertEquals(8, outbound.getExtrasLength());
    assertEquals(0, outbound.getExtras().readInt());
    assertEquals(10, outbound.getExtras().readInt());
    assertEquals(18, outbound.getTotalBodyLength());
    assertEquals("content", outbound.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.releaseLater(outbound);

    request = new InsertRequest("key", content.copy(), 0, 5, "bucket");
    request.partition((short) 512);
    channel.writeOutbound(request);
    outbound = (FullBinaryMemcacheRequest) channel.readOutbound();
    assertNotNull(outbound);
    assertEquals("key", new String(outbound.getKey(), CHARSET));
    assertEquals("key".length(), outbound.getKeyLength());
    assertEquals(512, outbound.getReserved());
    assertEquals(KeyValueHandler.OP_INSERT, outbound.getOpcode());
    assertEquals(8, outbound.getExtrasLength());
    assertEquals(5, outbound.getExtras().readInt());
    assertEquals(0, outbound.getExtras().readInt());
    assertEquals(18, outbound.getTotalBodyLength());
    assertEquals("content", outbound.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.releaseLater(outbound);

    request = new InsertRequest("key", content.copy(), 30, 99, "bucket");
    request.partition((short) 512);
    channel.writeOutbound(request);
    outbound = (FullBinaryMemcacheRequest) channel.readOutbound();
    assertNotNull(outbound);
    assertEquals("key", new String(outbound.getKey(), CHARSET));
    assertEquals("key".length(), outbound.getKeyLength());
    assertEquals(512, outbound.getReserved());
    assertEquals(KeyValueHandler.OP_INSERT, outbound.getOpcode());
    assertEquals(8, outbound.getExtrasLength());
    assertEquals(99, outbound.getExtras().readInt());
    assertEquals(30, outbound.getExtras().readInt());
    assertEquals(18, outbound.getTotalBodyLength());
    assertEquals("content", outbound.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.releaseLater(outbound);

    ReferenceCountUtil.release(content);
}