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.cluster.SubdocumentMessageTest.java

License:Apache License

@Test
public void shouldHaveIndividualResultsOnFullySuccessfulMultiLookup() {
    String expected = "EXIST(sub): SUCCESS\n" + "GET(sub.array[1]): SUCCESS = 2\n";

    SubMultiLookupRequest request = new SubMultiLookupRequest(testSubKey, bucket(),
            new LookupCommand(Lookup.EXIST, "sub"), new LookupCommand(Lookup.GET, "sub.array[1]"));

    MultiLookupResponse response = cluster().<MultiLookupResponse>send(request).toBlocking().single();
    assertEquals(Unpooled.EMPTY_BUFFER, response.content());
    StringBuilder body = new StringBuilder();
    for (MultiResult r : response.responses()) {
        body.append(r.toString()).append('\n');
        ReferenceCountUtil.release(r.value());
    }// www.ja v  a  2  s.c om

    assertTrue(response.cas() != 0);
    assertEquals(ResponseStatus.SUCCESS, response.status());
    assertEquals(expected, body.toString());
}

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);// w  w w  .ja  va  2s  .co  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  w  w .  j  a v a 2 s .  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);

    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.loader.CarrierLoaderTest.java

License:Apache License

@Test
public void shouldThrowExceptionIfNotDiscovered() {
    ClusterFacade cluster = mock(ClusterFacade.class);
    Observable<CouchbaseResponse> response = Observable
            .just((CouchbaseResponse) new GetBucketConfigResponse(ResponseStatus.FAILURE,
                    KeyValueStatus.ERR_NOT_FOUND.code(), "bucket", Unpooled.EMPTY_BUFFER, host));
    when(cluster.send(isA(GetBucketConfigRequest.class))).thenReturn(response);

    CarrierLoader loader = new CarrierLoader(cluster, environment);
    Observable<String> configObservable = loader.discoverConfig("bucket", "password", host);
    try {/*w w w  .  j ava  2s. c  om*/
        configObservable.toBlocking().single();
        assertTrue(false);
    } catch (IllegalStateException ex) {
        assertEquals("Bucket config response did not return with success.", ex.getMessage());
    } catch (Exception ex) {
        assertTrue("Unexpected exception: " + ex, false);
    }
}

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

License:Open Source 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 a v a  2  s. co m
 * @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 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,
            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.BinaryAuthHandler.java

License:Open Source License

/**
 * Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs.
 *
 * @param ctx the handler context./* w ww  . j  a  v  a 2s . co  m*/
 * @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 AuthenticationException("SASL Challenge evaluation returned null.");
    }
}

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

License:Open Source License

/**
 * Encodes a {@link GetRequest} into its lower level representation.
 *
 * Depending on the flags set on the {@link GetRequest}, the appropriate opcode gets chosen. Currently, a regular
 * get, as well as "get and touch" and "get and lock" are supported. Latter variants have server-side side-effects
 * but do not differ in response behavior.
 *
 * @param ctx the {@link ChannelHandlerContext} to use for allocation and others.
 * @param msg the incoming message.// www  .java2  s  .c  om
 * @return a ready {@link BinaryMemcacheRequest}.
 */
private static BinaryMemcacheRequest handleGetRequest(final ChannelHandlerContext ctx, final GetRequest msg) {
    byte opcode;
    ByteBuf extras;
    if (msg.lock()) {
        opcode = OP_GET_AND_LOCK;
        extras = ctx.alloc().buffer().writeInt(msg.expiry());
    } else if (msg.touch()) {
        opcode = OP_GET_AND_TOUCH;
        extras = ctx.alloc().buffer().writeInt(msg.expiry());
    } else {
        opcode = OP_GET;
        extras = Unpooled.EMPTY_BUFFER;
    }

    String key = msg.key();
    short keyLength = (short) key.length();
    byte extrasLength = (byte) extras.readableBytes();
    BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key);
    request.setOpcode(opcode).setKeyLength(keyLength).setExtras(extras).setExtrasLength(extrasLength)
            .setTotalBodyLength(keyLength + extrasLength);
    return request;
}

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

License:Open Source License

/**
 * Encodes a {@link ObserveRequest} into its lower level representation.
 *
 * @return a ready {@link BinaryMemcacheRequest}.
 *//*from  www  . ja v  a 2 s  . co m*/
private static BinaryMemcacheRequest handleObserveRequest(final ChannelHandlerContext ctx,
        final ObserveRequest msg) {
    String key = msg.key();
    ByteBuf content = ctx.alloc().buffer();
    content.writeShort(msg.partition());
    content.writeShort(key.length());
    content.writeBytes(key.getBytes(CHARSET));

    BinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest("", Unpooled.EMPTY_BUFFER, content);
    request.setOpcode(OP_OBSERVE);
    request.setTotalBodyLength(content.readableBytes());
    return request;
}

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

License:Open Source License

private static BinaryMemcacheRequest handleAppendRequest(final AppendRequest msg) {
    String key = msg.key();/* w  w w.j  a va  2 s.  c  o m*/
    short keyLength = (short) key.length();
    BinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, Unpooled.EMPTY_BUFFER,
            msg.content());

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