Java Code Examples for io.netty.channel.ChannelPromise

The following are top voted examples for showing how to use io.netty.channel.ChannelPromise. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: simulacron   File: ServerTest.java   View source code 6 votes vote down vote up
@Override
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise)
    throws Exception {
  if (localAddress == slowAddr) {
    // delay binding 1 second.
    eventLoop.schedule(
        () -> {
          try {
            super.bind(ctx, localAddress, promise);
          } catch (Exception e) {
            // shouldn't happen.
          }
        },
        1,
        TimeUnit.SECONDS);
  } else {
    super.bind(ctx, localAddress, promise);
  }
}
 
Example 2
Project: nitmproxy   File: Http2FrontendHandler.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    LOGGER.info("[Client ({})] <= [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                msg);

    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;
        if (!response.headers().contains(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text())) {
            if (streams.isEmpty()) {
                throw new IllegalStateException("No active streams");
            }
            response.headers().add(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(),
                                   streams.poll());
        }
    }

    ctx.write(msg, promise);
}
 
Example 3
Project: ditb   File: TestAsyncIPC.java   View source code 6 votes vote down vote up
@Override
protected AsyncRpcClient createRpcClientRTEDuringConnectionSetup(Configuration conf) {
  setConf(conf);
  return new AsyncRpcClient(conf, new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                throws Exception {
              promise.setFailure(new RuntimeException("Injected fault"));
            }
          });
        }
      });
}
 
Example 4
Project: neoscada   File: FrameProcessor.java   View source code 6 votes vote down vote up
@Override
public void write ( final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise ) throws Exception
{
    if ( msg instanceof OpenResponse )
    {
        writeOpenResponse ( ctx, (OpenResponse)msg, promise );
    }
    else if ( msg instanceof SyslogResponse )
    {
        writeGenericResponse ( ctx, (AbstractGenericResponse)msg, promise );
    }
    else if ( msg instanceof ServerCloseMessage )
    {
        ctx.write ( new Frame ( 0, "serverclose", (ByteBuf)null ) );
    }
    else
    {
        super.write ( ctx, msg, promise );
    }
}
 
Example 5
Project: neoscada   File: FrameProcessor.java   View source code 6 votes vote down vote up
protected void writeOpenResponse ( final ChannelHandlerContext ctx, final OpenResponse msg, final ChannelPromise promise )
{
    final StringBuilder sb = new StringBuilder ();

    int i = 0;
    for ( final Map.Entry<String, String> entry : msg.getOffers ().entrySet () )
    {
        if ( i > 0 )
        {
            sb.append ( Constants.LF_STRING );
        }

        sb.append ( entry.getKey () );

        if ( entry.getValue () != null )
        {
            sb.append ( '=' );
            sb.append ( entry.getValue () );
        }
        i++;
    }

    ctx.write ( createCommonResponse ( msg.getTransactionId (), msg.getCode (), msg.getMessage (), sb ) );
}
 
Example 6
Project: neoscada   File: FrameCodec.java   View source code 6 votes vote down vote up
protected void processFrame ( final ChannelHandlerContext ctx, final Frame frame, final ChannelPromise promise )
{
    final int length = frame.getData () == null ? 0 : frame.getData ().readableBytes ();

    final ByteBuf data = ctx.alloc ().buffer ();
    data.writeBytes ( String.format ( "%s", frame.getTransactionId () ).getBytes ( TXNR_CHARSET ) );
    data.writeByte ( Constants.SP );
    data.writeBytes ( frame.getCommand ().getBytes ( COMMAND_CHARSET ) );
    data.writeByte ( Constants.SP );
    data.writeBytes ( String.format ( "%s", length ).getBytes ( LENGTH_CHARSET ) );

    if ( length > 0 )
    {
        data.writeByte ( Constants.SP );
        data.writeBytes ( frame.getData () );
    }

    if ( frame.getData () != null )
    {
        frame.getData ().release ();
    }

    data.writeByte ( Constants.LF );

    ctx.write ( data );
}
 
Example 7
Project: neoscada   File: MessageChannel.java   View source code 6 votes vote down vote up
private void handleMessageWrite ( final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise )
{
    final ByteBuf data = encode ( ctx, msg );

    if ( data == null )
    {
        // ignore
        return;
    }

    // if the buffer is full
    if ( this.ackBuffer.isFull () )
    {
        logger.trace ( "Store message for later transmission" );
        // ... store now and re-try later
        this.messageBuffer.add ( new WriteEvent ( ctx, data, promise ) );
    }
    else
    {
        writeMessageToChannel ( ctx, data, promise );
    }
}
 
