Example usage for io.netty.channel ChannelDuplexHandler ChannelDuplexHandler

List of usage examples for io.netty.channel ChannelDuplexHandler ChannelDuplexHandler

Introduction

In this page you can find the example usage for io.netty.channel ChannelDuplexHandler ChannelDuplexHandler.

Prototype

ChannelDuplexHandler

Source Link

Usage

From source file:io.reactivex.netty.pipeline.ByteArrayPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(new ChannelDuplexHandler() {

        @Override// w  ww .j  a  va  2  s  .  c o m
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            boolean handled = false;

            if (ByteBuf.class.isAssignableFrom(msg.getClass())) {
                ByteBuf byteBuf = (ByteBuf) msg;
                if (byteBuf.isReadable()) {
                    int readableBytes = byteBuf.readableBytes();
                    byte[] msgToPass = new byte[readableBytes];
                    byteBuf.readBytes(msgToPass);
                    handled = true;
                    ctx.fireChannelRead(msgToPass);
                }
            }
            if (!handled) {
                super.channelRead(ctx, msg);
            }
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof byte[]) {
                byte[] msgAsBytes = (byte[]) msg;
                ByteBuf byteBuf = ctx.alloc().buffer(msgAsBytes.length).writeBytes(msgAsBytes);
                super.write(ctx, byteBuf, promise);
            } else {
                super.write(ctx, msg, promise); // pass-through
            }
        }
    });
}

From source file:io.reactivex.netty.RxEventPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(new ChannelDuplexHandler() {

        @Override// www .  j a  va2 s. com
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            boolean handled = false;
            if (ByteBuf.class.isAssignableFrom(msg.getClass())) {
                ByteBuf byteBuf = (ByteBuf) msg;
                if (byteBuf.isReadable()) {
                    int protocolVersion = byteBuf.readByte();
                    if (protocolVersion != PROTOCOL_VERSION) {
                        throw new RuntimeException("Unsupported protocol version: " + protocolVersion);
                    }
                    int observableNameLength = byteBuf.readByte();
                    String observableName = null;
                    if (observableNameLength > 0) {
                        // read name
                        observableName = new String(byteBuf.readBytes(observableNameLength).array());
                    }
                    int operation = byteBuf.readByte();
                    RemoteRxEvent.Type type = null;
                    Map<String, String> subscribeParams = null;
                    byte[] valueData = null;
                    if (operation == 1) {
                        logger.debug("READ request for RemoteRxEvent: next");
                        type = RemoteRxEvent.Type.next;
                        valueData = new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(valueData);
                    } else if (operation == 2) {
                        logger.debug("READ request for RemoteRxEvent: error");
                        type = RemoteRxEvent.Type.error;
                        valueData = new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(valueData);
                    } else if (operation == 3) {
                        logger.debug("READ request for RemoteRxEvent: completed");
                        type = RemoteRxEvent.Type.completed;
                    } else if (operation == 4) {
                        logger.debug("READ request for RemoteRxEvent: subscribed");
                        type = RemoteRxEvent.Type.subscribed;
                        // read subscribe parameters
                        int subscribeParamsLength = byteBuf.readInt();
                        if (subscribeParamsLength > 0) {
                            // read byte into map
                            byte[] subscribeParamsBytes = new byte[subscribeParamsLength];
                            byteBuf.readBytes(subscribeParamsBytes);
                            subscribeParams = fromBytesToMap(subscribeParamsBytes);
                        }
                    } else if (operation == 5) {
                        logger.debug("READ request for RemoteRxEvent: unsubscribed");
                        type = RemoteRxEvent.Type.unsubscribed;
                    } else {
                        throw new RuntimeException("operation: " + operation + " not support.");
                    }
                    handled = true;
                    byteBuf.release();
                    ctx.fireChannelRead(new RemoteRxEvent(observableName, type, valueData, subscribeParams));
                }
            }
            if (!handled) {
                super.channelRead(ctx, msg);
            }
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof RemoteRxEvent) {
                ByteBuf buf = ctx.alloc().buffer();
                buf.writeByte(PROTOCOL_VERSION);
                RemoteRxEvent event = (RemoteRxEvent) msg;
                String observableName = event.getName();
                if (observableName != null && !observableName.isEmpty()) {
                    // write length
                    int nameLength = observableName.length();
                    if (nameLength < 127) {
                        buf.writeByte(nameLength);
                        buf.writeBytes(observableName.getBytes());
                    } else {
                        throw new RuntimeException(
                                "observableName " + observableName + " exceeds max limit of 127 characters");
                    }
                } else {
                    // no name provided, write 0 bytes for name length
                    buf.writeByte(0);
                }
                if (event.getType() == RemoteRxEvent.Type.next) {
                    logger.debug("WRITE request for RemoteRxEvent: next");
                    buf.writeByte(1);
                    buf.writeBytes(event.getData());
                    super.write(ctx, buf, promise);
                } else if (event.getType() == RemoteRxEvent.Type.error) {
                    logger.debug("WRITE request for RemoteRxEvent: error");
                    buf.writeByte(2);
                    buf.writeBytes(event.getData());
                    super.write(ctx, buf, promise);
                } else if (event.getType() == RemoteRxEvent.Type.completed) {
                    logger.debug("WRITE request for RemoteRxEvent: completed");
                    buf.writeByte(3);
                    super.write(ctx, buf, promise);
                    super.flush(ctx); // TODO why do I need to explicitly call flush for this to work??? empty data??
                } else if (event.getType() == RemoteRxEvent.Type.subscribed) {
                    logger.debug("WRITE request for RemoteRxEvent: subscribed");
                    buf.writeByte(4);
                    Map<String, String> subscribeParameters = event.getSubscribeParameters();
                    if (subscribeParameters != null && !subscribeParameters.isEmpty()) {
                        byte[] subscribeBytes = fromMapToBytes(subscribeParameters);
                        buf.writeInt(subscribeBytes.length); // write int for length
                        buf.writeBytes(subscribeBytes); // write data
                    } else {
                        buf.writeInt(0); // no data
                    }
                    super.write(ctx, buf, promise);
                    super.flush(ctx);
                } else if (event.getType() == RemoteRxEvent.Type.unsubscribed) {
                    logger.debug("WRITE request for RemoteRxEvent: unsubscribed");
                    buf.writeByte(5);
                    super.write(ctx, buf, promise);
                    super.flush(ctx); // TODO why do I need to explicitly call flush for this to work??? empty data??
                }
            } else {
                super.write(ctx, msg, promise);
            }
        }

    });

}

