List of usage examples for io.netty.util ReferenceCountUtil release
public static boolean release(Object msg)
From source file:com.chen.opensourceframework.netty.echo.EchoServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // ctx.write(msg); ByteBuf in = (ByteBuf) msg;/* w w w.java2 s . co m*/ try { while (in.isReadable()) { // (1) System.out.print(in.readChar()); System.out.flush(); } } finally { ReferenceCountUtil.release(msg); // (2) } }
From source file:com.chenyang.proxy.http.HttpPreHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (preCheck(ctx, msg)) { ctx.fireChannelRead(msg);// www . j a va2 s. c om } else { ReferenceCountUtil.release(msg); } }
From source file:com.chenyang.proxy.http.HttpRelayHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { if (relayChannel.isActive()) { relayChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override//from w w w. j a v a 2s . c o m public void operationComplete(ChannelFuture future) throws Exception { if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) { ctx.read(); } } }); } else { ReferenceCountUtil.release(msg); } }
From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { final Channel uaChannel = uaChannelCtx.channel(); final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); if (remoteChannel != null && remoteChannel.isActive()) { HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote); remoteChannel.writeAndFlush(request); } else {/*from w ww. j a va2 s .c o m*/ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this)); ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)); remoteChannel = remoteConnectFuture.channel(); remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel); remoteConnectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote)); for (HttpContent hc : httpContentBuffer) { future.channel().writeAndFlush(hc); if (hc instanceof LastHttpContent) { future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } httpContentBuffer.clear(); } else { HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR); httpContentBuffer.clear(); future.channel().close(); } } }); } ReferenceCountUtil.release(msg); } else { Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); HttpContent hc = ((HttpContent) msg); if (remoteChannel != null && remoteChannel.isActive()) { remoteChannel.writeAndFlush(hc); if (hc instanceof LastHttpContent) { remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } else { httpContentBuffer.add(hc); } } }
From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { // Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel())); final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY) .get().getRemote();/*from w w w . jav a2 s .c o m*/ bootstrap .connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(HttpUserAgentTunnelHandler.HANDLER_NAME); uaChannelCtx.pipeline() .addLast(new HttpRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.company.product.test.http.HttpServerHandler.java
License:Apache License
protected void messageReceived(ChannelHandlerContext ctx, Object msg) { FullHttpResponse response = null;//from w w w. j a v a 2 s . c om try { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); validateQueryString(params); compileAndSendMessage(params); // no need to provide a response, we did what was expected of us. response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); } } catch (IllegalArgumentException iae) { response = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); throw iae; } catch (InvalidTopicException ite) { response = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); throw ite; } finally { ctx.write(response); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(msg); } }
From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof CloseWebSocketFrame) { ctx.channel().close();/*www .j av a 2 s . c om*/ ReferenceCountUtil.release(msg); } else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) { ByteBufHolder frame = (ByteBufHolder) msg; ClientHead client = clientsBox.get(ctx.channel()); if (client == null) { log.debug("Client with was already disconnected. Channel closed!"); ctx.channel().close(); frame.release(); return; } ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET)); frame.release(); } else if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String path = queryDecoder.path(); List<String> transport = queryDecoder.parameters().get("transport"); List<String> sid = queryDecoder.parameters().get("sid"); if (transport != null && NAME.equals(transport.get(0))) { try { if (!configuration.getTransports().contains(Transport.WEBSOCKET)) { log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET); ctx.channel().close(); return; } if (sid != null && sid.get(0) != null) { final UUID sessionId = UUID.fromString(sid.get(0)); handshake(ctx, sessionId, path, req); } else { ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get(); // first connection handshake(ctx, client.getSessionId(), path, req); } } finally { req.release(); } } else { ctx.fireChannelRead(msg); } } else { ctx.fireChannelRead(msg); } }
From source file:com.couchbase.client.core.cluster.NetworkMetricsTest.java
License:Apache License
@Test public void shouldCapturePerformedOperations() throws Exception { Observable<CouchbaseEvent> eventBus = env().eventBus().get(); TestSubscriber<CouchbaseEvent> eventSubscriber = new TestSubscriber<CouchbaseEvent>(); eventBus.filter(new Func1<CouchbaseEvent, Boolean>() { @Override/*from w w w. j a va2s . com*/ public Boolean call(CouchbaseEvent event) { return event instanceof NetworkLatencyMetricsEvent; } }).subscribe(eventSubscriber); assertTrue(eventSubscriber.getOnErrorEvents().isEmpty()); assertTrue(eventSubscriber.getOnNextEvents().isEmpty()); InsertResponse insertResponse = cluster() .<InsertResponse>send( new InsertRequest("perfIns", Unpooled.copiedBuffer("ins", CharsetUtil.UTF_8), bucket())) .toBlocking().single(); ReferenceCountUtil.release(insertResponse); UpsertResponse upsertResponse = cluster() .<UpsertResponse>send( new UpsertRequest("perfUps", Unpooled.copiedBuffer("ups", CharsetUtil.UTF_8), bucket())) .toBlocking().single(); ReferenceCountUtil.release(upsertResponse); for (int i = 0; i < 5; i++) { GetResponse getResponse = cluster().<GetResponse>send(new GetRequest("perfIns", bucket())).toBlocking() .single(); ReferenceCountUtil.release(getResponse); } env().networkLatencyMetricsCollector().triggerEmit(); Thread.sleep(100); List<CouchbaseEvent> events = eventSubscriber.getOnNextEvents(); assertEquals(1, events.size()); NetworkLatencyMetricsEvent event = (NetworkLatencyMetricsEvent) events.get(0); boolean hasInsert = false; boolean hasUpsert = false; boolean hasGet = false; for (Map.Entry<NetworkLatencyMetricsIdentifier, LatencyMetric> metric : event.latencies().entrySet()) { assertFalse(metric.getKey().host().contains(":")); if (metric.getKey().request().equals("InsertRequest")) { hasInsert = true; assertTrue(metric.getValue().count() >= 1); } else if (metric.getKey().request().equals("UpsertRequest")) { hasUpsert = true; assertTrue(metric.getValue().count() >= 1); } else if (metric.getKey().request().equals("GetRequest")) { hasGet = true; assertTrue(metric.getValue().count() >= 1); } assertTrue(metric.getValue().max() > 0); assertTrue(metric.getValue().min() > 0); assertTrue(metric.getValue().count() > 0); long lastPercentile = 0; for (Map.Entry<Double, Long> percentile : metric.getValue().percentiles().entrySet()) { assertTrue(percentile.getValue() >= lastPercentile); lastPercentile = percentile.getValue(); } } assertTrue(hasInsert); assertTrue(hasUpsert); assertTrue(hasGet); }
From source file:com.couchbase.client.core.cluster.ObserveTest.java
License:Apache License
/** * Test that a previously inserted document is correctly persisted to disk on the master node. *//* w w w . ja v a2 s . c o m*/ @Test public void shouldObservePersistToMaster() { InsertRequest request = new InsertRequest("persInsDoc1", Unpooled.copiedBuffer("test", CharsetUtil.UTF_8), bucket()); InsertResponse response = cluster().<InsertResponse>send(request).toBlocking().single(); assertTrue(response.status().isSuccess()); ReferenceCountUtil.release(response); Boolean observeSuccess = Observe .call(cluster(), bucket(), "persInsDoc1", response.cas(), false, Observe.PersistTo.MASTER, Observe.ReplicateTo.NONE, BestEffortRetryStrategy.INSTANCE) .timeout(5, TimeUnit.SECONDS).toBlocking().single(); assertTrue(observeSuccess); }
From source file:com.couchbase.client.core.cluster.ObserveTest.java
License:Apache License
@Test public void shouldObservePersistToMasterOnRemoval() { InsertRequest request = new InsertRequest("persRemDoc1", Unpooled.copiedBuffer("test", CharsetUtil.UTF_8), bucket());// ww w.j a v a 2 s .c om InsertResponse response = cluster().<InsertResponse>send(request).toBlocking().single(); assertTrue(response.status().isSuccess()); ReferenceCountUtil.release(response); RemoveRequest removeRequest = new RemoveRequest("persRemDoc1", bucket()); RemoveResponse removeResponse = cluster().<RemoveResponse>send(removeRequest).toBlocking().single(); assertTrue(removeResponse.status().isSuccess()); ReferenceCountUtil.release(removeResponse); Boolean observeSuccess = Observe .call(cluster(), bucket(), "persRemDoc1", removeResponse.cas(), true, Observe.PersistTo.MASTER, Observe.ReplicateTo.NONE, BestEffortRetryStrategy.INSTANCE) .timeout(5, TimeUnit.SECONDS).toBlocking().single(); assertTrue(observeSuccess); }