Example usage for io.netty.buffer ByteBuf readableBytes

List of usage examples for io.netty.buffer ByteBuf readableBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readableBytes.

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

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

License:Open Source License

/**
 * Encodes a {@link TouchRequest} into its lower level representation.
 *
 * @return a ready {@link BinaryMemcacheRequest}.
 *//*from w  w w  . j  av  a2 s  .c om*/
private static BinaryMemcacheRequest handleTouchRequest(final ChannelHandlerContext ctx,
        final TouchRequest msg) {
    ByteBuf extras = ctx.alloc().buffer();
    extras.writeInt(msg.expiry());

    String key = msg.key();
    short keyLength = (short) key.length();
    byte extrasLength = (byte) extras.readableBytes();
    BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key);
    request.setExtras(extras);
    request.setOpcode(OP_TOUCH);
    request.setKeyLength(keyLength);
    request.setTotalBodyLength(keyLength + extrasLength);
    request.setExtrasLength(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}.
 *//* w  w  w .java2s .  c o 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

@Override
protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx,
        final FullBinaryMemcacheResponse msg) throws Exception {
    BinaryRequest request = currentRequest();
    ResponseStatus status = convertStatus(msg.getStatus());

    CouchbaseResponse response;//from  ww w .j av  a 2s .  c om
    ByteBuf content = msg.content().copy();
    long cas = msg.getCAS();
    String bucket = request.bucket();
    if (request instanceof GetRequest || request instanceof ReplicaGetRequest) {
        int flags = 0;
        if (msg.getExtrasLength() > 0) {
            final ByteBuf extrasReleased = msg.getExtras();
            final ByteBuf extras = ctx.alloc().buffer(msg.getExtrasLength());
            extras.writeBytes(extrasReleased, extrasReleased.readerIndex(), extrasReleased.readableBytes());
            flags = extras.getInt(0);
            extras.release();
        }
        response = new GetResponse(status, cas, flags, bucket, content, request);
    } else if (request instanceof GetBucketConfigRequest) {
        response = new GetBucketConfigResponse(status, bucket, content,
                ((GetBucketConfigRequest) request).hostname());
    } else if (request instanceof InsertRequest) {
        response = new InsertResponse(status, cas, bucket, content, request);
    } else if (request instanceof UpsertRequest) {
        response = new UpsertResponse(status, cas, bucket, content, request);
    } else if (request instanceof ReplaceRequest) {
        response = new ReplaceResponse(status, cas, bucket, content, request);
    } else if (request instanceof RemoveRequest) {
        response = new RemoveResponse(status, bucket, content, request);
    } else if (request instanceof CounterRequest) {
        response = new CounterResponse(status, bucket, msg.content().readLong(), cas, request);
    } else if (request instanceof UnlockRequest) {
        response = new UnlockResponse(status, bucket, content, request);
    } else if (request instanceof TouchRequest) {
        response = new TouchResponse(status, bucket, content, request);
    } else if (request instanceof ObserveRequest) {
        byte observed = content.getByte(content.getShort(2) + 4);
        response = new ObserveResponse(status, observed, ((ObserveRequest) request).master(), bucket, content,
                request);
    } else if (request instanceof AppendRequest) {
        response = new AppendResponse(status, cas, bucket, content, request);
    } else if (request instanceof PrependRequest) {
        response = new PrependResponse(status, cas, bucket, content, request);
    } else {
        throw new IllegalStateException(
                "Unhandled request/response pair: " + request.getClass() + "/" + msg.getClass());
    }

    return response;
}

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.//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 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./*  w w  w .  ja v  a  2 s.  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 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  ww .j  a  v  a 2  s  .  com*/
    } 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.DCPConnection.java

License:Apache License

private BinaryMemcacheRequest createBufferAcknowledgmentRequest(ChannelHandlerContext ctx, int bufferBytes) {
    ByteBuf extras = ctx.alloc().buffer(4).writeInt(bufferBytes);
    BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(new byte[] {}, extras);
    request.setOpcode(DCPHandler.OP_BUFFER_ACK);
    request.setExtrasLength((byte) extras.readableBytes());
    request.setTotalBodyLength(extras.readableBytes());
    return request;
}

From source file:com.couchbase.client.core.endpoint.dcp.DCPConnectionHandler.java

License:Apache License

/**
 * Creates a DCP Open Connection Request.
 *
 * @param ctx the channel handler context.
 * @return a converted {@link BinaryMemcacheRequest}.
 *///from  w w  w  .j av  a 2  s.  c  om
private BinaryMemcacheRequest handleOpenConnectionRequest(final ChannelHandlerContext ctx) {
    ByteBuf extras = ctx.alloc().buffer(8);
    extras.writeInt(0) // sequence number
            .writeInt(ConnectionType.CONSUMER.flags());

    byte[] key = connectionName.getBytes(CharsetUtil.UTF_8);
    byte extrasLength = (byte) extras.readableBytes();
    short keyLength = (short) key.length;

    BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key, extras);
    request.setOpcode(DCPHandler.OP_OPEN_CONNECTION);
    request.setKeyLength(keyLength);
    request.setExtrasLength(extrasLength);
    request.setTotalBodyLength(keyLength + extrasLength);

    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 .  j a va  2 s  .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.dcp.DCPHandler.java

License:Apache License

/**
 * Creates a DCP Stream Request.//from   ww w .  j ava2  s  .com
 *
 * See the [Protocol Description](https://github.com/couchbaselabs/dcp-documentation/blob/master/documentation/
 * commands/stream-request.md) for more details.
 *
 * @param ctx the channel handler context.
 * @param msg the stream request message.
 * @return a converted {@link BinaryMemcacheRequest}.
 */
private BinaryMemcacheRequest handleStreamRequestRequest(final ChannelHandlerContext ctx,
        final StreamRequestRequest msg) {
    ByteBuf extras = ctx.alloc().buffer(48);
    extras.writeInt(0) // flags
            .writeInt(0) // reserved
            .writeLong(msg.startSequenceNumber()) // start sequence number
            .writeLong(msg.endSequenceNumber()) // end sequence number
            .writeLong(msg.vbucketUUID()) // vbucket UUID
            .writeLong(msg.snapshotStartSequenceNumber()) // snapshot start sequence number
            .writeLong(msg.snapshotEndSequenceNumber()); // snapshot end sequence number

    byte extrasLength = (byte) extras.readableBytes();

    BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(extras);
    request.setOpcode(OP_STREAM_REQUEST);
    request.setExtrasLength(extrasLength);
    request.setTotalBodyLength(extrasLength);

    return request;
}