From source file:io.vertx.mqtt.impl.MqttClientImpl.java

License:Apache License

private void initChannel(ChannelPipeline pipeline) {

    // add into pipeline netty's (en/de)coder
    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);

    if (this.options.getMaxMessageSize() > 0) {
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {//from  www . j  av a  2  s .  c o m
        // max message size not set, so the default from Netty MQTT codec is used
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    if (this.options.isAutoKeepAlive() && this.options.getKeepAliveTimeSeconds() != 0) {

        pipeline.addBefore("handler", "idle",
                new IdleStateHandler(0, this.options.getKeepAliveTimeSeconds(), 0));
        pipeline.addBefore("handler", "keepAliveHandler", new ChannelDuplexHandler() {

            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

                if (evt instanceof IdleStateEvent) {
                    IdleStateEvent e = (IdleStateEvent) evt;
                    if (e.state() == IdleState.WRITER_IDLE) {
                        ping();
                    }
                }
            }
        });
    }
}

From source file:io.vertx.mqtt.impl.MqttServerConnection.java

License:Apache License

/**
 * Used for calling the endpoint handler when a connection is established with a remote MQTT client
 *//*from   ww w.j  a v  a2s. c om*/
private void handleConnect(MqttConnectMessage msg) {

    // if client sent one more CONNECT packet
    if (endpoint != null) {
        //we should treat it as a protocol violation and disconnect the client
        endpoint.close();
        return;
    }

    // if client sent one more CONNECT packet
    if (endpoint != null) {
        //we should treat it as a protocol violation and disconnect the client
        endpoint.close();
        return;
    }

    // retrieve will information from CONNECT message
    MqttWill will = new MqttWill(msg.variableHeader().isWillFlag(), msg.payload().willTopic(),
            msg.payload().willMessage(), msg.variableHeader().willQos(), msg.variableHeader().isWillRetain());

    // retrieve authorization information from CONNECT message
    MqttAuth auth = (msg.variableHeader().hasUserName() && msg.variableHeader().hasPassword())
            ? new MqttAuth(msg.payload().userName(), msg.payload().password())
            : null;

    // check if remote MQTT client didn't specify a client-id
    boolean isZeroBytes = (msg.payload().clientIdentifier() == null)
            || msg.payload().clientIdentifier().isEmpty();

    String clientIdentifier = null;

    // client-id got from payload or auto-generated (according to options)
    if (!isZeroBytes) {
        clientIdentifier = msg.payload().clientIdentifier();
    } else if (this.options.isAutoClientId()) {
        clientIdentifier = UUID.randomUUID().toString();
    }

    // create the MQTT endpoint provided to the application handler
    this.endpoint = new MqttEndpointImpl(so, clientIdentifier, auth, will,
            msg.variableHeader().isCleanSession(), msg.variableHeader().version(), msg.variableHeader().name(),
            msg.variableHeader().keepAliveTimeSeconds());

    // remove the idle state handler for timeout on CONNECT
    chctx.pipeline().remove("idle");
    chctx.pipeline().remove("timeoutOnConnect");

    // keep alive == 0 means NO keep alive, no timeout to handle
    if (msg.variableHeader().keepAliveTimeSeconds() != 0) {

        // the server waits for one and a half times the keep alive time period (MQTT spec)
        int timeout = msg.variableHeader().keepAliveTimeSeconds()
                + msg.variableHeader().keepAliveTimeSeconds() / 2;

        // modifying the channel pipeline for adding the idle state handler with previous timeout
        chctx.pipeline().addBefore("handler", "idle", new IdleStateHandler(timeout, 0, 0));
        chctx.pipeline().addBefore("handler", "keepAliveHandler", new ChannelDuplexHandler() {

            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

                if (evt instanceof IdleStateEvent) {
                    IdleStateEvent e = (IdleStateEvent) evt;
                    if (e.state() == IdleState.READER_IDLE) {
                        endpoint.close();
                    }
                }
            }
        });
    }

    // MQTT spec 3.1.1 : if client-id is "zero-bytes", clean session MUST be true
    if (isZeroBytes && !msg.variableHeader().isCleanSession()) {
        if (this.exceptionHandler != null) {
            this.exceptionHandler
                    .handle(new VertxException("With zero-length client-id, clean session MUST be true"));
        }
        this.endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED);
    } else {

        // an exception at connection level is propagated to the endpoint
        this.so.exceptionHandler(t -> {
            this.endpoint.handleException(t);
        });

        // Used for calling the close handler when the remote MQTT client closes the connection
        this.so.closeHandler(v -> this.endpoint.handleClosed());

        this.endpointHandler.handle(this.endpoint);
    }
}

