List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
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;//from w w w . j av a 2 s. c o m switch (msg.partitionState()) { case ANY: 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
private static BinaryMemcacheRequest handleSubdocumentRequest(ChannelHandlerContext ctx, BinarySubdocRequest msg) {//from w ww. j a va 2s. c om byte[] key = msg.keyBytes(); short keyLength = (short) key.length; ByteBuf extras = ctx.alloc().buffer(3, 7); //extras can be 7 bytes if there is an expiry byte extrasLength = 3; //by default 2 bytes for pathLength + 1 byte for "command" flags extras.writeShort(msg.pathLength()); long cas = 0L; if (msg instanceof BinarySubdocMutationRequest) { BinarySubdocMutationRequest mut = (BinarySubdocMutationRequest) msg; //for now only possible command flag is MKDIR_P (and it makes sense in mutations only) if (mut.createIntermediaryPath()) { extras.writeByte(0 | SUBDOC_BITMASK_MKDIR_P); } else { extras.writeByte(0); } if (mut.expiration() != 0L) { extrasLength = 7; extras.writeInt(mut.expiration()); } cas = mut.cas(); } else { extras.writeByte(0); } FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, extras, msg.content()); request.setOpcode(msg.opcode()).setKeyLength(keyLength).setExtrasLength(extrasLength) .setTotalBodyLength(keyLength + msg.content().readableBytes() + extrasLength).setCAS(cas); return request; }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
private static BinaryMemcacheRequest handleSubdocumentMultiMutationRequest(ChannelHandlerContext ctx, BinarySubdocMultiMutationRequest msg) { byte[] key = msg.keyBytes(); short keyLength = (short) key.length; byte extrasLength = 0; ByteBuf extras = Unpooled.EMPTY_BUFFER; if (msg.expiration() != 0L) { extrasLength = 4;//from w w w . jav a 2 s . co m extras = ctx.alloc().buffer(4, 4); extras.writeInt(msg.expiration()); } FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, extras, msg.content()); request.setOpcode(OP_SUB_MULTI_MUTATION).setCAS(msg.cas()).setKeyLength(keyLength) .setExtrasLength(extrasLength) .setTotalBodyLength(keyLength + msg.content().readableBytes() + 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 ww.j a v a 2 s .com*/ * @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 multi mutation response messages. * * @param request the current request.//w w w .j a v a 2 s .co 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 handleSubdocumentMultiMutationResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status, boolean seqOnMutation) { if (!(request instanceof BinarySubdocMultiMutationRequest)) return null; BinarySubdocMultiMutationRequest subdocRequest = (BinarySubdocMultiMutationRequest) request; long cas = msg.getCAS(); short statusCode = msg.getStatus(); String bucket = request.bucket(); MutationToken mutationToken = null; if (msg.getExtrasLength() > 0) { mutationToken = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); } MultiMutationResponse response; ByteBuf body = msg.content(); List<MultiResult<Mutation>> responses; if (status.isSuccess()) { List<MutationCommand> commands = subdocRequest.commands(); responses = new ArrayList<MultiResult<Mutation>>(commands.size()); //MB-17842: Mutations can have a value, so there could be individual results //but only mutation commands that provide a value will have an explicit result in the binary response. //However, we still want MutationResult for all of the commands ListIterator<MutationCommand> it = commands.listIterator(); int explicitResultSize = 0; //as long as there is an explicit response to read... while (msg.content().readableBytes() >= 7) { explicitResultSize++; //...read the data byte responseIndex = body.readByte(); short responseStatus = body.readShort(); //will this always be SUCCESS? int responseLength = body.readInt(); ByteBuf responseValue; if (responseLength > 0) { responseValue = ctx.alloc().buffer(responseLength, responseLength); responseValue.writeBytes(body, responseLength); } else { responseValue = Unpooled.EMPTY_BUFFER; //can an explicit response be 0-length (empty)? } //...sanity check response so subsequent loop don't run forever if (it.nextIndex() > responseIndex) { body.release(); throw new IllegalStateException("Unable to interpret multi mutation response, responseIndex = " + responseIndex + " while next available command was #" + it.nextIndex()); } ///...catch up on all commands before current one that didn't get an explicit response while (it.nextIndex() < responseIndex) { MutationCommand noResultCommand = it.next(); responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS, noResultCommand.path(), noResultCommand.mutation(), Unpooled.EMPTY_BUFFER)); } //...then process the one that did get an explicit response MutationCommand cmd = it.next(); responses.add(MultiResult.create(responseStatus, ResponseStatusConverter.fromBinary(responseStatus), cmd.path(), cmd.mutation(), responseValue)); } //...and finally the remainder of commands after the last one that got an explicit response: while (it.hasNext()) { MutationCommand noResultCommand = it.next(); responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS, noResultCommand.path(), noResultCommand.mutation(), Unpooled.EMPTY_BUFFER)); } if (responses.size() != commands.size()) { body.release(); throw new IllegalStateException( "Multi mutation spec size and result size differ: " + commands.size() + " vs " + responses.size() + ", including " + explicitResultSize + " explicit results"); } response = new MultiMutationResponse(bucket, subdocRequest, cas, mutationToken, responses); } else if (ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) { //MB-17842: order of index and status has been swapped byte firstErrorIndex = body.readByte(); short firstErrorCode = body.readShort(); response = new MultiMutationResponse(status, statusCode, bucket, firstErrorIndex, firstErrorCode, subdocRequest, cas, mutationToken); } else { response = new MultiMutationResponse(status, statusCode, bucket, subdocRequest, cas, mutationToken); } body.release(); 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;//w w w . j ava2 s . c o 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.query.QueryHandler.java
License:Apache License
@Override protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx, final HttpObject msg) throws Exception { CouchbaseResponse response = null;/*w w w . j a v a 2s. co m*/ if (msg instanceof HttpResponse) { responseHeader = (HttpResponse) msg; if (responseContent != null) { responseContent.clear(); } else { responseContent = ctx.alloc().buffer(); } } if (currentRequest() instanceof KeepAliveRequest) { if (msg instanceof LastHttpContent) { response = new KeepAliveResponse( ResponseStatusConverter.fromHttp(responseHeader.getStatus().code()), currentRequest()); responseContent.clear(); responseContent.discardReadBytes(); finishedDecoding(); } } else if (msg instanceof HttpContent) { responseContent.writeBytes(((HttpContent) msg).content()); boolean lastChunk = msg instanceof LastHttpContent; if (currentRequest() instanceof GenericQueryRequest) { if (queryRowObservable == null) { //still in initial parsing response = handleGenericQueryResponse(lastChunk); //null response indicates need for more data before continuing parsing if (response != null) { parseQueryResponse(lastChunk); } } else { parseQueryResponse(lastChunk); } } } return response; }
From source file:com.couchbase.client.core.endpoint.search.SearchHandler.java
License:Apache License
@Override protected CouchbaseResponse decodeResponse(ChannelHandlerContext ctx, HttpObject msg) throws Exception { SearchRequest request = currentRequest(); CouchbaseResponse response = null;//from w w w .jav a 2s . c om if (msg instanceof HttpResponse) { responseHeader = (HttpResponse) msg; if (responseContent != null) { responseContent.clear(); } else { responseContent = ctx.alloc().buffer(); } } if (msg instanceof HttpContent) { responseContent.writeBytes(((HttpContent) msg).content()); } if (msg instanceof LastHttpContent) { ResponseStatus status = ResponseStatusConverter.fromHttp(responseHeader.getStatus().code()); String body = responseContent.readableBytes() > 0 ? responseContent.toString(CHARSET) : responseHeader.getStatus().reasonPhrase(); if (request instanceof UpsertSearchIndexRequest) { response = new UpsertSearchIndexResponse(body, status); } else if (request instanceof GetSearchIndexRequest) { response = new GetSearchIndexResponse(body, status); } else if (request instanceof RemoveSearchIndexRequest) { response = new RemoveSearchIndexResponse(body, status); } else if (request instanceof SearchQueryRequest) { response = new SearchQueryResponse(body, status); } finishedDecoding(); } return response; }
From source file:com.couchbase.client.core.endpoint.view.ViewCodec.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> in) throws Exception { if (currentRequest == null) { currentRequest = queue.poll();/*from w w w . j a v a 2s. com*/ currentChunk = ctx.alloc().buffer(); } if (currentRequest.equals(ViewQueryRequest.class)) { handleViewQueryResponse(ctx, msg, in); } else { throw new IllegalStateException("Got a response message for a request that was not sent." + msg); } }
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);/*from w w w . j ava 2 s. c om*/ 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; }