Example usage for io.netty.handler.codec.mqtt MqttConnectReturnCode CONNECTION_REFUSED_IDENTIFIER_REJECTED

List of usage examples for io.netty.handler.codec.mqtt MqttConnectReturnCode CONNECTION_REFUSED_IDENTIFIER_REJECTED

Introduction

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

Prototype

MqttConnectReturnCode CONNECTION_REFUSED_IDENTIFIER_REJECTED

To view the source code for io.netty.handler.codec.mqtt MqttConnectReturnCode CONNECTION_REFUSED_IDENTIFIER_REJECTED.

Click Source Link

Usage

From source file:com.caricah.iotracah.core.handlers.ConnectionHandler.java

License:Apache License

/**
 * * 3.1.4 Response/*from w w w.  jav a2  s  .  c  o m*/
 * <p>
 * Note that a Server MAY support multiple protocols (including earlier versions of this protocol)
 * on the same TCP port or other network endpoint. If the Server determines that the protocol is MQTT 3.1.1
 * then it validates the connection attempt as follows.
 * <p>
 * 1.     If the Server does not receive a CONNECT Packet within a reasonable amount of time after
 * the Network Connection is established, the Server SHOULD close the connection.
 * <p>
 * 2.     The Server MUST validate that the CONNECT Packet conforms to section 3.1 and close
 * the Network Connection without sending a CONNACK if it does not conform [MQTT-3.1.4-1].
 * <p>
 * 3.     The Server MAY check that the contents of the CONNECT Packet meet any further restrictions
 * and MAY perform authentication and authorization checks. If any of these checks fail,
 * it SHOULD send an appropriate CONNACK response with a non-zero return code as described
 * in section 3.2 and it MUST close the Network Connection.
 * <p>
 * If validation is successful the Server performs the following steps.
 * <p>
 * 1.     If the ClientId represents a Client already connected to the Server then
 * the Server MUST disconnect the existing Client [MQTT-3.1.4-2].
 * 2.     The Server MUST perform the processing of CleanSession that is described
 * in section 3.1.2.4 [MQTT-3.1.4-3].
 * 3.     The Server MUST acknowledge the CONNECT Packet with a CONNACK Packet
 * containing a zero return code [MQTT-3.1.4-4].
 * 4.     Start message delivery and keep alive monitoring.
 * <p>
 * Clients are allowed to send further Control Packets immediately after sending a CONNECT Packet;
 * Clients need not wait for a CONNACK Packet to arrive from the Server. If the Server rejects the CONNECT,
 * it MUST NOT process any data sent by the Client after the CONNECT Packet [MQTT-3.1.4-5].
 * <p>
 * Non normative comment
 * Clients typically wait for a CONNACK Packet,
 * However, if the Client exploits its freedom to send Control Packets before it receives a CONNACK,
 * it might simplify the Client implementation as it does not have to police the connected state.
 * The Client accepts that any data that it sends before it receives a CONNACK packet from the
 * Server will not be processed if the Server rejects the connection.
 *
 * @return
 * @throws RetriableException
 * @throws UnRetriableException
 */