Example 8
Project: neoscada   File: MessageChannel.java   View source code 6 votes vote down vote up
private void writeMessageToChannel ( final ChannelHandlerContext ctx, final ByteBuf data, final ChannelPromise promise )
{
    final int seq = this.ackBuffer.addMessage ( data );

    if ( promise == null )
    {
        ctx.write ( new InformationTransfer ( seq, this.receiveCounter, data ) );
    }
    else
    {
        ctx.write ( new InformationTransfer ( seq, this.receiveCounter, data ), promise );
    }

    logger.trace ( "Enqueued message as {} : {}", seq, data );

    // we can stop timer #2 here ... will be restarted by receive
    this.timer2.stop ();
}
 
Example 9
Project: hekate   File: NetworkProtocolCodec.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof DeferredMessage) {
        DeferredMessage defMsg = (DeferredMessage)msg;

        if (defMsg.isPreEncoded()) {
            // Write pre-encoded message.
            ctx.write(defMsg.encoded(), promise);
        } else {
            super.write(ctx, defMsg.encoded(), promise);
        }
    } else if (msg instanceof ByteBuf) {
        ctx.write(msg, promise);
    } else {
        super.write(ctx, msg, promise);
    }
}
 
Example 10
Project: ClusterDeviceControlPlatform   File: KyOutBoundHandler.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    IMessage message = (IMessage) msg;
    if (message.getMsgId() >= 0x40 && message.getMsgId() <= 0x4F) {
        ctx.writeAndFlush(Unpooled.wrappedBuffer(tcpMsgBuilder.buildResponseMsg((BaseTcpResponseMsg) message)));
    } else if (message.getMsgId() >= 0x60 && message.getMsgId() <= 0x6F) {
        ctx.writeAndFlush(Unpooled.wrappedBuffer(tcpMsgBuilder.buildResponseMsg((BaseTcpResponseMsg) message)));
    } else if (message.getMsgId() >= -128 && message.getMsgId() <= -113) {
        ctx.writeAndFlush(Unpooled.wrappedBuffer(tcpMsgBuilder.buildResponseMsg((BaseTcpResponseMsg) message)));
    } else if (message.getMsgId() == MsgType.INITIALIZE_DEVICE_RESPONSE_CARD) {
        ctx.writeAndFlush(Unpooled.wrappedBuffer(tcpMsgBuilder.buildInitConfirmCardNumber((TcpMsgInitResponseCardNumber) message)));
    }
    if (message.getMsgId() == 0x00) {
        ctx.writeAndFlush(Unpooled.wrappedBuffer(tcpMsgBuilder.buildResponseMsg((BaseTcpResponseMsg) message)));
    }
    if (sendListener != null) {
        sendListener.send();
    }
}
 
Example 11
Project: ClusterDeviceControlPlatform   File: MsgRecognitionOutBoundHandler.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    SendableMsgContainer message = (SendableMsgContainer) msg;
    ByteBuf byteBuf = ctx.alloc().buffer();
    FrameMajorHeader header = message.getFrameHeader();
    byteBuf.writeByte(FrameSetting.MAJOR_FRAME_HEAD_1);
    byteBuf.writeByte(FrameSetting.MAJOR_FRAME_HEAD_2);
    byteBuf.writeByte(header.getGroupId());
    byteBuf.writeByte(header.getMsgId());
    byteBuf.writeByte(header.getDeviceId());
    byteBuf.writeByte(header.getBackupMsg());
    byteBuf.writeShort(header.getDataLength());

    List<ByteBuf> dataList = message.getDataList();
    dataList.forEach(byteBuf::writeBytes);
    ctx.writeAndFlush(byteBuf);
}
 
Example 12
Project: UnknownPandaServer   File: PacketCodec.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!(msg instanceof Packet)) {
        throw new RuntimeException("Object is not a *Packet");
    }

    Packet packet = (Packet) msg;
    int packetId = packet.getPacketInfo().id();
    int packetSize = packet.getPacketSize() + ProtocolSizer.ofVarInt(packetId);
    int bufferSize = packetSize + ProtocolSizer.ofVarInt(packetSize);

    ByteBuf unpooledByteBuf = Unpooled.buffer(bufferSize);
    PacketSerializer serializer = new PacketSerializer(unpooledByteBuf);

    UnknownPandaServer.getLogger().info("Sending packet: " + packet.getClass().getSimpleName() + " & id: 0x" + Integer.toHexString(packetId) + " & size: " + packetSize);
    serializer.writeVarInt(packetSize);
    serializer.writeVarInt(packetId);
    packet.send(serializer);

    ctx.writeAndFlush(serializer, promise);
}
 
Example 13
Project: ChatMenuAPI   File: PlayerChatIntercept.java   View source code 6 votes vote down vote up
public void write(ChannelHandlerContext context, Object packet, ChannelPromise promise) throws Exception
{
	BaseComponent[] components = interceptor.getComponents(packet);
	if(components != null)
	{
		boolean allowed = isAllowed(components);
		boolean paused = isPaused();
		if(!paused || !allowed)
		{
			while(messageQueue.size() > 20)
				messageQueue.remove();
			messageQueue.add(components);
		}
		
		if(paused && !allowed)
			return;
	}
	
	super.write(context, packet, promise);
}
 
Example 14
Project: CustomWorldGen   File: NetworkDispatcher.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
{
    if (msg instanceof FMLProxyPacket)
    {
        if (side == Side.CLIENT)
        {
            //Client to server large packets are not supported to prevent client being bad.
            ctx.write(((FMLProxyPacket) msg).toC17Packet(), promise);
        }
        else
        {
            List<Packet<INetHandlerPlayClient>> parts = ((FMLProxyPacket)msg).toS3FPackets();
            for (Packet<INetHandlerPlayClient> pkt : parts)
            {
                ctx.write(pkt, promise);
            }
        }
    }
    else
    {
        ctx.write(msg, promise);
    }
}
 
Example 15
Project: rmq4note   File: NettyRemotingClient.java   View source code 5 votes vote down vote up
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
    final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
    log.info("NETTY CLIENT PIPELINE: DISCONNECT {}", remoteAddress);
    closeChannel(ctx.channel());
    super.disconnect(ctx, promise);

    if (NettyRemotingClient.this.channelEventListener != null) {
        NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress.toString(), ctx.channel()));
    }
}
 
Example 16
Project: ZentrelaRPG   File: TinyProtocol.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    try {
        msg = onPacketOutAsync(player, ctx.channel(), msg);
    } catch (Exception e) {
        plugin.getLogger().log(Level.SEVERE, "Error in onPacketOutAsync().", e);
    }

    if (msg != null) {
        super.write(ctx, msg, promise);
    }
}
 
Example 17
Project: wechat-mall   File: NettyRemotingClient.java   View source code 5 votes vote down vote up
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
        SocketAddress localAddress, ChannelPromise promise) throws Exception {
    final String local = localAddress == null ? "UNKNOW" : localAddress.toString();
    final String remote = remoteAddress == null ? "UNKNOW" : remoteAddress.toString();
    log.info("NETTY CLIENT PIPELINE: CONNECT  {} => {}", local, remote);
    super.connect(ctx, remoteAddress, localAddress, promise);
}
 
Example 18
Project: wechat-mall   File: NettyRemotingClient.java   View source code 5 votes vote down vote up
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
    final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
    log.info("NETTY CLIENT PIPELINE: DISCONNECT {}", remoteAddress);
    closeChannel(ctx.channel());
    super.disconnect(ctx, promise);
}
 
Example 19
Project: JRediClients   File: CommandEncoder.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (acceptOutboundMessage(msg)) {
        if (!promise.setUncancellable()) {
            return;
        }
    }

    try {
        super.write(ctx, msg, promise);
    } catch (Exception e) {
        promise.tryFailure(e);
        throw e;
    }
}
 
Example 20
Project: JRediClients   File: CommandsQueue.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof QueueCommand) {
        QueueCommand data = (QueueCommand) msg;
        QueueCommandHolder holder = queue.peek();
        if (holder != null && holder.getCommand() == data) {
            super.write(ctx, msg, promise);
        } else {
            queue.add(new QueueCommandHolder(data, promise));
            sendData(ctx.channel());
        }
    } else {
        super.write(ctx, msg, promise);
    }
}
 
Example 21
Project: JRediClients   File: CommandBatchEncoder.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (acceptOutboundMessage(msg)) {
        if (!promise.setUncancellable()) {
            return;
        }
    }

    super.write(ctx, msg, promise);
}
 
Example 22
Project: nitmproxy   File: Http1BackendHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof FullHttpRequest) {
        LOGGER.info("[Client ({})] => [Server ({})] : (PENDING) {}",
                    connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                    msg);
        HttpRequest request = (HttpRequest) msg;
        pendings.offer(new RequestPromise(request, promise));
        next();
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handled message: " + msg.getClass());
    } else {
        ctx.write(msg, promise);
    }
}
 
Example 23
Project: nitmproxy   File: TlsHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    synchronized (pendings) {
        pendings.add(msg);
    }
    if (ctx.isRemoved()) {
        flushPendings(ctx);
        ctx.flush();
    }
}
 
Example 24
Project: nitmproxy   File: Http2BackendHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    LOGGER.info("[Client ({})] => [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                msg);
    if (msg instanceof FullHttpRequest) {
        HttpMessage httpMessage = (HttpRequest) msg;
        httpMessage.headers().add(ExtensionHeaderNames.SCHEME.text(), "https");
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handle message: " + msg.getClass());
    }

    ctx.writeAndFlush(msg, promise);
}
 
Example 25
Project: elasticsearch_my   File: Netty4MessageChannelHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof ByteBuf && transportServiceAdapter != null) {
        // record the number of bytes send on the channel
        promise.addListener(f -> transportServiceAdapter.addBytesSent(((ByteBuf) msg).readableBytes()));
    }
    ctx.write(msg, promise);
}
 
Example 26
Project: CustomWorldGen   File: NetworkDispatcher.java   View source code 5 votes vote down vote up
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception
{
    if (side == Side.CLIENT)
    {
        MinecraftForge.EVENT_BUS.post(new FMLNetworkEvent.ClientDisconnectionFromServerEvent(manager));
    }
    else
    {
        MinecraftForge.EVENT_BUS.post(new FMLNetworkEvent.ServerDisconnectionFromClientEvent(manager));
    }
    cleanAttributes(ctx);
    ctx.disconnect(promise);
}
 
Example 27
Project: talchain   File: WireTrafficStats.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    outPackets.incrementAndGet();
    if (msg instanceof ByteBuf) {
        outSize.addAndGet(((ByteBuf) msg).readableBytes());
    } else if (msg instanceof DatagramPacket) {
        outSize.addAndGet(((DatagramPacket) msg).content().readableBytes());
    }
    super.write(ctx, msg, promise);
}
 
Example 28
Project: drift   File: ThriftClientHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise)
        throws Exception
{
    if (message instanceof ThriftRequest) {
        ThriftRequest thriftRequest = (ThriftRequest) message;
        sendMessage(ctx, thriftRequest, promise);
    }
    else {
        ctx.write(message, promise);
    }
}
 
Example 29
Project: drift   File: ThriftClientHandler.java   View source code 5 votes vote down vote up
private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise)
        throws Exception
{
    // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed
    int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet();
    RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId);

    // register timeout
    requestHandler.registerRequestTimeout(context.executor());

    // write request
    ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc());

    // register request if we are expecting a response
    if (!thriftRequest.isOneway()) {
        if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) {
            requestHandler.onChannelError(new TTransportException("Another request with the same sequenceId is already in progress"));
        }
    }

    try {
        ChannelFuture sendFuture = context.write(requestBuffer, promise);
        sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler));
    }
    catch (Throwable t) {
        onError(context, t);
    }
}
 
Example 30
Project: SamaGamesAPI   File: TinyProtocol.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    try {
        msg = onPacketOutAsync(player, ctx.channel(), msg);
    } catch (Exception e) {
        plugin.getLogger().log(Level.SEVERE, "Error in onPacketOutAsync().", e);
    }

    if (msg != null) {
        super.write(ctx, msg, promise);
    }
}
 
Example 31
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: NettyRemotingClient.java   View source code 5 votes vote down vote up
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
    ChannelPromise promise) throws Exception {
    final String local = localAddress == null ? "UNKNOWN" : RemotingHelper.parseSocketAddressAddr(localAddress);
    final String remote = remoteAddress == null ? "UNKNOWN" : RemotingHelper.parseSocketAddressAddr(remoteAddress);
    log.info("NETTY CLIENT PIPELINE: CONNECT  {} => {}", local, remote);

    super.connect(ctx, remoteAddress, localAddress, promise);

    if (NettyRemotingClient.this.channelEventListener != null) {
        NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CONNECT, remote, ctx.channel()));
    }
}
 
