Java Code Examples for io.netty.util.ReferenceCountUtil#retain()

The following examples show how to use io.netty.util.ReferenceCountUtil#retain() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebSocketHandler.java    From blade with Apache License 2.0 6 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) {
    if (isWebSocketRequest(req)) {
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.uri(), null, true);
        this.handshaker = wsFactory.newHandshaker(req);
        if (this.handshaker == null) {
            //Return that we need cannot not support the web socket version
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            this.handshaker.handshake(ctx.channel(), req);
            this.session = new WebSocketSession(ctx);
            this.uri = req.uri();
            initHandlerWrapper();
            //Allows the user to send messages in the event of onConnect
            CompletableFuture.completedFuture(new WebSocketContext(this.session,this.handler))
                    .thenAcceptAsync(this.handler::onConnect,ctx.executor());
        }
    } else {
        ReferenceCountUtil.retain(req);
        ctx.fireChannelRead(req);
    }
}
 
Example 2
Source File: Server.java    From riiablo with Apache License 2.0 6 votes vote down vote up
@Override
  public void processPacket(ChannelHandlerContext ctx, SocketAddress from, ByteBuf bb) {
//    Gdx.app.debug(TAG, "Queueing packet...");
//    Gdx.app.debug(TAG, "  " + ByteBufUtil.hexDump(bb));
    D2GSPacket packet = D2GSPacket.obtain(ctx, from, bb);
    boolean success = false;
    try {
      success = inPackets.offer(packet, 1, TimeUnit.MILLISECONDS);
    } catch (Throwable t) {
      Gdx.app.error(TAG, t.getMessage(), t);
      success = false;
    } finally {
      if (success) {
        ReferenceCountUtil.retain(bb);
      } else {
        Gdx.app.error(TAG, "failed to add packet " + packet + " from " + from + " to queue ");
        Gdx.app.debug(TAG, "  " + "closing " + ctx);
        ctx.close();
      }
    }
  }
 
Example 3
Source File: RedisArrayAggregator.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, RedisMessage msg, List<Object> out) throws Exception {
    if (msg instanceof ArrayHeaderRedisMessage) {
        msg = decodeRedisArrayHeader((ArrayHeaderRedisMessage) msg);
        if (msg == null) {
            return;
        }
    } else {
        ReferenceCountUtil.retain(msg);
    }

    while (!depths.isEmpty()) {
        AggregateState current = depths.peek();
        current.children.add(msg);

        // if current aggregation completed, go to parent aggregation.
        if (current.children.size() == current.length) {
            msg = new ArrayRedisMessage(current.children);
            depths.pop();
        } else {
            // not aggregated yet. try next time.
            return;
        }
    }

    out.add(msg);
}
 
Example 4
Source File: DefaultChannelGroup.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private static Object safeDuplicate(Object message) {
    if (message instanceof ByteBuf) {
        return ((ByteBuf) message).duplicate().retain();
    } else if (message instanceof ByteBufHolder) {
        return ((ByteBufHolder) message).duplicate().retain();
    } else {
        return ReferenceCountUtil.retain(message);
    }
}
 
Example 5
Source File: WebSocketEncode.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) {
    if(msg == null) {
        return ;
    }
    if (msg instanceof IBaseMessage) {
        TextWebSocketFrame tsf = new TextWebSocketFrame(msg.toString());
        out.add(tsf);
    } else {
        ReferenceCountUtil.retain(msg);
        out.add(msg);
    }
}
 
Example 6
Source File: ProxyRemoteHandler.java    From karate with MIT License 5 votes vote down vote up
protected void send(FullHttpRequest request) {
    currentRequest = request;
    FullHttpRequest filtered;
    if (requestFilter != null) {
        ProxyResponse pr = requestFilter.apply(proxyContext, request);
        if (pr != null && pr.response != null) { // short circuit
            clientChannel.writeAndFlush(pr.response);
            return;
        }
        filtered = pr == null ? null : pr.request; // if not null, is transformed
    } else {
        filtered = null;
    }
    if (logger.isTraceEnabled()) {
        logger.trace(">> before: {}", request);
    }
    if (filtered == null) {
        ReferenceCountUtil.retain(request);
        filtered = request;
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace(">>>> after: {}", filtered);
        }
    }
    NettyUtils.fixHeadersForProxy(filtered);
    remoteChannel.writeAndFlush(filtered);
}
 
