List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
private static BinaryMemcacheRequest handleGetAllMutationTokensRequest(ChannelHandlerContext ctx, GetAllMutationTokensRequest msg) { BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(EMPTY_BYTES); ByteBuf extras; switch (msg.partitionState()) { case ANY:/*w w w . j av a 2s . com*/ extras = Unpooled.EMPTY_BUFFER; break; case ACTIVE: case REPLICA: case PENDING: case DEAD: default: extras = ctx.alloc().buffer().writeInt(msg.partitionState().value()); } byte extrasLength = (byte) extras.readableBytes(); request.setOpcode(OP_GET_ALL_MUTATION_TOKENS).setExtras(extras).setExtrasLength(extrasLength) .setTotalBodyLength(extrasLength); return request; }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all multi lookup response messages. * * @param request the current request.//from w w w . j a v a 2 s . c o m * @param msg the current response message. * @param ctx the handler context. * @param status the response status code. * @return the decoded response or null if it wasn't a subdocument multi lookup. */ private static CouchbaseResponse handleSubdocumentMultiLookupResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status) { if (!(request instanceof BinarySubdocMultiLookupRequest)) return null; BinarySubdocMultiLookupRequest subdocRequest = (BinarySubdocMultiLookupRequest) request; short statusCode = msg.getStatus(); long cas = msg.getCAS(); String bucket = request.bucket(); ByteBuf body = msg.content(); List<MultiResult<Lookup>> responses; if (status.isSuccess() || ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) { long bodyLength = body.readableBytes(); List<LookupCommand> commands = subdocRequest.commands(); responses = new ArrayList<MultiResult<Lookup>>(commands.size()); for (LookupCommand cmd : commands) { if (msg.content().readableBytes() < 6) { body.release(); throw new IllegalStateException("Expected " + commands.size() + " lookup responses, only got " + responses.size() + ", total of " + bodyLength + " bytes"); } short cmdStatus = body.readShort(); int valueLength = body.readInt(); ByteBuf value = ctx.alloc().buffer(valueLength, valueLength); value.writeBytes(body, valueLength); responses.add(MultiResult.create(cmdStatus, ResponseStatusConverter.fromBinary(cmdStatus), cmd.path(), cmd.lookup(), value)); } } else { responses = Collections.emptyList(); } body.release(); return new MultiLookupResponse(status, statusCode, bucket, responses, subdocRequest, cas); }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all other response messages. * * @param request the current request.//from ww w . ja v a 2 s. c o m * @param msg the current response message. * @param status the response status code. * @return the decoded response or null if none did match. */ private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ResponseStatus status, boolean seqOnMutation, String remoteHostname) { CouchbaseResponse response = null; ByteBuf content = msg.content(); long cas = msg.getCAS(); short statusCode = msg.getStatus(); String bucket = request.bucket(); if (request instanceof UnlockRequest) { response = new UnlockResponse(status, statusCode, bucket, content, request); } else if (request instanceof TouchRequest) { response = new TouchResponse(status, statusCode, bucket, content, request); } else if (request instanceof AppendRequest) { MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request); } else if (request instanceof PrependRequest) { MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request); } else if (request instanceof KeepAliveRequest) { releaseContent(content); response = new KeepAliveResponse(status, statusCode, request); } else if (request instanceof CounterRequest) { long value = status.isSuccess() ? content.readLong() : 0; releaseContent(content); MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request); } else if (request instanceof StatRequest) { String key = new String(msg.getKey(), CHARSET); String value = content.toString(CHARSET); releaseContent(content); response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request); } else if (request instanceof GetAllMutationTokensRequest) { // 2 bytes for partition ID, and 8 bytes for sequence number MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10]; for (int i = 0; i < mutationTokens.length; i++) { mutationTokens[i] = new MutationToken((long) content.readShort(), 0, content.readLong(), request.bucket()); } releaseContent(content); response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request); } else if (request instanceof ObserveRequest) { byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value(); long observedCas = 0; if (status.isSuccess()) { short keyLength = content.getShort(2); observed = content.getByte(keyLength + 4); observedCas = content.getLong(keyLength + 5); } releaseContent(content); response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(), observedCas, bucket, request); } else if (request instanceof ObserveSeqnoRequest) { if (status.isSuccess()) { byte format = content.readByte(); switch (format) { case 0: response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), content.readShort(), content.readLong(), content.readLong(), content.readLong(), status, statusCode, bucket, request); break; case 1: response = new FailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), content.readShort(), content.readLong(), content.readLong(), content.readLong(), content.readLong(), content.readLong(), status, statusCode, bucket, request); break; default: throw new IllegalStateException("Unknown format for observe-seq: " + format); } } else { response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0, 0, 0, 0, status, statusCode, bucket, request); } releaseContent(content); } return response; }
From source file:com.couchbase.client.core.endpoint.query.QueryHandler.java
License:Apache License
@Override protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final QueryRequest msg) throws Exception { FullHttpRequest request;//from www . j a va 2s. co m if (msg instanceof GenericQueryRequest) { GenericQueryRequest queryRequest = (GenericQueryRequest) msg; request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/query"); request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent()); if (queryRequest.isJsonFormat()) { request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); } ByteBuf query = ctx.alloc().buffer(((GenericQueryRequest) msg).query().length()); query.writeBytes(((GenericQueryRequest) msg).query().getBytes(CHARSET)); request.headers().add(HttpHeaders.Names.CONTENT_LENGTH, query.readableBytes()); request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx)); request.content().writeBytes(query); query.release(); } else if (msg instanceof KeepAliveRequest) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/admin/ping"); request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent()); request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx)); return request; } else { throw new IllegalArgumentException("Unknown incoming QueryRequest type " + msg.getClass()); } addHttpBasicAuth(ctx, request, msg.bucket(), msg.password()); return request; }
From source file:com.couchbase.client.core.endpoint.search.SearchHandler.java
License:Apache License
@Override protected HttpRequest encodeRequest(ChannelHandlerContext ctx, SearchRequest msg) throws Exception { HttpMethod httpMethod = HttpMethod.GET; if (msg instanceof UpsertSearchIndexRequest) { httpMethod = HttpMethod.PUT;/* w ww . j a va 2 s . c om*/ } else if (msg instanceof RemoveSearchIndexRequest) { httpMethod = HttpMethod.DELETE; } else if (msg instanceof SearchQueryRequest) { httpMethod = HttpMethod.POST; } ByteBuf content; if (msg instanceof UpsertSearchIndexRequest) { content = Unpooled.copiedBuffer(((UpsertSearchIndexRequest) msg).payload(), CharsetUtil.UTF_8); } else if (msg instanceof SearchQueryRequest) { content = Unpooled.copiedBuffer(((SearchQueryRequest) 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 UpsertSearchIndexRequest || msg instanceof SearchQueryRequest) { request.headers().set(HttpHeaders.Names.ACCEPT, "*/*"); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); } 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.util.ByteBufJsonHelper.java
License:Apache License
/** * Find the number of bytes until next occurrence of the character c * from the current {@link ByteBuf#readerIndex() readerIndex} in buf, * with the twist that if this occurrence is prefixed by the prefix * character, we try to find another occurrence. * * @param buf the {@link ByteBuf buffer} to look into. * @param c the character to search for. * @param prefix the character to trigger a retry. * @return the position of the first occurrence of c that is not prefixed by prefix * or -1 if none found./* w ww .ja va 2 s .c om*/ */ public static final int findNextCharNotPrefixedBy(ByteBuf buf, char c, char prefix) { int found = buf.bytesBefore((byte) c); if (found < 1) { return found; } else { int from; while (found > -1 && (char) buf.getByte(buf.readerIndex() + found - 1) == prefix) { //advance from from = buf.readerIndex() + found + 1; //search again int next = buf.bytesBefore(from, buf.readableBytes() - from + buf.readerIndex(), (byte) c); if (next == -1) { return -1; } else { found += next + 1; } } return found; } }
From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java
License:Apache License
@Override protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ViewRequest msg) throws Exception { if (msg instanceof KeepAliveRequest) { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.HEAD, "/", Unpooled.EMPTY_BUFFER);// w w w .j a v a2s. c o m request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent()); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0); return request; } StringBuilder path = new StringBuilder(); HttpMethod method = HttpMethod.GET; ByteBuf content = null; if (msg instanceof ViewQueryRequest) { ViewQueryRequest queryMsg = (ViewQueryRequest) msg; path.append("/").append(msg.bucket()).append("/_design/"); path.append(queryMsg.development() ? "dev_" + queryMsg.design() : queryMsg.design()); if (queryMsg.spatial()) { path.append("/_spatial/"); } else { path.append("/_view/"); } path.append(queryMsg.view()); int queryLength = queryMsg.query() == null ? 0 : queryMsg.query().length(); int keysLength = queryMsg.keys() == null ? 0 : queryMsg.keys().length(); boolean hasQuery = queryLength > 0; boolean hasKeys = keysLength > 0; if (hasQuery || hasKeys) { if (queryLength + keysLength < MAX_GET_LENGTH) { //the query is short enough for GET //it has query, query+keys or keys only if (hasQuery) { path.append("?").append(queryMsg.query()); if (hasKeys) { path.append("&keys=").append(encodeKeysGet(queryMsg.keys())); } } else { //it surely has keys if not query path.append("?keys=").append(encodeKeysGet(queryMsg.keys())); } } else { //the query is too long for GET, use the keys as JSON body if (hasQuery) { path.append("?").append(queryMsg.query()); } String keysContent = encodeKeysPost(queryMsg.keys()); //switch to POST method = HttpMethod.POST; //body is "keys" but in JSON content = ctx.alloc().buffer(keysContent.length()); content.writeBytes(keysContent.getBytes(CHARSET)); } } } else if (msg instanceof GetDesignDocumentRequest) { GetDesignDocumentRequest queryMsg = (GetDesignDocumentRequest) msg; path.append("/").append(msg.bucket()).append("/_design/"); path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name()); } else if (msg instanceof UpsertDesignDocumentRequest) { method = HttpMethod.PUT; UpsertDesignDocumentRequest queryMsg = (UpsertDesignDocumentRequest) msg; path.append("/").append(msg.bucket()).append("/_design/"); path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name()); content = Unpooled.copiedBuffer(queryMsg.body(), CHARSET); } else if (msg instanceof RemoveDesignDocumentRequest) { method = HttpMethod.DELETE; RemoveDesignDocumentRequest queryMsg = (RemoveDesignDocumentRequest) msg; path.append("/").append(msg.bucket()).append("/_design/"); path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name()); } else { throw new IllegalArgumentException("Unknown incoming ViewRequest type " + msg.getClass()); } if (content == null) { content = Unpooled.buffer(0); } FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, path.toString(), content); request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent()); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx)); addHttpBasicAuth(ctx, request, msg.bucket(), msg.password()); return request; }
From source file:com.couchbase.client.core.message.kv.subdoc.multi.SubMultiLookupRequest.java
License:Apache License
private static ByteBuf encode(List<LookupCommand> commands) { CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(commands.size()); //FIXME pooled allocator? for (LookupCommand command : commands) { byte[] pathBytes = command.path().getBytes(CharsetUtil.UTF_8); short pathLength = (short) pathBytes.length; ByteBuf commandBuf = Unpooled.buffer(4 + pathLength); //FIXME a way of using the pooled allocator? commandBuf.writeByte(command.opCode()); commandBuf.writeByte(0); //no flags supported for lookup commandBuf.writeShort(pathLength); //no value length commandBuf.writeBytes(pathBytes); compositeBuf.addComponent(commandBuf); compositeBuf.writerIndex(compositeBuf.writerIndex() + commandBuf.readableBytes()); }/*from w w w . ja va2 s . c o m*/ return compositeBuf; }
From source file:com.couchbase.client.core.message.kv.subdoc.multi.SubMultiMutationRequest.java
License:Apache License
private static ByteBuf encode(List<MutationCommand> commands) { //FIXME a way of using the pooled allocator? CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(commands.size()); for (MutationCommand command : commands) { byte[] pathBytes = command.path().getBytes(CharsetUtil.UTF_8); short pathLength = (short) pathBytes.length; ByteBuf commandBuf = Unpooled.buffer(4 + pathLength + command.fragment().readableBytes()); commandBuf.writeByte(command.opCode()); if (command.createIntermediaryPath()) { commandBuf.writeByte(KeyValueHandler.SUBDOC_BITMASK_MKDIR_P); //0 | SUBDOC_BITMASK_MKDIR_P } else {//from ww w .j av a2s .com commandBuf.writeByte(0); } commandBuf.writeShort(pathLength); commandBuf.writeInt(command.fragment().readableBytes()); commandBuf.writeBytes(pathBytes); //copy the fragment but don't move indexes (in case it is retained and reused) commandBuf.writeBytes(command.fragment(), command.fragment().readerIndex(), command.fragment().readableBytes()); //eagerly release the fragment once it's been copied command.fragment().release(); //add the command to the composite buffer compositeBuf.addComponent(commandBuf); compositeBuf.writerIndex(compositeBuf.writerIndex() + commandBuf.readableBytes()); } return compositeBuf; }
From source file:com.couchbase.client.core.message.kv.subdoc.simple.AbstractSubdocRequest.java
License:Apache License
/** * Creates a new {@link AbstractSubdocRequest}. * * @param key the key of the document. * @param path the subdocument path to consider inside the document. * @param bucket the bucket of the document. * @param observable the observable which receives responses. * @param restOfContent the optional remainder of the {@link #content()} of the final protocol message, or null if not applicable * @throws NullPointerException if the path is null (see {@link #EXCEPTION_NULL_PATH}) *//*www. jav a 2 s . c om*/ public AbstractSubdocRequest(String key, String path, String bucket, Subject<CouchbaseResponse, CouchbaseResponse> observable, ByteBuf... restOfContent) { super(key, bucket, null, observable); this.path = path; ByteBuf pathByteBuf; if (path == null || path.isEmpty()) { pathByteBuf = Unpooled.EMPTY_BUFFER; } else { pathByteBuf = Unpooled.wrappedBuffer(path.getBytes(CharsetUtil.UTF_8)); } this.pathLength = pathByteBuf.readableBytes(); this.content = createContent(pathByteBuf, restOfContent); //checking nullity here allows to release all of restOfContent through cleanUpAndThrow releasing content() if (this.path == null) { cleanUpAndThrow(EXCEPTION_NULL_PATH); } }