Example 32
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: NettyRemotingClient.java   View source code 5 votes vote down vote up
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
    final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
    log.info("NETTY CLIENT PIPELINE: DISCONNECT {}", remoteAddress);
    closeChannel(ctx.channel());
    super.disconnect(ctx, promise);

    if (NettyRemotingClient.this.channelEventListener != null) {
        NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress, ctx.channel()));
    }
}
 
Example 33
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: NettyRemotingClient.java   View source code 5 votes vote down vote up
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
    final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
    log.info("NETTY CLIENT PIPELINE: CLOSE {}", remoteAddress);
    closeChannel(ctx.channel());
    super.close(ctx, promise);

    if (NettyRemotingClient.this.channelEventListener != null) {
        NettyRemotingClient.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress, ctx.channel()));
    }
}
 
Example 34
Project: miracle-remote   File: NettyClientDispatchHandler.java   View source code 5 votes vote down vote up
@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
    if (msg instanceof Request) {
        Request request = (Request) msg;
        responseMap.putIfAbsent(request.getMessageId(), new LinkedBlockingQueue<Response>(1));
    }
    super.write(ctx, msg, promise);
}
 
Example 35
Project: CustomWorldGen   File: HandshakeInjector.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
{
    if (msg instanceof FMLProxyPacket)
    {
        this.dispatcher.sendProxy((FMLProxyPacket) msg);
    }
}
 
Example 36
Project: neoscada   File: MessageChannel.java   View source code 5 votes vote down vote up
@Override
public void write ( final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise ) throws Exception
{
    logger.trace ( "Write {}", msg );
    synchronized ( this )
    {
        if ( msg instanceof DataTransmissionMessage )
        {
            switch ( (DataTransmissionMessage)msg )
            {
                case REQUEST_START:
                    ctx.write ( new UnnumberedControl ( Function.STARTDT_ACT ), promise );
                    break;
                case CONFIRM_START:
                    ctx.write ( new UnnumberedControl ( Function.STARTDT_CONFIRM ), promise );
                    break;
                case REQUEST_STOP:
                    ctx.write ( new UnnumberedControl ( Function.STOPDT_ACT ), promise );
                    break;
                case CONFIRM_STOP:
                    ctx.write ( new UnnumberedControl ( Function.STOPDT_CONFIRM ), promise );
                    break;
                default:
                    throw new EncoderException ( String.format ( "Unknown data transmission message: %s", msg ) );
            }
        }
        else if ( msg == MessageSource.NOTIFY_TOKEN )
        {
            handleMessageSourceUpdates ( ctx );
        }
        else
        {
            handleMessageWrite ( ctx, msg, promise );
        }
    }
}
 
Example 37
Project: hekate   File: NettyClientIdleStateHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof Heartbeat) {
        ctx.write(msg, promise);
    } else {
        super.write(ctx, msg, promise);
    }
}
 
Example 38
Project: hekate   File: NettyClientDeferHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof DeferredMessage) {
        DeferredMessage def = (DeferredMessage)msg;

        if (deferredError == null) {
            if (debug) {
                log.debug("Deferring message sending since handshake is not completed yet [to={}, message={}]", id, def.source());
            }

            deferred.add(def);
        } else if (promise.tryFailure(deferredError)) {
            ReferenceCountUtil.release(def.encoded());
        }
    } else {
        if (deferredError == null) {
            if (debug) {
                log.debug("Writing message directly to the channel [to={}, message={}]", id, msg);
            }

            needToFlush = true;

            super.write(ctx, msg, promise);
        } else if (promise.tryFailure(deferredError)) {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 39
Project: hekate   File: NettyClientDeferHandler.java   View source code 5 votes vote down vote up
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
    if (trace) {
        log.trace("Deferred handler got channel close event [to={}]", id);
    }

    discardDeferred();

    super.close(ctx, future);
}
 
Example 40
Project: ClusterDeviceControlPlatform   File: SendingOutBoundHandler.java   View source code 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!(msg instanceof SendableMsg)) {
        return;
    }
    SendableMsg message = (SendableMsg) msg;
    ctx.writeAndFlush(Unpooled.wrappedBuffer(message.getBytes()));
}