List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:com.moshi.receptionist.remoting.netty.NettyDecoder.java
License:Apache License
@Override public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { try {/* w ww.ja v a2 s . c om*/ ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } byte[] tmpBuf = new byte[frame.capacity()]; frame.getBytes(0, tmpBuf); frame.release(); return RemotingCommand.decode(tmpBuf); } catch (Exception e) { log.error("decode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e); // ? pipelineclose??? RemotingUtil.closeChannel(ctx.channel()); } return null; }
From source file:com.mpush.common.message.ByteBufMessage.java
License:Apache License
@Override public byte[] encode() { ByteBuf body = connection.getChannel().alloc().heapBuffer(); try {//from w w w .j a va2s . co m encode(body); byte[] bytes = new byte[body.readableBytes()]; body.readBytes(bytes); return bytes; } finally { body.release(); } }
From source file:com.myftpserver.handler.ReceiveFileHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (bos == null) { User user = fs.getUser();//from w w w . j a v a 2s .com if (user.getUploadSpeedLitmit() == 0L) logger.info("File upload speed is limited by connection speed"); else { ctx.channel().pipeline().addFirst("TrafficShapingHandler", new ChannelTrafficShapingHandler(0L, user.getUploadSpeedLitmit() * 1024)); logger.info("File upload speed limit:" + user.getUploadSpeedLitmit() + " kB/s"); } ctx.channel().closeFuture().addListener(this); tempFile = File.createTempFile("temp-file-name", ".tmp"); fs.setUploadTempFile(tempFile); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); } ByteBuf in = (ByteBuf) msg; //logger.debug("ReceiveFileHandler channelRead buffer capacity="+in.capacity()+",readable byte count="+in.readableBytes()); try { while (in.isReadable()) { in.readBytes(bos, in.readableBytes()); } bos.flush(); } finally { in.release(); } }
From source file:com.necla.simba.server.gateway.server.frontend.FrontendFrameDecoder.java
License:Apache License
private ByteBuf decompress(ChannelHandlerContext ctx, ByteBuf frame) throws Exception { int readableBytes = frame.readableBytes(); if (frame.hasArray()) { inflater.setInput(frame.array(), 0, readableBytes); } else {// w w w . java2s . c o m byte[] array = new byte[frame.readableBytes()]; frame.getBytes(0, array); inflater.setInput(array); } int totalLength = 0; List<ByteBuf> all = new LinkedList<ByteBuf>(); int multiplier = 2; alldone: while (true) { int maxOutputLength = inflater.getRemaining() * multiplier; // multiplier keeps increasing, so we will keep picking // larger and larger buffers the more times we have to loop // around, i.e., the more we realize that the data was very // heavily compressed, the larger our buffers are going to be. multiplier += 1; ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength); while (!inflater.needsInput()) { byte[] outArray = decompressed.array(); int outIndex = decompressed.arrayOffset() + decompressed.writerIndex(); int length = outArray.length - outIndex; if (length == 0) break; try { //LOG.debug("here1"); int outputLength = inflater.inflate(outArray, outIndex, length); totalLength += outputLength; //LOG.debug("here2"); if (outputLength > 0) decompressed.writerIndex(decompressed.writerIndex() + outputLength); } catch (DataFormatException e) { throw new Exception("Could not inflate" + e.getMessage()); } if (inflater.finished()) { all.add(decompressed); break alldone; } } all.add(decompressed); } inflater.reset(); if (all.size() == 1) return all.get(0); else { ByteBuf allData = ctx.alloc().heapBuffer(totalLength); for (ByteBuf b : all) { //LOG.debug("capacity=" + allData.capacity()); allData.writeBytes(b); b.release(); } return allData; } }
From source file:com.netflix.prana.http.api.ProxyHandler.java
License:Apache License
@Override public Observable<Void> handle(final HttpServerRequest<ByteBuf> serverRequest, final HttpServerResponse<ByteBuf> serverResponse) { String vip = Utils.forQueryParam(serverRequest.getQueryParameters(), "vip"); String path = Utils.forQueryParam(serverRequest.getQueryParameters(), "path"); if (Strings.isNullOrEmpty(vip)) { serverResponse.getHeaders().set("Content-Type", "application/xml"); serverResponse.writeString(ERROR_RESPONSE); logger.error("VIP is empty"); return serverResponse.close(); }//from w w w . j a va 2 s.c o m if (path == null) { path = ""; } final LoadBalancingHttpClient<ByteBuf, ByteBuf> client = getClient(vip); final HttpClientRequest<ByteBuf> req = HttpClientRequest.create(serverRequest.getHttpMethod(), path); populateRequestHeaders(serverRequest, req); final UnicastDisposableCachingSubject<ByteBuf> cachedContent = UnicastDisposableCachingSubject.create(); /** * Why do we retain here? * After the onNext on the content returns, RxNetty releases the sent ByteBuf. This ByteBuf is kept out of * the scope of the onNext for consumption of the client in the route. The client when eventually writes * this ByteBuf over the wire expects the ByteBuf to be usable (i.e. ref count => 1). If this retain() call * is removed, the ref count will be 0 after the onNext on the content returns and hence it will be unusable * by the client in the route. */ serverRequest.getContent().map(new Func1<ByteBuf, ByteBuf>() { @Override public ByteBuf call(ByteBuf byteBuf) { return byteBuf.retain(); } }).subscribe(cachedContent); // Caches data if arrived before client writes it out, else passes through req.withContentSource(cachedContent); return client.submit(req).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() { @Override public Observable<Void> call(final HttpClientResponse<ByteBuf> response) { serverResponse.setStatus(response.getStatus()); List<Map.Entry<String, String>> headers = response.getHeaders().entries(); for (Map.Entry<String, String> header : headers) { serverResponse.getHeaders().add(header.getKey(), header.getValue()); } return response.getContent().map(new Func1<ByteBuf, ByteBuf>() { @Override public ByteBuf call(ByteBuf byteBuf) { return byteBuf.retain(); } }).map(new Func1<ByteBuf, Void>() { @Override public Void call(ByteBuf byteBuf) { serverResponse.write(byteBuf); return null; } }); } }).onErrorResumeNext(new Func1<Throwable, Observable<Void>>() { @Override public Observable<Void> call(Throwable throwable) { serverResponse.getHeaders().set("Content-Type", "application/xml"); serverResponse.writeString(ERROR_RESPONSE); return Observable.just(null); } }).doOnCompleted(new Action0() { @Override public void call() { serverResponse.close(); cachedContent.dispose(new Action1<ByteBuf>() { @Override public void call(ByteBuf byteBuf) { /** * Why do we release here? * * All ByteBuf which were never consumed are disposed and sent here. This means that the * client in the route never consumed this ByteBuf. Before sending this ByteBuf to the * content subject, we do a retain (see above for reason) expecting the client in the route * to release it when written over the wire. In this case, though, the client never consumed * it and hence never released corresponding to the retain done by us. */ if (byteBuf.refCnt() > 1) { // 1 refCount will be from the subject putting into the cache. byteBuf.release(); } } }); } }); }
From source file:com.netflix.ribbon.RibbonTest.java
License:Apache License
@Test public void testCommand() throws IOException, InterruptedException, ExecutionException { MockWebServer server = new MockWebServer(); String content = "Hello world"; MockResponse response = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain") .setBody(content);// w w w . j av a 2s . c om server.enqueue(response); server.enqueue(response); server.enqueue(response); server.play(); HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create().withMaxAutoRetriesNextServer(3).withReadTimeout(300000) .withConfigurationBasedServerList( "localhost:12345, localhost:10092, localhost:" + server.getPort())); HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/") .withMethod("GET").build(); RibbonRequest<ByteBuf> request = template.requestBuilder().build(); String result = request.execute().toString(Charset.defaultCharset()); assertEquals(content, result); // repeat the same request ByteBuf raw = request.execute(); result = raw.toString(Charset.defaultCharset()); raw.release(); assertEquals(content, result); result = request.queue().get().toString(Charset.defaultCharset()); assertEquals(content, result); }
From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java
License:Apache License
private boolean readClientPrefaceString(ByteBuf in) throws Http2Exception { ByteBuf clientPrefaceString = Http2CodecUtil.connectionPrefaceBuf(); int prefaceRemaining = clientPrefaceString.readableBytes(); int bytesRead = min(in.readableBytes(), prefaceRemaining); // If the input so far doesn't match the preface, break the connection. if (bytesRead == 0 || !ByteBufUtil.equals(in, in.readerIndex(), clientPrefaceString, clientPrefaceString.readerIndex(), bytesRead)) { String receivedBytes = hexDump(in, in.readerIndex(), min(in.readableBytes(), clientPrefaceString.readableBytes())); throw connectionError(PROTOCOL_ERROR, "HTTP/2 client preface string missing or corrupt. " + "Hex dump for received bytes: %s", receivedBytes);/*w ww. j a v a2s.c o m*/ } in.skipBytes(bytesRead); clientPrefaceString.skipBytes(bytesRead); if (!clientPrefaceString.isReadable()) { // Entire preface has been read. clientPrefaceString.release(); return true; } return false; }
From source file:com.openddal.server.mysql.MySQLAuthenticator.java
License:Apache License
@Override public void authorize(Channel channel, ByteBuf buf) { MySQLSession session = channel.attr(TMP_SESSION_KEY).getAndRemove(); HandshakeResponse authReply = null;//from w w w . j a va2s . c o m try { byte[] packet = new byte[buf.readableBytes()]; buf.readBytes(packet); authReply = HandshakeResponse.loadFromPacket(packet); Connection connect = connectEngine(authReply); session.setHandshakeResponse(authReply); session.setEngineConnection(connect); session.bind(channel); success(channel); } catch (Exception e) { String msg = authReply == null ? e.getMessage() : "Access denied for user '" + authReply.username + "' to database '" + authReply.schema + "'"; LOGGER.error("Authorize failed. " + msg, e); error(channel, MySQLErrorCode.ER_DBACCESS_DENIED_ERROR, msg); } finally { buf.release(); } }
From source file:com.otcdlink.chiron.downend.Http11ProxyHandler.java
License:Apache License
public Http11ProxyHandler(SocketAddress proxyAddress, String username, String password) { super(proxyAddress); if (username == null) { throw new NullPointerException("username"); }//from w w w. j a v a 2 s . c o m if (password == null) { throw new NullPointerException("password"); } this.username = username; this.password = password; ByteBuf authz = Unpooled.copiedBuffer(username + ':' + password, CharsetUtil.UTF_8); ByteBuf authzBase64 = Base64.encode(authz, false); authorization = new AsciiString("Basic " + authzBase64.toString(CharsetUtil.US_ASCII)); authz.release(); authzBase64.release(); }
From source file:com.ottogroup.bi.spqr.websocket.server.SPQRWebSocketServerHandler.java
License:Apache License
/** * Sends a {@link HttpResponse} according to prepared {@link FullHttpResponse} to the client. The * code was copied from netty.io websocket server example. The origins may be found at: * {@linkplain https://github.com/netty/netty/blob/4.0/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServerHandler.java} * @param ctx/*w w w .ja v a2 s. co m*/ * @param req * @param res */ private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }