org.eclipse.paho.client.mqttv3.IMqttToken Java Examples

The following examples show how to use org.eclipse.paho.client.mqttv3.IMqttToken. 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: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onSuccess(IMqttToken asyncActionToken) {
    cancelTimeoutFuture.run();

    connection.isConnecting = false;
    if (connection.reconnectStrategy != null) {
        connection.reconnectStrategy.connectionEstablished();
    }
    List<CompletableFuture<Boolean>> futures = new ArrayList<>();
    connection.subscribers.forEach((topic, subscriberList) -> {
        futures.add(connection.subscribeRaw(topic));
    });

    // As soon as all subscriptions are performed, turn the connection future complete.
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).thenRun(() -> {
        future.complete(true);
        connection.connectionObservers
                .forEach(o -> o.connectionStateChanged(connection.connectionState(), null));
    });
}
 
Example #2
Source File: MqttManager.java    From Bluefruit_LE_Connect_Android with MIT License 6 votes vote down vote up
@Override
public void onSuccess(IMqttToken iMqttToken) {
    if (mMqqtClientStatus == MqqtConnectionStatus.CONNECTING) {
        Log.d(TAG, "Mqtt connect onSuccess");
        mMqqtClientStatus = MqqtConnectionStatus.CONNECTED;
        if (mListener != null) mListener.onMqttConnected();

        MqttSettings settings = MqttSettings.getInstance(mContext);
        String topic = settings.getSubscribeTopic();
        int topicQos = settings.getSubscribeQos();
        if (settings.isSubscribeEnabled() && topic != null) {
            subscribe(topic, topicQos);
        }
    } else if (mMqqtClientStatus == MqqtConnectionStatus.DISCONNECTING) {
        Log.d(TAG, "Mqtt disconnect onSuccess");
        mMqqtClientStatus = MqqtConnectionStatus.DISCONNECTED;
        if (mListener != null) mListener.onMqttDisconnected();
    } else {
        Log.d(TAG, "Mqtt unknown onSuccess");
    }
}
 
Example #3
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onFailure(@Nullable IMqttToken token, @Nullable Throwable error) {
    cancelTimeoutFuture.run();

    final Throwable throwable = (token != null && token.getException() != null) ? token.getException() : error;

    final MqttConnectionState connectionState = connection.connectionState();
    future.complete(false);
    connection.connectionObservers.forEach(o -> o.connectionStateChanged(connectionState, throwable));

    // If we tried to connect via start(), use the reconnect strategy to try it again
    if (connection.isConnecting) {
        connection.isConnecting = false;
        if (connection.reconnectStrategy != null) {
            connection.reconnectStrategy.lostConnection();
        }
    }
}
 
Example #4
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 #5
Source File: FlowableEmitterMqttActionListenerTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenTheConstructorIsCalledWithAValidEmitterThenGetOnErrorReturnsTheEmitter() {

    // Given
    @SuppressWarnings("unchecked")
    final FlowableEmitter<Object> emitter = Mockito
            .mock(FlowableEmitter.class);
    final Throwable ex = Mockito.mock(Throwable.class);
    final FlowableEmitterMqttActionListener<Object> listener = new FlowableEmitterMqttActionListener<Object>(
            emitter) {

        @Override
        public void onSuccess(final IMqttToken asyncActionToken) {
            // Not invoked
        }
    };

    // When
    final OnError onError = listener.getOnError();
    onError.onError(ex);

    // Then
    Mockito.verify(emitter).onError(ex);
}
 
Example #6
Source File: ConnectionListener.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 6 votes vote down vote up
@Override
	public void onSuccess(IMqttToken asyncActionToken) {
		System.out.println(
			String.format(
				"%s successfully connected",
				name));
//		try {
//			subscribeToken = 
//				client.subscribe(
//					TOPIC,
//					QUALITY_OF_SERVICE, 
//					null, 
//					this);
//		} catch (MqttException e) {
//			e.printStackTrace();
//		}
	}
 
Example #7
Source File: AwsIotMqttConnectionListener.java    From aws-iot-device-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
    LOGGER.log(Level.WARNING, (isConnect ? "Connect" : "Disconnect") + " request failure", arg1);

    client.scheduleTask(new Runnable() {
        @Override
        public void run() {
            if (isConnect) {
                client.getConnection().onConnectionFailure();
            } else {
                client.getConnection().onConnectionClosed();
            }
            if (userCallback != null) {
                userCallback.onFailure();
            }
        }
    });
}
 
