List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:com.corundumstudio.socketio.protocol.PacketEncoder.java
License:Apache License
public void encodeJsonP(Integer jsonpIndex, Queue<Packet> packets, ByteBuf out, ByteBufAllocator allocator, int limit) throws IOException { boolean jsonpMode = jsonpIndex != null; ByteBuf buf = allocateBuffer(allocator); int i = 0;/* w w w .jav a 2 s. co m*/ while (true) { Packet packet = packets.poll(); if (packet == null || i == limit) { break; } ByteBuf packetBuf = allocateBuffer(allocator); encodePacket(packet, packetBuf, allocator, true); int packetSize = packetBuf.writerIndex(); buf.writeBytes(toChars(packetSize)); buf.writeBytes(B64_DELIMITER); buf.writeBytes(packetBuf); packetBuf.release(); i++; for (ByteBuf attachment : packet.getAttachments()) { ByteBuf encodedBuf = Base64.encode(attachment, Base64Dialect.URL_SAFE); buf.writeBytes(toChars(encodedBuf.readableBytes() + 2)); buf.writeBytes(B64_DELIMITER); buf.writeBytes(BINARY_HEADER); buf.writeBytes(encodedBuf); } } if (jsonpMode) { out.writeBytes(JSONP_HEAD); out.writeBytes(toChars(jsonpIndex)); out.writeBytes(JSONP_START); } processUtf8(buf, out, jsonpMode); buf.release(); if (jsonpMode) { out.writeBytes(JSONP_END); } }
From source file:com.corundumstudio.socketio.protocol.PacketEncoder.java
License:Apache License
public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary) throws IOException { ByteBuf buf = buffer;/*from ww w .j a v a2 s. c om*/ if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); try { switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); jsonSupport.writeValue(out, packet.getData()); break; } case MESSAGE: { ByteBuf encBuf = null; if (packet.getSubType() == PacketType.ERROR) { encBuf = allocateBuffer(allocator); ByteBufOutputStream out = new ByteBufOutputStream(encBuf); jsonSupport.writeValue(out, packet.getData()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK) { List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT) { values.add(packet.getName()); } encBuf = allocateBuffer(allocator); List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(encBuf); jsonSupport.writeValue(out, values); if (!jsonSupport.getArrays().isEmpty()) { packet.initAttachments(jsonSupport.getArrays().size()); for (byte[] array : jsonSupport.getArrays()) { packet.addAttachment(Unpooled.wrappedBuffer(array)); } packet.setSubType(PacketType.BINARY_EVENT); } } byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.hasAttachments()) { byte[] ackId = toChars(packet.getAttachments().size()); buf.writeBytes(ackId); buf.writeByte('-'); } if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeByte(','); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } if (encBuf != null) { buf.writeBytes(encBuf); encBuf.release(); } break; } } } finally { // we need to write a buffer in any case if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); buf.release(); } } }
From source file:com.corundumstudio.socketio.SocketIOEncoder.java
License:Apache License
private void write(HttpMessage xhrMessage, Packet packet, ChannelHandlerContext ctx, ByteBuf out) throws IOException { XHRClientEntry clientEntry = getXHRClientEntry(xhrMessage.getSessionId()); if (packet != null) { clientEntry.addPacket(packet);/* w w w .j a v a 2 s . co m*/ } Channel channel = ctx.channel(); if (!channel.isActive() || clientEntry.getPackets().isEmpty() || !clientEntry.writeOnce(channel)) { out.release(); return; } encoder.encodePackets(clientEntry.getPackets(), out, ctx.alloc()); sendMessage(xhrMessage, channel, out); }
From source file:com.corundumstudio.socketio.SocketIOEncoder.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out) { HttpResponse res = createHttpResponse(msg.getOrigin(), out); channel.write(res);/* w ww .ja va2s .c o m*/ if (log.isTraceEnabled()) { log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); } if (out.isReadable()) { channel.write(out); } else { out.release(); } ChannelFuture f = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); f.addListener(ChannelFutureListener.CLOSE); }
From source file:com.corundumstudio.socketio.SocketIOEncoder.java
License:Apache License
private void handle(WebSocketPacketMessage webSocketPacketMessage, Channel channel, ByteBuf out) throws IOException { encoder.encodePacket(webSocketPacketMessage.getPacket(), out); WebSocketFrame res = new TextWebSocketFrame(out); log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), webSocketPacketMessage.getSessionId()); channel.writeAndFlush(res);//from ww w . j a v a2s .c om if (!out.isReadable()) { out.release(); } }
From source file:com.corundumstudio.socketio.transport.FlashPolicyHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { ByteBuf message = (ByteBuf) msg; ByteBuf data = message.slice(0, requestBuffer.readableBytes()); if (data.equals(requestBuffer)) { message.release(); ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(responseBuffer)); f.addListener(ChannelFutureListener.CLOSE); return; }/* www . ja v a2 s . com*/ ctx.pipeline().remove(this); } ctx.fireChannelRead(msg); }
From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java
License:Apache License
/** * Add basic authentication headers to a {@link HttpRequest}. * * The given information is Base64 encoded and the authorization header is set appropriately. Since this needs * to be done for every request, it is refactored out. * * @param ctx the handler context.//from w w w . j a v a 2s. c o m * @param request the request where the header should be added. * @param user the username for auth. * @param password the password for auth. */ public static void addHttpBasicAuth(final ChannelHandlerContext ctx, final HttpRequest request, final String user, final String password) { final String pw = password == null ? "" : password; ByteBuf raw = ctx.alloc().buffer(user.length() + pw.length() + 1); raw.writeBytes((user + ":" + pw).getBytes(CHARSET)); ByteBuf encoded = Base64.encode(raw, false); request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + encoded.toString(CHARSET)); encoded.release(); raw.release(); }
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 w w w .ja v a2 s. c o m*/ 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.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all multi lookup response messages. * * @param request the current request.// w w w .j a va2 s .c om * @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 av a 2s. 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 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; }