List of usage examples for io.netty.buffer ByteBuf retain
@Override public abstract ByteBuf retain();
From source file:org.waarp.openr66.protocol.localhandler.packet.DataPacket.java
License:Open Source License
/** * @param headerLength/*from w w w . j a v a 2s . c o m*/ * @param middleLength * @param endLength * @param buf * @return the new DataPacket from buffer * @throws OpenR66ProtocolPacketException */ public static DataPacket createFromBuffer(int headerLength, int middleLength, int endLength, ByteBuf buf) throws OpenR66ProtocolPacketException { if (headerLength - 1 <= 0) { throw new OpenR66ProtocolPacketException("Not enough data"); } if (middleLength <= 0) { throw new OpenR66ProtocolPacketException("Not enough data"); } int packetRank = buf.readInt(); ByteBuf data = buf.readSlice(middleLength); data.retain(); ByteBuf key; if (endLength > 0) { key = buf.readSlice(endLength); key.retain(); } else { key = Unpooled.EMPTY_BUFFER; } return new DataPacket(packetRank, data, key); }
From source file:org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketCodec.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { // Make sure if the length field was received. if (buf.readableBytes() < 4) { // The length field was not received yet - return null. // This method will be invoked again when more packets are // received and appended to the buffer. return;/* w w w . java 2s .com*/ } // Mark the current buffer position buf.markReaderIndex(); // Read the length field final int length = buf.readInt(); if (length < 9) { throw new OpenR66ProtocolPacketException( "Incorrect decode first field in Network Packet: " + length + " < 9"); } if (buf.readableBytes() < length) { buf.resetReaderIndex(); return; } // Now we can read the two Ids final int localId = buf.readInt(); final int remoteId = buf.readInt(); final byte code = buf.readByte(); int readerInder = buf.readerIndex(); ByteBuf buffer = buf.slice(readerInder, length - 9); buffer.retain(); buf.skipBytes(length - 9); NetworkPacket networkPacket = new NetworkPacket(localId, remoteId, code, buffer); if (code == LocalPacketFactory.KEEPALIVEPACKET) { KeepAlivePacket keepAlivePacket = (KeepAlivePacket) LocalPacketCodec .decodeNetworkPacket(networkPacket.getBuffer()); if (keepAlivePacket.isToValidate()) { keepAlivePacket.validate(); NetworkPacket response = new NetworkPacket(ChannelUtils.NOCHANNEL, ChannelUtils.NOCHANNEL, keepAlivePacket, null); NetworkChannelReference nc = NetworkTransaction.getImmediateNetworkChannel(ctx.channel()); if (nc != null) { nc.useIfUsed(); } ctx.writeAndFlush(response.getNetworkPacket()); buffer.release(); } // Replaced by a NoOp packet networkPacket = new NetworkPacket(localId, remoteId, new NoOpPacket(), null); NetworkServerHandler nsh = (NetworkServerHandler) ctx.pipeline().last(); nsh.setKeepAlivedSent(); } out.add(networkPacket); }
From source file:org.waarp.openr66.proxy.network.NetworkPacketCodec.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { // Make sure if the length field was received. if (buf.readableBytes() < 4) { // The length field was not received yet - return null. // This method will be invoked again when more packets are // received and appended to the buffer. return;// w w w .ja v a 2 s . c om } // Mark the current buffer position buf.markReaderIndex(); // Read the length field final int length = buf.readInt(); if (buf.readableBytes() < length) { buf.resetReaderIndex(); return; } // Now we can read the two Ids // Slight change in Proxy = first is remote and second is local! final int remoteId = buf.readInt(); final int localId = buf.readInt(); final byte code = buf.readByte(); int readerInder = buf.readerIndex(); ByteBuf buffer = buf.slice(readerInder, length - 9); buffer.retain(); buf.skipBytes(length - 9); NetworkPacket networkPacket = new NetworkPacket(localId, remoteId, code, buffer); if (code == LocalPacketFactory.KEEPALIVEPACKET) { KeepAlivePacket keepAlivePacket = (KeepAlivePacket) LocalPacketCodec .decodeNetworkPacket(networkPacket.getBuffer()); if (keepAlivePacket.isToValidate()) { keepAlivePacket.validate(); NetworkPacket response = new NetworkPacket(ChannelUtils.NOCHANNEL, ChannelUtils.NOCHANNEL, keepAlivePacket, null); ctx.writeAndFlush(response.getNetworkPacket()); } // Replaced by a NoOp packet networkPacket = new NetworkPacket(localId, remoteId, new NoOpPacket(), null); NetworkServerHandler nsh = (NetworkServerHandler) ctx.pipeline().last(); nsh.setKeepAlivedSent(); } out.add(networkPacket); }
From source file:org.wso2.carbon.transport.http.netty.listener.http2.HTTP2SourceHandler.java
License:Open Source License
@Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { HTTPCarbonMessage cMsg = streamIdRequestMap.get(streamId); if (cMsg != null) { cMsg.addHttpContent(new DefaultLastHttpContent(data.retain())); if (endOfStream) { cMsg.setEndOfMsgAdded(true); // if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { // HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestSending(cMsg); // } }/*from w ww. j a v a2 s .c o m*/ } return data.readableBytes() + padding; }
From source file:qunar.tc.qmq.netty.DecodeHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception { if (in.readableBytes() < RemotingHeader.MIN_HEADER_SIZE + RemotingHeader.LENGTH_FIELD) return;//w w w .j a v a 2 s .c om int magicCode = in.getInt(in.readerIndex() + RemotingHeader.LENGTH_FIELD); if (DEFAULT_MAGIC_CODE != magicCode) { throw new IOException("Illegal Data, MagicCode=" + Integer.toHexString(magicCode)); } in.markReaderIndex(); int total = in.readInt(); if (in.readableBytes() < total) { in.resetReaderIndex(); return; } short headerSize = in.readShort(); RemotingHeader remotingHeader = decodeHeader(in); int bodyLength = total - headerSize - RemotingHeader.HEADER_SIZE_LEN; RemotingCommand remotingCommand = new RemotingCommand(); //because netty(lower version) has memory leak when ByteBuf cross thread //We can ensure server use high version netty, bu we can't ensure client if (isServer) { ByteBuf bodyData = in.readSlice(bodyLength); bodyData.retain(); remotingCommand.setBody(bodyData); } else { ByteBuf bodyData = Unpooled.buffer(bodyLength, bodyLength); in.readBytes(bodyData, bodyLength); remotingCommand.setBody(bodyData); } remotingCommand.setHeader(remotingHeader); list.add(remotingCommand); }
From source file:qunar.tc.qmq.startup.ServerWrapper.java
License:Apache License
private void createStorage() { slaveSyncClient = new SlaveSyncClient(config); this.storage = new DefaultStorage(BrokerConfig.getBrokerRole(), new StorageConfigImpl(config), new CheckpointLoader() { @Override/*from ww w . jav a 2s . c om*/ public ByteBuf loadCheckpoint() { Datagram datagram = null; try { datagram = syncCheckpointUntilSuccess(); final ByteBuf body = datagram.getBody(); body.retain(); return body; } finally { if (datagram != null) { datagram.release(); } } } private Datagram syncCheckpointUntilSuccess() { while (true) { try { return slaveSyncClient.syncCheckpoint(); } catch (Exception e) { LOG.warn("sync checkpoint failed, will retry after 2 seconds", e); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ignore) { LOG.debug("sync checkpoint interrupted"); } } } } }); }
From source file:ratpack.form.internal.FormDecoder.java
License:Apache License
public static Form parseForm(Context context, TypedData requestBody, MultiValueMap<String, String> base) throws RuntimeException { Request request = context.getRequest(); HttpMethod method = io.netty.handler.codec.http.HttpMethod.valueOf(request.getMethod().getName()); HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri()); nettyRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, request.getBody().getContentType().toString()); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(nettyRequest); HttpContent content = new DefaultHttpContent(requestBody.getBuffer()); decoder.offer(content);/*from www .j av a 2 s .c om*/ decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT); Map<String, List<String>> attributes = new LinkedHashMap<>(base.getAll()); Map<String, List<UploadedFile>> files = new LinkedHashMap<>(); try { InterfaceHttpData data = decoder.next(); while (data != null) { if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) { List<String> values = attributes.get(data.getName()); if (values == null) { values = new ArrayList<>(1); attributes.put(data.getName(), values); } try { values.add(((Attribute) data).getValue()); } catch (IOException e) { throw uncheck(e); } finally { data.release(); } } else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) { List<UploadedFile> values = files.get(data.getName()); if (values == null) { values = new ArrayList<>(1); files.put(data.getName(), values); } try { FileUpload nettyFileUpload = (FileUpload) data; final ByteBuf byteBuf = nettyFileUpload.getByteBuf(); byteBuf.retain(); context.onClose(new Action<RequestOutcome>() { @Override public void execute(RequestOutcome thing) throws Exception { byteBuf.release(); } }); MediaType contentType; String rawContentType = nettyFileUpload.getContentType(); if (rawContentType == null) { contentType = null; } else { Charset charset = nettyFileUpload.getCharset(); if (charset == null) { contentType = DefaultMediaType.get(rawContentType); } else { contentType = DefaultMediaType.get(rawContentType + ";charset=" + charset); } } UploadedFile fileUpload = new DefaultUploadedFile( new ByteBufBackedTypedData(byteBuf, contentType), nettyFileUpload.getFilename()); values.add(fileUpload); } catch (IOException e) { throw uncheck(e); } finally { data.release(); } } data = decoder.next(); } } catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) { // ignore } finally { decoder.destroy(); } return new DefaultForm(new ImmutableDelegatingMultiValueMap<>(attributes), new ImmutableDelegatingMultiValueMap<>(files)); }
From source file:ratpack.http.client.internal.DefaultReceivedResponse.java
License:Apache License
@Override public void forwardTo(Response response) { response.getHeaders().copy(headers); response.status(status);//from w ww.j a va 2 s. c om ByteBuf buffer = typedData.getBuffer(); if (buffer.readableBytes() > 0) { response.send(buffer.retain()); } else { buffer.release(); response.send(); } }
From source file:ratpack.session.clientside.internal.NoCrypto.java
License:Apache License
private ByteBuf passthrough(ByteBuf message) { return message.retain().slice().asReadOnly(); }
From source file:ratpack.session.internal.LocalMemorySessionStore.java
License:Apache License
@Override public Operation store(AsciiString sessionId, ByteBuf sessionData) { return Operation.of(() -> { maybeCleanup();/*from ww w . jav a 2s .c o m*/ ByteBuf retained = sessionData.retain().asReadOnly(); cache.put(sessionId, retained); }); }