@Override
public void handle(ConnectMessage connectMessage) throws RetriableException, UnRetriableException {

    log.debug(" handle : client initiating a new connection.");

    /**
     * 2.     The Server MUST validate that the CONNECT Packet conforms to section 3.1 and close
     *        the Network Connection without sending a CONNACK if it does not conform [MQTT-3.1.4-1].
     *
     *        3.1[ The Server MUST process a second CONNECT Packet sent from a Client as a protocol
     *        violation and disconnect the Client [MQTT-3.1.0-2].  See section 4.8 for information about handling errors.]
     *
     *
     */

    try {

        if (!MqttVersion.MQTT_3_1_1.protocolName().equals(connectMessage.getProtocolName())
                && !MqttVersion.MQTT_3_1.protocolName().equals(connectMessage.getProtocolName())) {

            /**
             * If the protocol name is incorrect the Server MAY disconnect the Client,
             * or it MAY continue processing the CONNECT packet in accordance with some other specification.
             * In the latter case, the Server MUST NOT continue to process the CONNECT packet in line with
             * this specification [MQTT-3.1.2-1].
             *
             */

            throw new UnknownProtocalException();

        }

        if (MqttVersion.MQTT_3_1_1.protocolLevel() != connectMessage.getProtocalLevel()
                && MqttVersion.MQTT_3_1.protocolLevel() != connectMessage.getProtocalLevel()) {

            /**
             * The 8 bit unsigned value that represents the revision level of the protocol used by the Client.
             * The value of the Protocol Level field for the version 3.1.1 of the protocol is 4 (0x04).
             * The Server MUST respond to the CONNECT Packet with a CONNACK return code 0x01 (unacceptable protocol level)
             * and then disconnect the Client if the Protocol Level is not supported by the Server [MQTT-3.1.2-2].
             */

            throw new MqttUnacceptableProtocolVersionException();
        } else {
            log.debug(" handle: the required protocal was selected.");
        }

        //TODO:      The Server MUST validate that the reserved flag in the CONNECT Control Packet is set to zero and disconnect the Client if it is not zero [MQTT-3.1.2-3].

        //We now proceed to openning a session on our core service interface.
        boolean cleanSession = connectMessage.isCleanSession();

        /**
         * The Server MUST allow ClientIds which are between 1 and 23 UTF-8 encoded bytes in length,
         * and that contain only the characters
         *           "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" [MQTT-3.1.3-5].
         *
         * The Server MAY allow ClientIds that contain more than 23 encoded bytes.
         * The Server MAY allow ClientIds that contain characters not included in the list given above.
         *
         *
         * A Server MAY allow a Client to supply a ClientId that has a length of zero bytes,
         * however if it does so the Server MUST treat this as a special case and assign a unique ClientId to that Client.
         * It MUST then process the CONNECT packet as if the Client had provided that unique ClientId [MQTT-3.1.3-6].
         *
         */
        String clientIdentifier = connectMessage.getClientId();

        /**
         * If the Client supplies a zero-byte ClientId, the Client MUST also set CleanSession to 1 [MQTT-3.1.3-7].
         *
         * If the Client supplies a zero-byte ClientId with CleanSession set to 0,
         * the Server MUST respond to the CONNECT Packet with a CONNACK return code 0x02 (Identifier rejected)
         * and then close the Network Connection [MQTT-3.1.3-8].
         */
        if ((null == clientIdentifier || clientIdentifier.isEmpty())) {

            if (!cleanSession) {

                throw new MqttIdentifierRejectedException();
            }
        } else {

            //Run a regular expression to check for invalid characters in our clientIdentifier.
            if (!pattern.matcher(clientIdentifier).matches()) {

                throw new MqttIdentifierRejectedException();

            }

        }

        log.debug(" handle: we are ready now to obtain the core session.");

        Observable<IOTClient> newClientObservable = openSubject(connectMessage.getCluster(),
                connectMessage.getNodeId(), connectMessage.getConnectionId(), clientIdentifier, cleanSession,
                connectMessage.getUserName(), connectMessage.getPassword(), connectMessage.getKeepAliveTime(),
                connectMessage.getSourceHost(), connectMessage.getProtocol());

        newClientObservable.subscribe(

                (iotSession) -> {

                    log.debug(" handle: obtained a client session : {}. ", iotSession);

                    /**
                     * 3.     The Server MAY check that the contents of the CONNECT Packet meet any further restrictions
                     *        and MAY perform authentication and authorization checks. If any of these checks fail,
                     *        it SHOULD send an appropriate CONNACK response with a non-zero return code as described
                     *      in section 3.2 and it MUST close the Network Connection.
                     *
                     */

                    //Respond to server with a connection successfull.
                    ConnectAcknowledgeMessage connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(
                            connectMessage.isDup(), connectMessage.getQos(), connectMessage.isRetain(),
                            connectMessage.getKeepAliveTime(), MqttConnectReturnCode.CONNECTION_ACCEPTED);
                    connectAcknowledgeMessage = iotSession.copyTransmissionData(connectAcknowledgeMessage);
                    connectAcknowledgeMessage.setAuthKey(iotSession.getAuthKey());
                    pushToServer(connectAcknowledgeMessage);

                    if (connectMessage.isHasWill()) {

                        /**
                         * If the Will Flag is set to 1 this indicates that, if the Connect request is accepted,
                         * a Will Message MUST be stored on the Server and associated with the Network Connection.
                         * The Will Message MUST be published when the Network Connection is subsequently closed unless
                         * the Will Message has been deleted by the Server on receipt of a DISCONNECT Packet [MQTT-3.1.2-8].
                         */

                        PublishMessage publishMessage = PublishMessage.from(PublishMessage.ID_TO_SHOW_IS_WILL,
                                false, connectMessage.getWillQos(), false, connectMessage.getWillTopic(),
                                ByteBuffer.wrap(connectMessage.getWillMessage().getBytes()), false);
                        publishMessage.setClientId(iotSession.getSessionId());
                        publishMessage.setSessionId(iotSession.getSessionId());
                        publishMessage.setPartitionId(iotSession.getPartitionId());

                        // We have the appropriate id's to save the will.

                        getDatastore().saveWill(iotSession, publishMessage);
                        log.debug(" handle: message has will : {} ", publishMessage);

                    } else {
                        //We need to clear the existing will if any.
                        getDatastore().removeWill(iotSession);
                    }

                    //Perform a reset for our session.
                    getWorker().getSessionResetManager().process(iotSession);

                },

                (e) -> {

                    log.error(" onError : Problems ", e);

                    ConnectAcknowledgeMessage connectAcknowledgeMessage;

                    if (e instanceof AuthenticationException) {

                        connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                                connectMessage.getQos(), connectMessage.isRetain(),
                                connectMessage.getKeepAliveTime(),
                                MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);

                    } else if (e instanceof AuthorizationException) {

                        connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                                connectMessage.getQos(), connectMessage.isRetain(),
                                connectMessage.getKeepAliveTime(),
                                MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);

                    } else {
                        connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                                connectMessage.getQos(), connectMessage.isRetain(),
                                connectMessage.getKeepAliveTime(),
                                MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
                    }

                    connectAcknowledgeMessage.copyTransmissionData(connectMessage);
                    pushToServer(connectAcknowledgeMessage);

                }, () -> {

                });
    } catch (MqttUnacceptableProtocolVersionException | MqttIdentifierRejectedException
            | AuthenticationException | UnknownProtocalException e) {

        log.debug(" handle : Client connection issues ", e);

        //Respond to server with a connection unsuccessfull.
        ConnectAcknowledgeMessage connectAcknowledgeMessage;

        if (e instanceof MqttIdentifierRejectedException) {
            connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                    connectMessage.getQos(), connectMessage.isRetain(), connectMessage.getKeepAliveTime(),
                    MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED);

        } else if (e instanceof MqttUnacceptableProtocolVersionException) {

            connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                    connectMessage.getQos(), connectMessage.isRetain(), connectMessage.getKeepAliveTime(),
                    MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION);

        } else if (e instanceof UnknownProtocalException) {

            connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                    connectMessage.getQos(), connectMessage.isRetain(), connectMessage.getKeepAliveTime(),
                    MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION);

        } else {
            connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(connectMessage.isDup(),
                    connectMessage.getQos(), connectMessage.isRetain(), connectMessage.getKeepAliveTime(),
                    MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
        }

        connectAcknowledgeMessage.copyTransmissionData(connectMessage);
        throw new ShutdownException(connectAcknowledgeMessage);

    } catch (Exception systemError) {

        ConnectAcknowledgeMessage connectAcknowledgeMessage = ConnectAcknowledgeMessage.from(
                connectMessage.isDup(), connectMessage.getQos(), connectMessage.isRetain(),
                connectMessage.getKeepAliveTime(), MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
        connectAcknowledgeMessage.copyTransmissionData(connectMessage);
        log.error(" handle : System experienced the error ", systemError);
        throw new ShutdownException(connectAcknowledgeMessage);

    }

}

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;// w ww . j a  va  2  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.crate.mqtt.protocol.MqttProcessorTest.java

@Test
public void testConnectWithoutClientId() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel();

    // clientId may be null if the session is clean
    MqttMessage msg = connectMessage(null, true);
    processor.handleConnect(ch, (MqttConnectMessage) msg);

    MqttConnAckMessage response = ch.readOutbound();
    assertThat(response.variableHeader().connectReturnCode(), is(MqttConnectReturnCode.CONNECTION_ACCEPTED));
    assertTrue(response.variableHeader().isSessionPresent());

    // clientID must not be null if the session is not clean
    msg = connectMessage(null, false);// w  ww .j a  v a  2  s  . com
    processor.handleConnect(ch, (MqttConnectMessage) msg);

    response = ch.readOutbound();
    assertThat(response.variableHeader().connectReturnCode(),
            is(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED));
    assertFalse(response.variableHeader().isSessionPresent());
}

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  av a2s.  co m
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.j  ava  2s . co  m
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.test.MqttConnectionTest.java

License:Apache License

@Test
public void refusedIdentifierRejected(TestContext context) {

    this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

    try {/*  w  w  w. j  a va  2s . co  m*/
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT),
                "12345", persistence);
        client.connect();
        context.assertTrue(false);
    } catch (MqttException e) {
        context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
        e.printStackTrace();
    }
}

From source file:io.vertx.mqtt.test.server.MqttServerConnectionTest.java

License:Apache License

@Test
public void refusedIdentifierRejected(TestContext context) {

    this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

    try {/*from  www  . ja  v a2 s .  co m*/
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT),
                "12345", persistence);
        client.connect();
        context.fail();
    } catch (MqttException e) {
        context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
    }
}

From source file:io.vertx.mqtt.test.server.MqttServerConnectionTest.java

License:Apache License

@Test
public void refusedClientIdZeroBytes(TestContext context) {

    this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

    try {//from   w  ww  . j a v a 2 s  . c  o  m
        MemoryPersistence persistence = new MemoryPersistence();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "",
                persistence);
        client.connect(options);
        context.fail();
    } catch (MqttException e) {
        context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
        context.assertNotNull(rejection);
    }
}

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

License:Apache License

private String generateClientId(ChannelHandlerContext ctx, boolean cleanSession) {
    if (cleanSession) {
        if (Settings.SELF.getBoolean("mqtt.acceptEmptyClientId", true)) {
            return "Lannister_"
                    + Long.toString(Hazelcast.SELF.generator().getIdGenerator("clientIdGenerator").newId()); // [MQTT-3.1.3-6],[MQTT-3.1.3-7]
        } else {//ww w  . ja  v a 2  s. c om
            sendNoneAcceptMessage(ctx, MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED);
            return null;
        }
    } else {
        sendNoneAcceptMessage(ctx, MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED); // [MQTT-3.1.3-8]
        return null;
    }
}

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;
    }/*ww w .  j ava2 s  . co  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;
}