Example 7
Source File: SslHandshakeInfoHandlerTest.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Test
public void sslEarlyHandshakeFailure() throws Exception {
    EmbeddedChannel clientChannel = new EmbeddedChannel();
    SSLEngine clientEngine = SslContextBuilder.forClient().build().newEngine(clientChannel.alloc());
    clientChannel.pipeline().addLast(new SslHandler(clientEngine));

    EmbeddedChannel serverChannel = new EmbeddedChannel();
    SelfSignedCertificate cert = new SelfSignedCertificate("localhorse");
    SSLEngine serverEngine = SslContextBuilder.forServer(cert.key(), cert.cert()).build()
            .newEngine(serverChannel.alloc());

    serverChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            // Simulate an early closure form the client.
            ReferenceCountUtil.safeRelease(msg);
            promise.setFailure(new ClosedChannelException());
        }
    });
    serverChannel.pipeline().addLast(new SslHandler(serverEngine));
    serverChannel.pipeline().addLast(new SslHandshakeInfoHandler());

    Object clientHello = clientChannel.readOutbound();
    assertNotNull(clientHello);
    ReferenceCountUtil.retain(clientHello);

    serverChannel.writeInbound(clientHello);

    // Assert that the handler removes itself from the pipeline, since it was torn down.
    assertNull(serverChannel.pipeline().context(SslHandshakeInfoHandler.class));
}
 
Example 8
Source File: Http2ProxyRoute.java    From xio with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Http2Request request, ChannelHandlerContext ctx) {
  if (request.payload instanceof Http2Headers) {
    handleHeaders(ctx, request);
  } else if (request.payload instanceof Http2DataFrame) {
    Http2DataFrame data = (Http2DataFrame) request.payload;
    ReferenceCountUtil.retain(data);
    handleData(ctx, request);
  }
}
 
Example 9
Source File: EmbeddedChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
    for (;;) {
        Object msg = in.current();
        if (msg == null) {
            break;
        }

        ReferenceCountUtil.retain(msg);
        outboundMessages.add(msg);
        in.remove();
    }
}
 
Example 10
Source File: EmptyHttpResponse.java    From netty-reactive-streams with Apache License 2.0 4 votes vote down vote up
@Override
public FullHttpResponse retain() {
    ReferenceCountUtil.retain(message);
    return this;
}
 
Example 11
Source File: EmptyHttpResponse.java    From netty-reactive-streams with Apache License 2.0 4 votes vote down vote up
@Override
public FullHttpResponse retain(int increment) {
    ReferenceCountUtil.retain(message, increment);
    return this;
}
 
Example 12
Source File: EmptyHttpRequest.java    From netty-reactive-streams with Apache License 2.0 4 votes vote down vote up
@Override
public FullHttpRequest retain() {
    ReferenceCountUtil.retain(message);
    return this;
}
 
Example 13
Source File: EmptyHttpRequest.java    From netty-reactive-streams with Apache License 2.0 4 votes vote down vote up
@Override
public FullHttpRequest retain(int increment) {
    ReferenceCountUtil.retain(message, increment);
    return this;
}
 
Example 14
Source File: EmptyHttpResponse.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public FullHttpResponse retain() {
    ReferenceCountUtil.retain(message);
    return this;
}
 
