Example usage for io.netty.util ReferenceCountUtil retain

List of usage examples for io.netty.util ReferenceCountUtil retain

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil retain.

Prototype

@SuppressWarnings("unchecked")
public static <T> T retain(T msg) 

Source Link

Document

Try to call ReferenceCounted#retain() if the specified message implements ReferenceCounted .

Usage

From source file:org.lanternpowered.server.network.NetworkSession.java

License:MIT License

/**
 * Sends a {@link Message}./*from  w  ww. j  a  va2  s.co  m*/
 *
 * @param message The message
 */
public void send(Message message) {
    checkNotNull(message, "message");
    if (!this.channel.isActive()) {
        return;
    }
    ReferenceCountUtil.retain(message);
    // Thrown exceptions will be delegated through the exceptionCaught method
    this.channel.writeAndFlush(message, this.channel.voidPromise());
}

From source file:org.lanternpowered.server.network.NetworkSession.java

License:MIT License

/**
 * Sends a array of {@link Message}s.//w w w.  j  a va  2 s. c o m
 *
 * @param messages The messages
 */
public void send(Message... messages) {
    checkNotNull(messages, "messages");
    checkArgument(messages.length != 0, "messages cannot be empty");
    if (!this.channel.isActive()) {
        return;
    }
    final ChannelPromise voidPromise = this.channel.voidPromise();
    if (messages.length == 1) {
        this.channel.writeAndFlush(messages[0], voidPromise);
    } else {
        final EventLoop eventLoop = this.channel.eventLoop();
        if (eventLoop.inEventLoop()) {
            for (Message message : messages) {
                ReferenceCountUtil.retain(message);
                this.channel.writeAndFlush(message, voidPromise);
            }
        } else {
            // If there are more then one message, combine them inside the
            // event loop to reduce overhead of wakeup calls and object creation

            // Create a copy of the list, to avoid concurrent modifications
            final List<Message> messages0 = ImmutableList.copyOf(messages);
            messages0.forEach(ReferenceCountUtil::retain);
            eventLoop.submit(() -> {
                for (Message message0 : messages0) {
                    this.channel.writeAndFlush(message0, voidPromise);
                }
            });
        }
    }
}

From source file:org.opendaylight.sxp.core.handler.ConnectionDecoder.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf message)
        throws ErrorCodeDataLengthException, AttributeLengthException, TlvNotFoundException,
        AddressLengthException, UnknownNodeIdException, ErrorMessageException, UnknownSxpMessageTypeException,
        AttributeVariantException, UnknownHostException, UnknownPrefixException {
    InetSocketAddress address = getAddress(ctx);
    final SxpConnection connection = owner.getConnection(address);
    final SxpDomain domain = getTemplateDomain(address);

    if (address != null && connection == null && domain != null) {
        final SxpConnectionTemplateFields template = domain.getTemplate(address);
        Notification notification = MessageFactory.parse(null, message);
        Version version = getVersion(notification);
        ConnectionMode mode = getMode(notification);
        if ((template.getTemplateMode() == null || template.getTemplateMode().equals(mode))
                && (template.getTemplateVersion() == null || template.getTemplateVersion().equals(version))) {
            LOG.info("{} Adding new SxpConnection from template {}", owner, template);
            addConnection(domain.getName(),
                    new ConnectionBuilder().setMode(invertMode(mode)).setTcpPort(template.getTemplateTcpPort())
                            .setPeerAddress(new IpAddress(address.getAddress().getHostAddress().toCharArray()))
                            .setPassword(template.getTemplatePassword())
                            .setDescription("AutoGenerated connection.").setState(ConnectionState.Off)
                            .setConnectionTimers(new ConnectionTimersBuilder().build()).setVersion(version)
                            .setCapabilities(Configuration.getCapabilities(version)).build());
        }//from   w  ww . j ava 2 s .  co m
        ctx.close();
    } else {
        ReferenceCountUtil.retain(message);
        ctx.fireChannelRead(message);
    }
}

From source file:org.opendaylight.usc.plugin.Demultiplexer.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    LOG.trace("Demultiplexer.channelRead0: " + msg);

    Channel channel = ctx.channel();
    Channel serverChannel = channel.attr(UscPlugin.LOCAL_SERVER_CHANNEL).get();
    ReferenceCountUtil.retain(msg);

    if (msg instanceof DatagramPacket) {
        ByteBuf payload = ((DatagramPacket) msg).content();
        serverChannel.writeAndFlush(payload);
    } else {/*  ww w.  java2  s. c  o m*/
        serverChannel.writeAndFlush(msg);
    }
}

From source file:org.opendaylight.usc.plugin.UscRemoteDeviceHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (isRemote(ctx)) {
        ByteBuf payload = (ByteBuf) msg;
        byte[] data = getPayloadFromByteBuf(payload);
        writeBuffer(data);/*from  w  w w .ja  v  a 2s .c  o  m*/
        return;
    }
    ReferenceCountUtil.retain(msg);
    // propagate the data to rest of handlers in pipeline
    ctx.fireChannelRead(msg);
}

