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.binary.BinaryHandler.java

License:Open Source License

private static BinaryMemcacheRequest handlePrependRequest(final PrependRequest msg) {
    String key = msg.key();//w w w.j  a v  a 2 s . co  m
    short keyLength = (short) key.length();
    BinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, Unpooled.EMPTY_BUFFER,
            msg.content());

    request.setOpcode(OP_PREPEND);
    request.setKeyLength(keyLength);
    request.setCAS(msg.cas());
    request.setTotalBodyLength(keyLength + msg.content().readableBytes());
    return request;
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandlerTest.java

License:Open Source License

@Test
public void shouldDecodeGetSuccessResponse() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse("key", Unpooled.EMPTY_BUFFER,
            content.copy());//w  w  w . j av 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");
    queue.add(requestMock);
    channel.writeInbound(response);
    channel.readInbound();

    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GetResponse inbound = (GetResponse) firedEvents.get(0);
    assertEquals(ResponseStatus.SUCCESS, inbound.status());
    assertEquals("bucket", inbound.bucket());
    assertEquals(123456789L, inbound.cas());
    assertEquals(123, inbound.flags());
    assertEquals("content", inbound.content().toString(CharsetUtil.UTF_8));
    assertTrue(queue.isEmpty());

    ReferenceCountUtil.release(content);
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandlerTest.java

License:Open Source License

@Test
public void shouldDecodeGetNotFoundResponse() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("Not Found", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse("key", Unpooled.EMPTY_BUFFER,
            content.copy());//from ww  w .jav a2  s.  c o  m
    response.setStatus(BinaryMemcacheResponseStatus.KEY_ENOENT);

    GetRequest requestMock = mock(GetRequest.class);
    when(requestMock.bucket()).thenReturn("bucket");
    queue.add(requestMock);
    channel.writeInbound(response);
    channel.readInbound();

    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GetResponse inbound = (GetResponse) firedEvents.get(0);
    assertEquals(ResponseStatus.NOT_EXISTS, inbound.status());
    assertEquals("bucket", inbound.bucket());
    assertEquals(0, inbound.cas());
    assertEquals(0, inbound.flags());
    assertEquals("Not Found", inbound.content().toString(CharsetUtil.UTF_8));
    assertTrue(queue.isEmpty());

    ReferenceCountUtil.release(content);
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandlerTest.java

License:Open Source License

@Test
public void shouldDecodeReplicaGetResponse() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse("key", Unpooled.EMPTY_BUFFER,
            content.copy());/*from  w  ww.  ja v a2s  . co m*/
    response.setCAS(123456789L);
    response.setExtras(Unpooled.buffer().writeInt(123));
    response.setExtrasLength((byte) 4);

    ReplicaGetRequest requestMock = mock(ReplicaGetRequest.class);
    when(requestMock.bucket()).thenReturn("bucket");
    queue.add(requestMock);
    channel.writeInbound(response);
    channel.readInbound();

    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GetResponse inbound = (GetResponse) firedEvents.get(0);
    assertEquals(ResponseStatus.SUCCESS, inbound.status());
    assertEquals("bucket", inbound.bucket());
    assertEquals(123456789L, inbound.cas());
    assertEquals(123, inbound.flags());
    assertEquals("content", inbound.content().toString(CharsetUtil.UTF_8));
    assertTrue(queue.isEmpty());

    ReferenceCountUtil.release(content);
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandlerTest.java

License:Open Source License

@Test
public void shouldDecodeGetBucketConfigResponse() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse("key", Unpooled.EMPTY_BUFFER,
            content.copy());/*  w w w.  j  av a  2s. c o  m*/

    GetBucketConfigRequest requestMock = mock(GetBucketConfigRequest.class);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.hostname()).thenReturn(InetAddress.getLocalHost());
    queue.add(requestMock);
    channel.writeInbound(response);
    channel.readInbound();

    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GetBucketConfigResponse inbound = (GetBucketConfigResponse) firedEvents.get(0);
    assertEquals(ResponseStatus.SUCCESS, inbound.status());
    assertEquals("bucket", inbound.bucket());
    assertEquals(InetAddress.getLocalHost(), inbound.hostname());
    assertEquals("content", inbound.content().toString(CharsetUtil.UTF_8));
    assertTrue(queue.isEmpty());

    ReferenceCountUtil.release(content);
}

