Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

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

License:Open Source License

/**
 * Creates the actual protocol level request for an incoming insert request.
 *
 * @param request the incoming insert request.
 * @param ctx the channel handler context for buffer allocations.
 * @return the built protocol request.//from  w ww.java2s .co m
 */
private BinaryMemcacheRequest handleInsertRequest(final InsertRequest request,
        final ChannelHandlerContext ctx) {
    ByteBuf extras = ctx.alloc().buffer(8);
    extras.writeInt(request.flags());
    extras.writeInt(request.expiration());

    FullBinaryMemcacheRequest msg = new DefaultFullBinaryMemcacheRequest(request.key(), extras,
            request.content());

    msg.setOpcode(BinaryMemcacheOpcodes.ADD);
    msg.setKeyLength((short) request.key().length());
    msg.setTotalBodyLength(
            (short) request.key().length() + request.content().readableBytes() + extras.readableBytes());
    msg.setReserved(request.partition());
    msg.setExtrasLength((byte) extras.readableBytes());
    return msg;
}

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./* w  w w . j a va 2 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 BinaryStoreRequest} into its lower level representation.
 *
 * There are three types of store operations that need to be considered: insert, upsert and replace, which
 * directly translate to the add, set and replace binary memcached opcodes. By convention, only the replace
 * command supports setting a CAS value, even if the others theoretically would do as well (but do not provide
 * benefit in such cases).//from   w  w w . j a va2s .  c om
 *
 * Currently, the content is loaded and sent down in one batch, streaming for requests is not supported.
 *
 * @return a ready {@link BinaryMemcacheRequest}.
 */
private static BinaryMemcacheRequest handleStoreRequest(final ChannelHandlerContext ctx,
        final BinaryStoreRequest msg) {
    ByteBuf extras = ctx.alloc().buffer(8);
    extras.writeInt(msg.flags());
    extras.writeInt(msg.expiration());

    String key = msg.key();
    short keyLength = (short) key.length();
    byte extrasLength = (byte) extras.readableBytes();
    FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, extras, msg.content());

    if (msg instanceof InsertRequest) {
        request.setOpcode(OP_INSERT);
    } else if (msg instanceof UpsertRequest) {
        request.setOpcode(OP_UPSERT);
    } else if (msg instanceof ReplaceRequest) {
        request.setOpcode(OP_REPLACE);
        request.setCAS(((ReplaceRequest) msg).cas());
    } else {
        throw new IllegalArgumentException("Unknown incoming BinaryStoreRequest type " + msg.getClass());
    }

    request.setKeyLength(keyLength);
    request.setTotalBodyLength(keyLength + msg.content().readableBytes() + extrasLength);
    request.setExtrasLength(extrasLength);
    return request;
}

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

License:Open Source License

/**
 * Encodes a {@link CounterRequest} into its lower level representation.
 *
 * Depending on if the {@link CounterRequest#delta} is positive or negative, either the incr or decr memcached
 * commands are utilized. The value is converted to its absolute variant to conform with the protocol.
 *
 * @return a ready {@link BinaryMemcacheRequest}.
 *//*from www.jav a 2 s.  co m*/
private static BinaryMemcacheRequest handleCounterRequest(final ChannelHandlerContext ctx,
        final CounterRequest msg) {
    ByteBuf extras = ctx.alloc().buffer();
    extras.writeLong(Math.abs(msg.delta()));
    extras.writeLong(msg.initial());
    extras.writeInt(msg.expiry());

    String key = msg.key();
    short keyLength = (short) key.length();
    byte extrasLength = (byte) extras.readableBytes();
    BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key, extras);
    request.setOpcode(msg.delta() < 0 ? OP_COUNTER_DECR : OP_COUNTER_INCR);
    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 TouchRequest} into its lower level representation.
 *
 * @return a ready {@link BinaryMemcacheRequest}.
 *///from w  w w  .  j a  v  a  2  s.c o  m
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 .  jav a  2  s .  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;/* w  w w.  ja  v  a2s  . 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./*  w w  w . j a  va  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.config.ConfigHandler.java

License:Apache License

@Override
protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx, final HttpObject msg)
        throws Exception {
    ConfigRequest request = currentRequest();
    CouchbaseResponse response = null;//from   www  .  j  a  v a  2s .  c o m

    if (msg instanceof HttpResponse) {
        responseHeader = (HttpResponse) msg;

        if (request instanceof BucketStreamingRequest) {
            response = handleBucketStreamingResponse(ctx, responseHeader);
        }

        if (responseContent != null) {
            responseContent.clear();
        } else {
            responseContent = ctx.alloc().buffer();
        }
    }

    if (msg instanceof HttpContent) {
        responseContent.writeBytes(((HttpContent) msg).content());
        if (streamingConfigObservable != null) {
            maybePushConfigChunk();
        }
    }

    if (msg instanceof LastHttpContent) {
        if (request instanceof BucketStreamingRequest) {
            if (streamingConfigObservable != null) {
                streamingConfigObservable.onCompleted();
                streamingConfigObservable = null;
            }
            finishedDecoding();
            return null;
        }

        ResponseStatus status = ResponseStatusConverter.fromHttp(responseHeader.getStatus().code());
        String body = responseContent.readableBytes() > 0 ? responseContent.toString(CHARSET)
                : responseHeader.getStatus().reasonPhrase();

        if (request instanceof BucketConfigRequest) {
            response = new BucketConfigResponse(body, status);
        } else if (request instanceof ClusterConfigRequest) {
            response = new ClusterConfigResponse(body, status);
        } else if (request instanceof BucketsConfigRequest) {
            response = new BucketsConfigResponse(body, status);
        } else if (request instanceof GetDesignDocumentsRequest) {
            response = new GetDesignDocumentsResponse(body, status, request);
        } else if (request instanceof RemoveBucketRequest) {
            response = new RemoveBucketResponse(status);
        } else if (request instanceof InsertBucketRequest) {
            response = new InsertBucketResponse(body, status);
        } else if (request instanceof UpdateBucketRequest) {
            response = new UpdateBucketResponse(body, status);
        } else if (request instanceof FlushRequest) {
            boolean done = responseHeader.getStatus().code() != 201;
            response = new FlushResponse(done, body, status);
        }

        finishedDecoding();
    }

    return response;
}

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;
}