From source file:org.opendaylight.usc.plugin.UscRemoteServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object data) throws Exception {
    UscRouteIdentifier localRouteId = null;

    // get local route identifier
    if (data instanceof UscFrame) {
        LOG.trace("Read data from Usc Agent: " + data);
        // communicate with agent
        final UscHeader header = ((UscFrame) data).getHeader();
        final UscChannelImpl connection = ctx.channel().attr(UscPlugin.CHANNEL).get();
        // for remote session
        localRouteId = new UscRouteIdentifier(connection.getDevice().getInetAddress(), connection.getType(),
                header.getSessionId(), header.getApplicationPort());
    } else {//w w  w. jav a 2s . c  o m
        LOG.trace("Read data from None Usc Agent: " + data);
        // communicate directly with device
        localRouteId = ctx.channel().attr(UscPlugin.ROUTE_IDENTIFIER).get();
    }

    if (broker == null) {
        broker = UscServiceUtils.getService(UscRouteBrokerService.class);
    }
    if (broker == null) {
        LOG.error("Broker service is null!Can't check if it is response from remote channel.Route id is "
                + localRouteId);
    } else if (broker.isRemoteSession(localRouteId)) {
        byte[] payload = null;
        // get content, after reading the readable data become zero,can't
        // use again
        if (data instanceof UscFrame) {
            payload = getPayloadFromByteBuf(((UscFrame) data).getPayload());
        } else if (data instanceof DatagramPacket) {
            payload = getPayloadFromByteBuf(((DatagramPacket) data).content());
        } else {
            payload = getPayloadFromByteBuf((ByteBuf) data);
        }
        if (data instanceof UscError) {
            // propagate exception to the client channel
            UscSessionException ex = new UscSessionException(((UscError) data).getErrorCode());
            // send error message back to remote request controller
            broker.sendException(localRouteId, ex);
        } else {
            broker.sendResponse(localRouteId, payload);
        }
        LOG.trace("It is response from local remote channel.Sending message to route id (" + localRouteId
                + ").messsage is " + new String(payload));
        return;
    }

    ReferenceCountUtil.retain(data);
    // propagate the data to rest of handlers in pipeline
    ctx.fireChannelRead(data);
}

From source file:org.thingsboard.mqtt.MqttPingHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof MqttMessage)) {
        ctx.fireChannelRead(msg);//  www  .j av  a  2  s.  c om
        return;
    }
    MqttMessage message = (MqttMessage) msg;
    if (message.fixedHeader().messageType() == MqttMessageType.PINGREQ) {
        this.handlePingReq(ctx.channel());
    } else if (message.fixedHeader().messageType() == MqttMessageType.PINGRESP) {
        this.handlePingResp();
    } else {
        ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
    }
}

From source file:org.wso2.carbon.mss.internal.router.RequestRouter.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    Channel channel = ctx.channel();
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        if (handleRequest(request, channel, ctx)) {
            if (httpMethodInfoBuilder.getHttpResourceModel().isStreamingReqSupported()
                    && channel.pipeline().get("aggregator") != null) {
                channel.pipeline().remove("aggregator");
            } else if (!httpMethodInfoBuilder.getHttpResourceModel().isStreamingReqSupported()
                    && channel.pipeline().get("aggregator") == null) {
                channel.pipeline().addAfter("router", "aggregator",
                        new HttpObjectAggregator(Integer.MAX_VALUE));
            }/*from   ww w  .  j  a  v  a  2  s  .  com*/
        }
        ReferenceCountUtil.retain(msg);
        ctx.fireChannelRead(msg);
    } else if (msg instanceof HttpContent) {
        ReferenceCountUtil.retain(msg);
        ctx.fireChannelRead(msg);
    }
}

From source file:reactor.ipc.netty.channel.FluxReceive.java

License:Open Source License

final void onInboundNext(Object msg) {
    if (inboundDone) {
        if (log.isDebugEnabled()) {
            log.debug("Dropping frame {}", msg);
        }//from   w  ww .j  ava 2s .co  m
        return;
    }
    ReferenceCountUtil.retain(msg);
    if (receiverFastpath && receiver != null) {
        try {
            receiver.onNext(msg);
        } finally {
            ReferenceCountUtil.release(msg);
        }

    } else {
        Queue<Object> q = receiverQueue;
        if (q == null) {
            q = QueueSupplier.unbounded().get();
            receiverQueue = q;
        }
        q.offer(msg);
        if (drainReceiver()) {
            receiverFastpath = true;
        }
    }
}

From source file:reactor.ipc.netty.channel.NettyOperations.java

License:Open Source License

/**
 * React on inbound {@link Channel#read}
 *
 * @param msg the read payload//  w  ww  .  j  av a  2  s.co m
 */
protected void onInboundNext(Object msg) {
    if (msg == null) {
        onChannelError(new NullPointerException("msg is null"));
        return;
    }
    if (inboundDone) {
        Operators.onNextDropped(msg);
        return;
    }
    ReferenceCountUtil.retain(msg);
    if (receiverCaughtUp && receiver != null) {
        try {
            receiver.onNext(msg);
        } finally {
            ReferenceCountUtil.release(msg);
            channel.read();
        }

    } else {
        Queue<Object> q = inboundQueue;
        if (q == null) {
            q = QueueSupplier.unbounded().get();
            inboundQueue = q;
        }
        q.offer(msg);
        if (drainReceiver()) {
            receiverCaughtUp = true;
        }
    }
}