From source file:com.couchbase.client.core.endpoint.binary.BinarySaslClient.java

License:Open Source License

/**
 * Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.
 *
 * @param ctx the handler context./* w  w  w.j a  v  a 2  s  . c om*/
 * @param msg the incoming message to investigate.
 * @throws Exception
 */
private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg)
        throws Exception {
    String remote = ctx.channel().remoteAddress().toString();
    String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
    if (supportedMechanisms.length == 0) {
        throw new IllegalStateException("Received empty SASL mechanisms list from server: " + remote);
    }

    saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
    selectedMechanism = saslClient.getMechanismName();
    int mechanismLength = selectedMechanism.length();
    byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[] {}) : null;
    ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload)
            : Unpooled.EMPTY_BUFFER;

    FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(selectedMechanism,
            Unpooled.EMPTY_BUFFER, payload);
    initialRequest.setOpcode(SASL_AUTH_OPCODE).setKeyLength((short) mechanismLength)
            .setTotalBodyLength(mechanismLength + payload.readableBytes());

    ctx.writeAndFlush(initialRequest);
}

From source file:com.couchbase.client.core.endpoint.binary.BinarySaslClient.java

License:Open Source License

/**
 * Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs.
 *
 * @param ctx the handler context./*from  w w  w .j  a  v a 2 s  .  c  om*/
 * @param msg the incoming message to investigate.
 * @throws Exception
 */
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) {
        String[] evaluated = new String(evaluatedBytes).split(" ");
        ByteBuf content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);

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

        ctx.writeAndFlush(stepRequest);
    } else {
        throw new IllegalStateException("SASL Challenge evaluation returned null.");
    }
}

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

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ConfigRequest msg) throws Exception {
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof FlushRequest || msg instanceof InsertBucketRequest
            || msg instanceof UpdateBucketRequest) {
        httpMethod = HttpMethod.POST;//from  w w w  .j  a v  a2s .  co m
    } else if (msg instanceof RemoveBucketRequest) {
        httpMethod = HttpMethod.DELETE;
    }

    ByteBuf content;
    if (msg instanceof InsertBucketRequest) {
        content = Unpooled.copiedBuffer(((InsertBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpdateBucketRequest) {
        content = Unpooled.copiedBuffer(((UpdateBucketRequest) 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 InsertBucketRequest || msg instanceof UpdateBucketRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    }
    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.dcp.DCPConnectionHandler.java

License:Apache License

private FullBinaryMemcacheRequest controlRequest(ChannelHandlerContext ctx, ControlParameter parameter,
        String value) {//from  w  w  w  . ja  v  a2s  .c o m
    byte[] key = parameter.value().getBytes(CharsetUtil.UTF_8);
    short keyLength = (short) key.length;
    byte[] val = value.getBytes(CharsetUtil.UTF_8);
    ByteBuf body = ctx.alloc().buffer(val.length);
    body.writeBytes(val);

    FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, Unpooled.EMPTY_BUFFER, body);
    request.setOpcode(DCPHandler.OP_CONTROL);
    request.setKeyLength(keyLength);
    request.setTotalBodyLength(keyLength + body.readableBytes());
    return request;
}

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

License:Apache License

/**
 * Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.
 *
 * @param ctx the handler context.//from w w  w.j ava2 s . com
 * @param msg the incoming message to investigate.
 * @throws Exception if something goes wrong during negotiation.
 */
private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg)
        throws Exception {
    String remote = ctx.channel().remoteAddress().toString();
    String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
    if (supportedMechanisms.length == 0) {
        throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
    }

    saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
    selectedMechanism = saslClient.getMechanismName();
    int mechanismLength = selectedMechanism.length();
    byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[] {}) : null;
    ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload)
            : Unpooled.EMPTY_BUFFER;

    FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(
            selectedMechanism.getBytes(CharsetUtil.UTF_8), Unpooled.EMPTY_BUFFER, payload);
    initialRequest.setOpcode(SASL_AUTH_OPCODE).setKeyLength((short) mechanismLength)
            .setTotalBodyLength(mechanismLength + payload.readableBytes());

    ChannelFuture future = ctx.writeAndFlush(initialRequest);
    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);
            }
        }
    });
}