Example 15
Source File: SimpleProxyHandler.java    From xio with Apache License 2.0 4 votes vote down vote up
@Override
public RequestUpdateHandler handle(HttpRequest payload, ChannelHandlerContext ctx) {
  ReferenceCountUtil.retain(payload);
  buildAndAttach(ctx);
  if (HttpUtil.is100ContinueExpected(payload)) {
    ctx.writeAndFlush(
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
  }

  Optional<String> path =
      route
          .groups(payload.uri())
          .entrySet()
          .stream()
          .filter(e -> e.getKey().equals("path"))
          .map(e -> e.getValue())
          .findFirst();

  if (!config.pathPassthru) {
    payload.setUri(path.map(config.urlPath::concat).orElse(config.urlPath));
  }

  payload.headers().set("Host", config.hostHeader);

  XioRequest request =
      HttpTracingState.hasSpan(ctx)
          ? new XioRequest(payload, HttpTracingState.getSpan(ctx).context())
          : new XioRequest(payload, null);

  log.info("Requesting {}", payload);
  ctx.channel().attr(key).get().write(request);

  return new RequestUpdateHandler() {
    @Override
    public void update(HttpContent content) {
      ReferenceCountUtil.retain(content);
      client.write(content);
    }

    @Override
    public void update(LastHttpContent last) {
      ReferenceCountUtil.retain(last);
      client.write(last);
    }
  };
}
 
Example 16
Source File: DefaultAddressedEnvelope.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public AddressedEnvelope<M, A> retain(int increment) {
    ReferenceCountUtil.retain(message, increment);
    return this;
}
 
Example 17
Source File: DefaultAddressedEnvelope.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public AddressedEnvelope<M, A> retain() {
    ReferenceCountUtil.retain(message);
    return this;
}
 
Example 18
Source File: DefaultAddressedEnvelope.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Override
public AddressedEnvelope<M, A> retain() {
    ReferenceCountUtil.retain(message);
    return this;
}
 
Example 19
Source File: UnicastDisposableCachingSubject.java    From Prana with Apache License 2.0 4 votes vote down vote up
private void add(Object toAdd) {
    ReferenceCountUtil.retain(toAdd); // Released when the notification is sent.
    actual.add(toAdd);
}
 
Example 20
Source File: HttpReqDispatcher.java    From jframe with Apache License 2.0 4 votes vote down vote up
/**
 * request regular expression
 */
// public final static Pattern Req_Regx = Pattern
// .compile("\\/(.*?)\\/(.*?)(?:\\/(.*))?");

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Dispatch req path {} method {}", req.getUri(), req.getMethod().name());
        }

        // pay client req
        final String reqUrl = req.getUri();
        Map<String, WeakReference<String>> cache = _cache;

        WeakReference<String> wr = cache.get(reqUrl);
        String clazz = wr != null && wr.get() != null ? wr.get() : null;
        if (clazz != null) {
            // if (reqUrl.startsWith("/common/image/download")) {
            // ctx.pipeline().addLast("http aggregator",
            // new HttpObjectAggregator(65536));
            // ctx.pipeline().addLast("http chunk",
            // new ChunkedWriteHandler());
            // }

            ctx.pipeline().addLast((ChannelHandler) getClass().getClassLoader().loadClass(clazz).newInstance());
        } else {
            List<Dispatcher> list = _dispatcher;
            boolean notFound = true;
            for (Dispatcher d : list) {
                if (d.getMethod().contains(req.getMethod().name()) && Pattern.matches(d.getUrl(), reqUrl)) {
                    // if (d.getId().equals("img.down")) {
                    // ctx.pipeline().remove("http compressor");
                    // ctx.pipeline().addLast("http aggregator",
                    // new HttpObjectAggregator(65536)); //
                    // ctx.pipeline().addLast("http chunk",
                    // new ChunkedWriteHandler());
                    // }
                    ctx.pipeline().addLast(
                            (ChannelHandler) getClass().getClassLoader().loadClass(d.getClazz()).newInstance());
                    cache.put(reqUrl, new WeakReference<String>(d.getClazz()));
                    notFound = false;
                    break;
                }
            }
            if (notFound) {
                // ctx.pipeline().addLast(VoidHandler);
                // cache.put(reqUrl, new
                // WeakReference<String>(VoidHandler.getClass().getName()));
                // LOG.error("Not found reqUrl->{}", reqUrl);
                throw new Exception("HttpReqDispatcher not match uri->" + reqUrl + " method->" + req.getMethod());
            }
        }
    }
    ReferenceCountUtil.retain(msg);
    ctx.fireChannelRead(msg);
}