From source file:io.vertx.mqtt.impl.MqttServerImpl.java

License:Apache License

private void initChannel(ChannelPipeline pipeline) {

    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);
    if (this.options.getMaxMessageSize() > 0) {
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {//w ww .  j  a  v  a 2  s  .c  o m
        // max message size not set, so the default from Netty MQTT codec is used
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    // adding the idle state handler for timeout on CONNECT packet
    pipeline.addBefore("handler", "idle", new IdleStateHandler(this.options.timeoutOnConnect(), 0, 0));
    pipeline.addBefore("handler", "timeoutOnConnect", new ChannelDuplexHandler() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.READER_IDLE) {
                    // as MQTT 3.1.1 describes, if no packet is sent after a "reasonable" time (here CONNECT timeout)
                    // the connection is closed
                    ctx.channel().close();
                }
            }
        }
    });
}

From source file:org.eclipse.neoscada.protocol.iec60870.client.Client.java

License:Open Source License

protected void handleInitChannel(final SocketChannel ch) {
    // add the APCI/APDU handler
    ch.pipeline().addLast(new APDUDecoder());
    ch.pipeline().addLast(new APDUEncoder());

    // add logging
    if (Boolean.getBoolean("org.eclipse.scada.protocol.iec60870.trace")) {
        ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
    }/*from  ww w  .  j  a va2s  .c  o  m*/

    final MessageChannel messageChannel = new MessageChannel(this.options, this.manager);

    // message channel
    ch.pipeline().addLast(messageChannel);

    // now add all server modules

    for (final Module module : this.modules) {
        module.initializeChannel(ch, messageChannel);
    }

    // finally add the default exception catcher

    ch.pipeline().addLast(new ChannelDuplexHandler() {
        @Override
        public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
            logger.warn("Close connection due to uncaught exception", cause);
            ctx.close();
        }

        @Override
        public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
            fireDisconnected(null);
        }
    });
}

