Example usage for io.netty.handler.codec.mqtt MqttConnectMessage variableHeader

List of usage examples for io.netty.handler.codec.mqtt MqttConnectMessage variableHeader

Introduction

In this page you can find the example usage for io.netty.handler.codec.mqtt MqttConnectMessage variableHeader.

Prototype

@Override
    public MqttConnectVariableHeader variableHeader() 

Source Link

Usage

From source file:com.caricah.iotracah.server.mqttserver.transform.MqttIOTTransformerImpl.java

License:Apache License

@Override
public IOTMessage toIOTMessage(MqttMessage serverMessage) {

    MqttFixedHeader fxH = serverMessage.fixedHeader();

    if (null == fxH) {
        return null;
    }/* w  w  w .  j  a  va 2s.  c o  m*/

    switch (fxH.messageType()) {

    case PUBLISH:

        MqttPublishMessage publishMessage = (MqttPublishMessage) serverMessage;

        MqttPublishVariableHeader pubVH = publishMessage.variableHeader();

        ByteBuffer byteBuffer = publishMessage.payload().nioBuffer();

        return PublishMessage.from(pubVH.messageId(), fxH.isDup(), fxH.qosLevel().value(), fxH.isRetain(),
                pubVH.topicName(), byteBuffer, true);

    case PUBACK:

        MqttPubAckMessage pubAckMessage = (MqttPubAckMessage) serverMessage;

        MqttMessageIdVariableHeader msgIdVH = pubAckMessage.variableHeader();
        return AcknowledgeMessage.from(msgIdVH.messageId());

    case PUBREC:

        msgIdVH = (MqttMessageIdVariableHeader) serverMessage.variableHeader();
        return PublishReceivedMessage.from(msgIdVH.messageId());

    case PUBREL:

        msgIdVH = (MqttMessageIdVariableHeader) serverMessage.variableHeader();
        return ReleaseMessage.from(msgIdVH.messageId(), fxH.isDup());

    case PUBCOMP:

        msgIdVH = (MqttMessageIdVariableHeader) serverMessage.variableHeader();

        return CompleteMessage.from(msgIdVH.messageId());
    case PINGREQ:
    case PINGRESP:
        return Ping.from(fxH.isDup(), fxH.qosLevel().value(), fxH.isRetain());

    case CONNECT:

        MqttConnectMessage mqttConnectMessage = (MqttConnectMessage) serverMessage;
        MqttConnectVariableHeader conVH = mqttConnectMessage.variableHeader();
        MqttConnectPayload conPayload = mqttConnectMessage.payload();

        boolean isAnnonymousConnect = (!conVH.hasPassword() && !conVH.hasUserName());

        ConnectMessage connectionMessage = ConnectMessage.from(fxH.isDup(), fxH.qosLevel().value(),
                fxH.isRetain(), conVH.name(), conVH.version(), conVH.isCleanSession(), isAnnonymousConnect,
                conPayload.clientIdentifier(), conPayload.userName(), conPayload.password(),
                conVH.keepAliveTimeSeconds(), "");

        connectionMessage.setHasWill(conVH.isWillFlag());
        connectionMessage.setRetainWill(conVH.isWillRetain());
        connectionMessage.setWillQos(conVH.willQos());
        connectionMessage.setWillTopic(conPayload.willTopic());
        connectionMessage.setWillMessage(conPayload.willMessage());
        return connectionMessage;

    case CONNACK:

        MqttConnAckMessage connAckMessage = (MqttConnAckMessage) serverMessage;
        MqttConnAckVariableHeader connAckVH = connAckMessage.variableHeader();

        return ConnectAcknowledgeMessage.from(fxH.isDup(), fxH.qosLevel().value(), fxH.isRetain(), 20,
                connAckVH.connectReturnCode());

    case SUBSCRIBE:

        MqttSubscribeMessage subMsg = (MqttSubscribeMessage) serverMessage;
        msgIdVH = subMsg.variableHeader();
        MqttSubscribePayload subPayload = subMsg.payload();

        SubscribeMessage subscribeMessage = SubscribeMessage.from(msgIdVH.messageId(), fxH.isDup(),
                fxH.qosLevel().value(), fxH.isRetain());

        subPayload.topicSubscriptions().forEach(tSub -> {
            subscribeMessage.getTopicFilterList()
                    .add(new AbstractMap.SimpleEntry<>(tSub.topicName(), tSub.qualityOfService().value()));
        });

        return subscribeMessage;

    case UNSUBSCRIBE:

        MqttUnsubscribeMessage unSubMsg = (MqttUnsubscribeMessage) serverMessage;

        msgIdVH = unSubMsg.variableHeader();
        MqttUnsubscribePayload unsubscribePayload = unSubMsg.payload();

        return UnSubscribeMessage.from(msgIdVH.messageId(), fxH.isDup(), fxH.qosLevel().value(), fxH.isRetain(),
                unsubscribePayload.topics());

    case DISCONNECT:
        return DisconnectMessage.from(false);

    default:
        return null;
    }
}

From source file:io.crate.mqtt.protocol.MqttProcessor.java

public void handleConnect(Channel channel, MqttConnectMessage msg) {
    String clientId = msg.payload().clientIdentifier();
    LOGGER.debug("CONNECT for client <{}>", clientId);

    if (!(msg.variableHeader().version() == MqttVersion.MQTT_3_1.protocolLevel()
            || msg.variableHeader().version() == MqttVersion.MQTT_3_1_1.protocolLevel())) {
        sendErrorResponse(channel, MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION)
                .addListener(f -> LOGGER.warn("CONNECT sent UNACCEPTABLE_PROTOCOL_VERSION"));
        return;/*from  w  w w  . j a v a2 s  .c om*/
    }

    // We require the clean session header to be true if client id is not provided
    // See MQTT-3.1.3-8 http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
    if (clientId == null || clientId.length() == 0) {
        if (msg.variableHeader().isCleanSession() == false) {
            sendErrorResponse(channel, MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED)
                    .addListener(cf -> LOGGER.warn("CONNECT sent IDENTIFIER_REJECTED"));
            return;
        }
        clientId = UUID.randomUUID().toString();
        LOGGER.info("Client connected with server generated identifier: {}", clientId);
    }
    NettyUtils.clientID(channel, clientId);

    int keepAlive = msg.variableHeader().keepAliveTimeSeconds();
    if (keepAlive > 0) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Client connected with keepAlive of {} s", keepAlive);
        }
        NettyUtils.keepAlive(channel, keepAlive);

        if (channel.pipeline().names().contains("idleStateHandler")) {
            channel.pipeline().remove("idleStateHandler");
        }

        // avoid terminating connections too early
        int allIdleTimeSeconds = Math.round(keepAlive * 1.5f);
        channel.pipeline().addFirst("idleStateHandler", new IdleStateHandler(0, 0, allIdleTimeSeconds));
    }

    channel.writeAndFlush(MqttMessageFactory.newConnAck(MqttConnectReturnCode.CONNECTION_ACCEPTED, true))
            .addListener(cf -> LOGGER.info("CONNECT sent CONNECTION_ACCEPTED"));
}

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

License:Apache License

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

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

    // retrieve authorization information from CONNECT message
    MqttAuthImpl auth = (msg.variableHeader().hasUserName() && msg.variableHeader().hasPassword())
            ? new MqttAuthImpl(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(this, clientIdentifier, auth, will,
            msg.variableHeader().isCleanSession(), msg.variableHeader().version(), msg.variableHeader().name(),
            msg.variableHeader().keepAliveTimeSeconds());

    // 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
        channel.pipeline().addBefore("handler", "idle", new IdleStateHandler(0, 0, timeout));
    }

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

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

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

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
 *///w  w w. ja  v  a 2s  .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:net.anyflow.lannister.packetreceiver.ConnectReceiver.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, MqttConnectMessage msg) throws Exception {
    logger.debug("packet incoming [message={}]", msg.toString());

    Session session = Session.NEXUS.get(ctx.channel().id());
    if (session != null) {
        session.dispose(true); // [MQTT-3.1.0-2]
        return;/*from  ww  w.ja  v  a  2 s.  c  o  m*/
    }

    boolean cleanSession = msg.variableHeader().isCleanSession();
    String clientId = msg.payload().clientIdentifier();

    if (Strings.isNullOrEmpty(clientId)) {
        clientId = generateClientId(ctx, cleanSession);

        if (clientId == null) {
            return;
        }
    }

    if (!filterPlugins(ctx, msg)) {
        return;
    }

    session = Session.NEXUS.get(clientId); // [MQTT-3.1.2-4]
    boolean sessionPresent = !cleanSession && session != null; // [MQTT-3.2.2-1],[MQTT-3.2.2-2],[MQTT-3.2.2-3]

    if (cleanSession) {
        if (session != null) {
            session.dispose(false); // [MQTT-3.1.4-2]
        }
        session = newSession(msg, cleanSession, clientId); // [MQTT-3.1.2-6]
    } else if (session == null) { // [MQTT-3.1.2-4]
        session = newSession(msg, cleanSession, clientId);
    }

    Session.NEXUS.put(session, ctx);

    processRetainedWill(session);

    final Session sessionFinal = session;
    final MqttConnAckMessage acceptMsg = MessageFactory.connack(MqttConnectReturnCode.CONNECTION_ACCEPTED,
            sessionPresent); // [MQTT-3.1.4-4]

    session.send(acceptMsg).addListener(f -> { // [MQTT-3.2.0-1]
        Plugins.SELF.get(ConnectEventListener.class).connectHandled(new ConnectEventArgs() {
            @Override
            public String clientId() {
                return sessionFinal.clientId();
            }

            @Override
            public IMessage will() {
                return sessionFinal.will();
            }

            @Override
            public Boolean cleanSession() {
                return sessionFinal.cleanSession();
            }

            @Override
            public MqttConnectReturnCode returnCode() {
                return MqttConnectReturnCode.CONNECTION_ACCEPTED;
            }
        });

        if (!sessionFinal.cleanSession()) {
            sessionFinal.completeRemainedMessages(); // [MQTT-4.4.0-1]
        }
    });
}

From source file:net.anyflow.lannister.packetreceiver.ConnectReceiver.java

License:Apache License

private Session newSession(MqttConnectMessage msg, boolean cleanSession, String clientId) {
    return new Session(clientId, msg.variableHeader().keepAliveTimeSeconds(), cleanSession,
            newWill(clientId, msg));/*from  w  w  w .j  a v  a 2  s.c o m*/
}

From source file:net.anyflow.lannister.packetreceiver.ConnectReceiver.java

License:Apache License

private Message newWill(String clientId, MqttConnectMessage conn) {
    if (conn.variableHeader().isWillFlag() == false) {
        return null;
    } // [MQTT-3.1.2-12]

    return new Message(-1, conn.payload().willTopic(), clientId, conn.payload().willMessage().getBytes(),
            MqttQoS.valueOf(conn.variableHeader().willQos()), conn.variableHeader().isWillRetain());
}

From source file:net.anyflow.lannister.packetreceiver.ConnectReceiver.java

License:Apache License

private boolean filterPlugins(ChannelHandlerContext ctx, MqttConnectMessage msg) {
    String clientId = msg.payload().clientIdentifier();
    String userName = msg.variableHeader().hasUserName() ? msg.payload().userName() : null;
    String password = msg.variableHeader().hasPassword() ? msg.payload().password() : null;

    if (Plugins.SELF.get(ServiceChecker.class).isServiceAvailable() == false) {
        sendNoneAcceptMessage(ctx, MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
        return false;
    }/*from ww w  . j av a 2s . c o m*/

    if (Plugins.SELF.get(Authenticator.class).isValid(clientId) == false) {
        sendNoneAcceptMessage(ctx, MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED); // [MQTT-3.1.3-9]
        return false;
    }

    if (Plugins.SELF.get(Authenticator.class).isValid(clientId, userName, password) == false) {
        sendNoneAcceptMessage(ctx, MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
        return false;
    }

    if (Plugins.SELF.get(Authorizer.class).isAuthorized(clientId, userName) == false) {
        sendNoneAcceptMessage(ctx, MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
        return false;
    }

    return true;
}

From source file:org.apache.activemq.artemis.core.protocol.mqtt.MQTTProtocolHandler.java

License:Apache License

/**
 * Called during connection./* ww w  .  j  a v a  2s.c  om*/
 *
 * @param connect
 */
void handleConnect(MqttConnectMessage connect, ChannelHandlerContext ctx) throws Exception {
    this.ctx = ctx;
    connectionEntry.ttl = connect.variableHeader().keepAliveTimeSeconds() * 1500L;

    String clientId = connect.payload().clientIdentifier();
    session.getConnectionManager().connect(clientId, connect.payload().userName(),
            connect.payload().passwordInBytes(), connect.variableHeader().isWillFlag(),
            connect.payload().willMessageInBytes(), connect.payload().willTopic(),
            connect.variableHeader().isWillRetain(), connect.variableHeader().willQos(),
            connect.variableHeader().isCleanSession());
}