Example #8
Source File: MqttManager.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
@Override
public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
    Log.d(TAG, "Mqtt onFailure. " + throwable);

    // Remove the auto-connect till the failure is solved
    if (mMqqtClientStatus == MqqtConnectionStatus.CONNECTING) {
        MqttSettings.setConnectedEnabled(mContext, false);
    }

    // Set as an error
    mMqqtClientStatus = MqqtConnectionStatus.ERROR;
    String errorText = mContext.getString(R.string.mqtt_connection_failed) + ". " + throwable.getLocalizedMessage();
    Toast.makeText(mContext, errorText, Toast.LENGTH_LONG).show();

    // Call listener
    MqttManagerListener listener = mWeakListener.get();
    if (listener != null) {
        listener.onMqttDisconnected();
    }
}
 
Example #9
Source File: MqttManager.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
@Override
public void onSuccess(IMqttToken iMqttToken) {
    MqttManagerListener listener = mWeakListener.get();
    if (mMqqtClientStatus == MqqtConnectionStatus.CONNECTING) {
        Log.d(TAG, "Mqtt connect onSuccess");
        mMqqtClientStatus = MqqtConnectionStatus.CONNECTED;
        if (listener != null) {
            listener.onMqttConnected();
        }

        String topic = MqttSettings.getSubscribeTopic(mContext);
        int topicQos = MqttSettings.getSubscribeQos(mContext);
        if (MqttSettings.isSubscribeEnabled(mContext) && topic != null) {
            subscribe(topic, topicQos);
        }
    } else if (mMqqtClientStatus == MqqtConnectionStatus.DISCONNECTING) {
        Log.d(TAG, "Mqtt disconnect onSuccess");
        mMqqtClientStatus = MqqtConnectionStatus.DISCONNECTED;
        if (listener != null) {
            listener.onMqttDisconnected();
        }
    } else {
        Log.d(TAG, "Mqtt unknown onSuccess");
    }
}
 
Example #10
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 #11
Source File: ActionListener.java    From Sparkplug with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The action associated with the object was a failure
 *
 * @param token     This argument is not used
 * @param exception The exception which indicates why the action failed
 */
@Override
public void onFailure(IMqttToken token, Throwable exception) {
    switch (action) {
        case CONNECT:
            connect(exception);
            break;
        case DISCONNECT:
            disconnect(exception);
            break;
        case SUBSCRIBE:
            subscribe(exception);
            break;
        case PUBLISH:
            publish(exception);
            break;
    }

}
 
Example #12
Source File: ActionListener.java    From Sparkplug with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The action associated with this listener has been successful.
 *
 * @param asyncActionToken This argument is not used
 */
@Override
public void onSuccess(IMqttToken asyncActionToken) {
    switch (action) {
        case CONNECT:
            connect();
            break;
        case DISCONNECT:
            disconnect();
            break;
        case SUBSCRIBE:
            subscribe();
            break;
        case PUBLISH:
            publish();
            break;
    }

}
 
Example #13
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 #14
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 #15
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Process notification of a published message having been delivered
 * 
 * @param data
 */
private void messageDeliveredAction(Bundle data) {
	IMqttToken token = removeMqttToken(data);
	if (token != null) {
		if (callback != null) {
			Status status = (Status) data
					.getSerializable(MqttServiceConstants.CALLBACK_STATUS);
			if (status == Status.OK && token instanceof IMqttDeliveryToken) {
				callback.deliveryComplete((IMqttDeliveryToken) token);
			}
		}
	}
}
 
Example #16
Source File: MqttConnection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
	resultBundle.putString(MqttServiceConstants.CALLBACK_ERROR_MESSAGE,
			exception.getLocalizedMessage());

	resultBundle.putSerializable(
			MqttServiceConstants.CALLBACK_EXCEPTION, exception);

	service.callbackToActivity(clientHandle, Status.ERROR, resultBundle);
}
 
Example #17
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 #18
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 #19
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 #20
Source File: PublishFactory.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(final IMqttToken mqttToken) {

    final PublishToken publishToken = new PublishToken() {

        @Override
        public String getClientId() {
            return mqttToken.getClient().getClientId();
        }

        @Override
        public String[] getTopics() {
            return mqttToken.getTopics();
        }

        @Override
        public int getMessageId() {
            return mqttToken.getMessageId();
        }

        @Override
        public boolean getSessionPresent() {
            return mqttToken.getSessionPresent();
        }

    };
    this.emitter.onSuccess(publishToken);
}
 
Example #21
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get a token identified by a string, and remove it from our map
 * 
 * @param data
 * @return the token
 */
private synchronized IMqttToken removeMqttToken(Bundle data) {
	
	String activityToken = data.getString(MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN);
	if (activityToken!=null){
		int tokenNumber = Integer.parseInt(activityToken);
		IMqttToken token = tokenMap.get(tokenNumber);
		tokenMap.delete(tokenNumber);
		return token;
	}
	return null;
}
 
Example #22
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 #23
Source File: MqttAsyncClientEx.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IMqttToken connect(MqttConnectOptions options, Object userContext, IMqttActionListener callback)
        throws MqttException, MqttSecurityException {
    if (!connection.connectTimeout) {
        connection.connectionStateOverwrite = MqttConnectionState.CONNECTED;
        if (connection.connectSuccess) {
            callback.onSuccess(getToken(userContext, callback, null));
        } else {
            callback.onFailure(getToken(userContext, callback, null), new MqttException(0));
        }
    } else {
        connection.connectionStateOverwrite = MqttConnectionState.DISCONNECTED;
    }
    return getToken(userContext, callback, null);
}
 
Example #24
Source File: MqttAsyncClientEx.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IMqttToken unsubscribe(String topic, Object userContext, IMqttActionListener callback) throws MqttException {
    if (connection.unsubscribeSuccess) {
        callback.onSuccess(getToken(userContext, callback, topic));
    } else {
        callback.onFailure(getToken(userContext, callback, topic), new MqttException(0));
    }
    return getToken(userContext, callback, topic);
}
 
Example #25
Source File: FlowableEmitterMqttActionListenerTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void whenTheConstructorIsCalledWithANullEmitterANullPointerExceptionOccurs() {
    new FlowableEmitterMqttActionListener<Object>(null) {

        @Override
        public void onSuccess(final IMqttToken asyncActionToken) {
            // Not invoked
        }

    };
}
 
Example #26
Source File: UnsubscribeFactoryTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenOnSuccessIsCalledThenObserverOnNextAndOnCompletedAreCalled()
        throws Exception {
    final CompletableEmitter observer = Mockito
            .mock(CompletableEmitter.class);
    final UnsubscribeActionListener listener = new UnsubscribeFactory.UnsubscribeActionListener(
            observer);
    final IMqttToken asyncActionToken = Mockito.mock(IMqttToken.class);
    listener.onSuccess(asyncActionToken);
    Mockito.verify(observer).onComplete();
}
 
Example #27
Source File: DisconnectFactoryTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenOnSuccessIsCalledThenObserverOnNextAndOnCompletedAreCalled()
        throws Exception {
    final CompletableEmitter observer = Mockito
            .mock(CompletableEmitter.class);
    final DisconnectActionListener listener = new DisconnectFactory.DisconnectActionListener(
            observer);
    final IMqttToken asyncActionToken = Mockito.mock(IMqttToken.class);
    listener.onSuccess(asyncActionToken);
    Mockito.verify(observer).onComplete();
}
 
Example #28
Source File: TrafficService.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Called when there was a successful MQTT connection
 */
@Override
public void onSuccess(IMqttToken asyncActionToken) {
    ConnectionState state = (ConnectionState) asyncActionToken.getUserContext();
    if (state == ConnectionState.Connecting) {
        Timber.i("Successfully connected");
        onConnect();
    }
}
 
Example #29
Source File: MqttAsyncClientEx.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IMqttToken subscribe(String topic, int qos, Object userContext, IMqttActionListener callback)
        throws MqttException {
    if (connection.publishSuccess) {
        callback.onSuccess(getToken(userContext, callback, topic));
    } else {
        callback.onFailure(getToken(userContext, callback, topic), new MqttException(0));
    }
    return getToken(userContext, callback, topic);
}
 
Example #30
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);
}