From source file:org.eclipse.neoscada.protocol.iec60870.server.Server.java

License:Open Source License

protected void handleInitChannel(final SocketChannel ch) {
    // add the APCI/APDU handler

    ch.pipeline().addLast(new APDUDecoder());
    ch.pipeline().addLast(new APDUEncoder());

    // add logging

    if (Boolean.getBoolean("org.eclipse.scada.protocol.iec60870.trace")) {
        ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
    }/*from  w w w  . j  a v a 2  s. c  om*/

    final MessageChannel messageChannel = new MessageChannel(this.options, this.manager);

    // message channel

    ch.pipeline().addLast(messageChannel);

    // now add all server modules

    for (final ServerModule module : this.modules) {
        module.initializeChannel(ch, messageChannel);
    }

    // finally add the default exception catcher

    ch.pipeline().addLast(new ChannelDuplexHandler() {
        @Override
        public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
            logger.warn("Close connection due to uncaught exception", cause);
            ctx.close();
        }
    });
}

From source file:org.eclipse.scada.protocol.iec60870.server.Server.java

License:Open Source License

protected void handleInitChannel(final SocketChannel ch) {
    // add the APCI/APDU handler
    ch.pipeline().addLast(new APDUDecoder());
    ch.pipeline().addLast(new APDUEncoder());

    // add logging
    if (Boolean.getBoolean("org.eclipse.scada.protocol.iec60870.trace")) {
        ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
    }/*from   ww w .  j a  v  a 2 s . co  m*/

    final MessageChannel messageChannel = new MessageChannel(this.options, this.manager);

    // message channel
    ch.pipeline().addLast(messageChannel);

    // now add all server modules

    for (final ServerModule module : this.modules) {
        module.initializeChannel(ch, messageChannel);
    }

    // finally add the default exception catcher

    ch.pipeline().addLast(new ChannelDuplexHandler() {
        @Override
        public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
            logger.warn("Close connection due to uncaught exception", cause);
            ctx.close();
        }
    });
}

From source file:org.hornetq.amqp.test.minimalclient.SimpleAMQPConnector.java

License:Apache License

public AMQPClientConnection connect(String host, int port) throws Exception {
    SocketAddress remoteDestination = new InetSocketAddress(host, port);

    ChannelFuture future = bootstrap.connect(remoteDestination);

    future.awaitUninterruptibly();/* w ww. j  a  v  a 2s .  co  m*/

    AMQPClientSPI clientConnectionSPI = new AMQPClientSPI(future.channel());

    final AMQPClientConnection connection = (AMQPClientConnection) ProtonClientConnectionFactory.getFactory()
            .createConnection(clientConnectionSPI, false);

    future.channel().pipeline().addLast(new ChannelDuplexHandler() {

        @Override
        public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
            ByteBuf buffer = (ByteBuf) msg;
            connection.inputBuffer(buffer);
        }
    });

    return connection;
}

From source file:org.proton.plug.test.minimalclient.SimpleAMQPConnector.java

License:Apache License

public AMQPClientConnectionContext connect(String host, int port) throws Exception {
    SocketAddress remoteDestination = new InetSocketAddress(host, port);

    ChannelFuture future = bootstrap.connect(remoteDestination);

    future.awaitUninterruptibly();//www  .  jav a2s .c o  m

    AMQPClientSPI clientConnectionSPI = new AMQPClientSPI(future.channel());

    final AMQPClientConnectionContext connection = (AMQPClientConnectionContext) ProtonClientConnectionContextFactory
            .getFactory().createConnection(clientConnectionSPI);

    future.channel().pipeline().addLast(new ChannelDuplexHandler() {

        @Override
        public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
            ByteBuf buffer = (ByteBuf) msg;
            connection.inputBuffer(buffer);
        }
    });

    return connection;
}