Java Code Examples for org.eclipse.paho.client.mqttv3.IMqttToken#waitForCompletion()

The following examples show how to use org.eclipse.paho.client.mqttv3.IMqttToken#waitForCompletion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MqttAsyncCallback.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
protected void reConnect() {
    if (mqttAsyncClient != null) {
        try {
            connectionListener = new MqttConnectionListener(connectionConsumer);
            IMqttToken token = mqttAsyncClient.connect(connectOptions);

            token.waitForCompletion();
            if (!mqttAsyncClient.isConnected()) {
                connectionListener.onFailure();
            }

            if (mqttAsyncClient.isConnected()) {
                int qosLevel = Integer.parseInt(mqttProperties.getProperty(MqttConstants.MQTT_QOS));
                if (confac.getTopic() != null) {
                    mqttAsyncClient.subscribe(confac.getTopic(), qosLevel);
                }
                log.info("MQTT inbound endpoint " + name + " re-connected to the broker");
            }
        } catch (MqttException ex) {
            log.error("Error while trying to subscribe to the remote.", ex);
            connectionListener.onFailure();
        }
    }
}
 
Example 2
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    try {
        MessageListener listener = new MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse(this.topicName, listener);
        token.waitForCompletion();

        Assert.assertEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());

        MqttMessage message = new MqttMessage(this.content.getBytes(StandardCharsets.UTF_8));
        this.mqttClient.publish(this.topicName, message);

        Thread.sleep(this.actionTimeout);
        Assert.assertTrue(listener.received > 0);
    } catch (MqttException | InterruptedException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 3
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    try {
        MessageListener listener = new MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse(this.topicName, listener);
        token.waitForCompletion();

        Assert.assertEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());

        MqttMessage message = new MqttMessage(this.content.getBytes(StandardCharsets.UTF_8));
        this.mqttClient.publish(this.topicName, message);

        Thread.sleep(this.actionTimeout);
        Assert.assertTrue(listener.received > 0);
    } catch (MqttException | InterruptedException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 4
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeWildcard() {
    try {
        MessageListener listener = new MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse("#", listener);
        token.waitForCompletion();

        Assert.assertEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());

        MqttMessage message = new MqttMessage(this.content.getBytes(StandardCharsets.UTF_8));
        this.mqttClient.publish(this.topicName, message);

        Thread.sleep(this.actionTimeout);
        Assert.assertTrue(listener.received > 0);
    } catch (Exception e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 5
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeBatch() {
    try {
        MessageListener listener = new MessageListener();
        String[] topics = {this.topicName, "not_exist"};
        IMqttToken token = this.mqttClient.subscribeWithResponse(topics, new IMqttMessageListener[]{listener, listener});
        token.waitForCompletion();

        // do right
        Assert.assertEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());
        // not exist
        Assert.assertNotEquals(token.getGrantedQos()[1], MqttQoS.AT_LEAST_ONCE.value());

        MqttMessage message = new MqttMessage(this.content.getBytes(StandardCharsets.UTF_8));
        this.mqttClient.publish(this.topicName, message);

        Thread.sleep(this.actionTimeout);
        Assert.assertTrue(listener.received > 0);
    } catch (Exception e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 6
Source File: Bridge.java    From MQTTKafkaBridge with Apache License 2.0 6 votes vote down vote up
private void connect(String serverURI, String clientId, String zkConnect) throws MqttException {
	
	mqtt = new MqttAsyncClient(serverURI, clientId);
	mqtt.setCallback(this);
	IMqttToken token = mqtt.connect();
	Properties props = new Properties();
	
	//Updated based on Kafka v0.8.1.1
	props.put("metadata.broker.list", "localhost:9092");
       props.put("serializer.class", "kafka.serializer.StringEncoder");
       props.put("partitioner.class", "example.producer.SimplePartitioner");
       props.put("request.required.acks", "1");
	
	ProducerConfig config = new ProducerConfig(props);
	kafkaProducer = new Producer<String, String>(config);
	token.waitForCompletion();
	logger.info("Connected to MQTT and Kafka");
}
 
Example 7
Source File: MqttConnectionConsumer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public void execute() {
    if (mqttAsyncClient != null) {
        if (mqttAsyncClient.isConnected()) {
            //do nothing just return
            //this is a case for manually tenant loading case
            //as we maintain connection when the tenant is manually loaded ( no connection
            //disconnect and reconnect )
            return;
        } else {
            try {
                connectionListener = new MqttConnectionListener(this);
                IMqttToken token = mqttAsyncClient.connect(connectOptions);

                token.waitForCompletion();
                if (!mqttAsyncClient.isConnected()) {
                    connectionListener.onFailure();
                }

                if (mqttAsyncClient.isConnected()) {
                    int qosLevel = Integer.parseInt(mqttProperties.getProperty(MqttConstants.MQTT_QOS));
                    if (confac.getTopic() != null) {
                        mqttAsyncClient.subscribe(confac.getTopic(), qosLevel);
                    }
                    log.info("MQTT inbound endpoint " + this.name + " connected to the broker");
                }
            } catch (MqttException ex) {
                log.error("Error while trying to subscribe to the remote ", ex);
                connectionListener.onFailure();
            }
        }
    }
}
 
Example 8
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscribeNotExist() {
    try {
        MQTTTest.MessageListener listener = new MQTTTest.MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse("not_exist", listener);
        token.waitForCompletion();

        Assert.assertNotEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 9
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscribeNotExist() {
    try {
        MessageListener listener = new MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse("not_exist", listener);
        token.waitForCompletion();

        Assert.assertNotEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 10
Source File: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void subscribe(String topicName, int qos) throws MqttException {
    mqttMessageStorage = new ConcurrentLinkedQueue<Message>();
    receivedMessageCounter = new AtomicLong(0);

    // Subscribe to the requested topic.
    // Control is returned as soon client has accepted to deliver the subscription.
    // Use a token to wait until the subscription is in place.
    log.info("Subscribing to topic \"" + topicName + "\" qos " + qos);
    IMqttToken subToken = client.subscribe(topicName, qos, null, null);
    subToken.waitForCompletion();
    log.info("Subscribed to topic \"" + topicName);
}
 
Example 11
Source File: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void disconnect() throws MqttException {
    // Disconnect the client
    // Issue the disconnect and then use the token to wait until
    // the disconnect completes.
    log.info("Disconnecting");
    IMqttToken discToken = client.disconnect(null, null);
    discToken.waitForCompletion();
    log.info("Disconnected");
}
 
Example 12
Source File: Bridge.java    From MQTTKafkaBridge with Apache License 2.0 4 votes vote down vote up
private void reconnect() throws MqttException {
	IMqttToken token = mqtt.connect();
	token.waitForCompletion();
}
 
Example 13
Source File: QoS1Consumer.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("QoS1Consumer initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttAsyncClient mqttClient = new MqttAsyncClient(host, "HelloWorldQoS1Consumer");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());

        // Connect the client
        System.out.println("Connecting to Solace messaging at " + host);
        IMqttToken conToken = mqttClient.connect(connOpts);
        conToken.waitForCompletion(10000);
        if (!conToken.isComplete() || conToken.getException() != null) {
            System.out.println("Error connecting: " + conToken.getException());
            System.exit(-1);
        }
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);

        // Callback - Anonymous inner-class for receiving messages
        mqttClient.setCallback(new MqttCallback() {

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // Called when a message arrives from the server that
                // matches any subscription made by the client
                String time = new Timestamp(System.currentTimeMillis()).toString();
                System.out.println("\nReceived a Message!" +
                        "\n\tTime:    " + time + 
                        "\n\tTopic:   " + topic + 
                        "\n\tMessage: " + new String(message.getPayload()) + 
                        "\n\tQoS:     " + message.getQos() + "\n");
                latch.countDown(); // unblock main thread
            }

            public void connectionLost(Throwable cause) {
                System.out.println("Connection to Solace messaging lost!" + cause.getMessage());
                latch.countDown();
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });

        // Topic filter the client will subscribe to
        final String subTopic = "Q/tutorial";

        // Subscribe client to the topic filter with QoS level of 1
        System.out.println("Subscribing client to topic: " + subTopic);
        IMqttToken subToken = mqttClient.subscribe(subTopic, 1);
        subToken.waitForCompletion(10000);
        if (!subToken.isComplete() || subToken.getException() != null) {
            System.out.println("Error subscribing: " + subToken.getException());
            System.exit(-1);
        }
        if (subToken.getGrantedQos()[0] != 1) {
            System.out.println("Expected OoS level 1 but got OoS level: " + subToken.getGrantedQos()[0]);
            System.exit(-1);
        }
        System.out.println("Subscribed with OoS level 1 and waiting to receive msgs");

        // Wait for the message to be received
        try {
            latch.await(); // block here until message received, and latch will flip
        } catch (InterruptedException e) {
            System.out.println("I was awoken while waiting");
        }

        // Disconnect the client
        mqttClient.disconnect();
        System.out.println("Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
Example 14
Source File: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an instance of the sample client wrapper
 *
 * @param brokerUrl    the url to connect to
 * @param clientId     the client id to connect with
 * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions)
 * @param userName     the username to connect with
 * @param password     the password for the user
 * @throws MqttException
 */
public AsyncClient(String brokerUrl, String clientId, boolean cleanSession,
                   String userName, String password, int keepAlive) throws MqttException {
    this.brokerUrl = brokerUrl;

    String testPlanFileDir = System.getProperty("java.io.tmpdir") + File.separator + "mqtt" + File.separator +
                                                        clientId + File.separator + Thread.currentThread().getId();
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(testPlanFileDir);

    try {
        // Construct the connection options object that contains connection parameters
        // such as cleanSession and LWT
        MqttConnectOptions conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(cleanSession);
        if (password != null && !password.isEmpty()) {
            conOpt.setPassword(password.toCharArray());
        }
        if (userName != null && !userName.isEmpty()) {
            conOpt.setUserName(userName);
        }

        // Setting keep alive time
        conOpt.setKeepAliveInterval(keepAlive);

        // Construct a non-blocking MQTT client instance
        client = new MqttAsyncClient(this.brokerUrl, clientId, dataStore);

        // Set this wrapper as the callback handler
        client.setCallback(this);

        // Connect to the MQTT server
        // issue a non-blocking connect and then use the token to wait until the
        // connect completes. An exception is thrown if connect fails.
        log.info("Connecting to " + brokerUrl + " with client ID '" + client.getClientId() + "' and cleanSession " +
                 "                                  is " + String.valueOf(cleanSession) + " as an async clientt");
        IMqttToken conToken = client.connect(conOpt, null, null);
        conToken.waitForCompletion();
        log.info("Connected");

    } catch (MqttException e) {
        log.info("Unable to set up client: " + e.toString());
    }
}
 
Example 15
Source File: AlMqttClient.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public IMqttToken connectWithResult(MqttConnectOptions options, IMqttActionListener callback) throws MqttSecurityException, MqttException {
    IMqttToken tok = aClient.connect(options, null, callback);
    tok.waitForCompletion(getTimeToWait());
    return tok;
}