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

The following examples show how to use org.eclipse.paho.client.mqttv3.IMqttMessageListener. 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: PushListActivity.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void subscribeToMqttTopic() {
    try {
        mqttClient.subscribe("myTopic", 2, new IMqttMessageListener() { // TODO: @paynemiller once API team defines topic, subscribe to it.
            @Override
            public void messageArrived(String topic, MqttMessage message) {
                handleMessage(topic, message);
            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: SubscriberMqttMessageListenerTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenAMessageArrivesThenTheObserverIsNotified()
        throws Exception {
    @SuppressWarnings("unchecked")
    final FlowableEmitter<MqttMessage> observer = Mockito
            .mock(FlowableEmitter.class);
    final IMqttMessageListener listener = new SubscriberMqttMessageListener(
            observer);
    final String expectedTopic = "expected";
    final byte[] expectedPayload = new byte[] { 'a', 'b', 'c' };
    final org.eclipse.paho.client.mqttv3.MqttMessage expectedMessage = new org.eclipse.paho.client.mqttv3.MqttMessage(
            expectedPayload);
    expectedMessage.setQos(2);
    expectedMessage.setId(1);
    expectedMessage.setRetained(true);
    final ArgumentCaptor<SubscribeMessage> actualMessage = ArgumentCaptor
            .forClass(SubscribeMessage.class);
    listener.messageArrived(expectedTopic, expectedMessage);
    Mockito.verify(observer).onNext(actualMessage.capture());
    Assert.assertArrayEquals(expectedPayload,
            actualMessage.getValue().getPayload());
    Assert.assertEquals(2, actualMessage.getValue().getQos());
    Assert.assertEquals(1, actualMessage.getValue().getId());
    Assert.assertTrue(actualMessage.getValue().isRetained());
    Assert.assertEquals(expectedTopic, actualMessage.getValue().getTopic());
}
 
Example #3
Source File: SubscribeFactoryTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCreateIsCalledThenAnObservableIsReturned()
        throws Exception {
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    final SubscribeFactory factory = new SubscribeFactory(client);
    final ArgumentCaptor<IMqttActionListener> actionListener = ArgumentCaptor
            .forClass(IMqttActionListener.class);
    final ArgumentCaptor<IMqttMessageListener[]> messageListener = ArgumentCaptor
            .forClass(IMqttMessageListener[].class);
    final String[] topics = new String[] { "topic1", "topic2" };
    final int[] qos = new int[] { 1, 2 };
    final Flowable<SubscribeMessage> obs = factory.create(topics, qos,
            BackpressureStrategy.ERROR);
    Assert.assertNotNull(obs);
    obs.subscribe();
    Mockito.verify(client).subscribe(Matchers.same(topics),
            Matchers.same(qos), Matchers.isNull(), actionListener.capture(),
            messageListener.capture());
    Assert.assertTrue(actionListener
            .getValue() instanceof SubscribeFactory.SubscribeActionListener);
    Assert.assertTrue(messageListener
            .getValue() instanceof SubscriberMqttMessageListener[]);
    Assert.assertEquals(2, messageListener.getValue().length);
}
 
Example #4
Source File: SubscribeFactoryTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCreateIsCalledAndAnErrorOccursThenObserverOnErrorIsCalled()
        throws Throwable {
    this.expectedException.expectCause(isA(MqttException.class));
    final ArgumentCaptor<IMqttActionListener> actionListener = ArgumentCaptor
            .forClass(IMqttActionListener.class);
    final ArgumentCaptor<IMqttMessageListener[]> messageListener = ArgumentCaptor
            .forClass(IMqttMessageListener[].class);
    final String[] topics = new String[] { "topic1", "topic2" };
    final int[] qos = new int[] { 1, 2 };
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    Mockito.when(client.subscribe(Matchers.same(topics), Matchers.same(qos),
            Matchers.isNull(), actionListener.capture(),
            messageListener.capture()))
            .thenThrow(new MqttException(
                    MqttException.REASON_CODE_CLIENT_CONNECTED));
    final SubscribeFactory factory = new SubscribeFactory(client);
    final Flowable<SubscribeMessage> obs = factory.create(topics, qos,
            BackpressureStrategy.ERROR);
    obs.blockingFirst();
}
 
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: MqttConnection.java    From Sparkplug with Eclipse Public License 1.0 6 votes vote down vote up
public void subscribe(String[] topicFilters, int[] qos, String invocationContext, String activityToken, IMqttMessageListener[] messageListeners) {
	service.traceDebug(TAG, "subscribe({" + Arrays.toString(topicFilters) + "}," + Arrays.toString(qos) + ",{"
			+ invocationContext + "}, {" + activityToken + "}");
	final Bundle resultBundle = new Bundle();
	resultBundle.putString(MqttServiceConstants.CALLBACK_ACTION, MqttServiceConstants.SUBSCRIBE_ACTION);
	resultBundle.putString(MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN, activityToken);
	resultBundle.putString(MqttServiceConstants.CALLBACK_INVOCATION_CONTEXT, invocationContext);
	if((myClient != null) && (myClient.isConnected())){
		IMqttActionListener listener = new MqttConnectionListener(resultBundle);
		try {

			myClient.subscribe(topicFilters, qos,messageListeners);
		} catch (Exception e){
			handleException(resultBundle, e);
		}
	} else {
		resultBundle.putString(MqttServiceConstants.CALLBACK_ERROR_MESSAGE, NOT_CONNECTED);
		service.traceError("subscribe", NOT_CONNECTED);
		service.callbackToActivity(clientHandle, Status.ERROR, resultBundle);
	}
}
 
Example #7
Source File: MqttUsage.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public void consumeRaw(String topicName, int count, long timeout, TimeUnit unit, Runnable completion,
        IMqttMessageListener messageListener) {
    AtomicLong readCounter = new AtomicLong();
    this.consumeRaw(topicName, this.continueIfNotExpired(() -> readCounter.get() < (long) count, timeout, unit), completion,
            (top, msg) -> {
                messageListener.messageArrived(top, msg);
                readCounter.incrementAndGet();
            });
}
 
Example #8
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(String[] topicFilters, IMqttMessageListener[] messageListeners) throws MqttException {
    this.mqttClient.subscribe(topicFilters, messageListeners);
}
 
Example #9
Source File: MqttTestClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String[] strings, int[] ints, IMqttMessageListener[] iMqttMessageListeners) throws MqttException {
    return null;
}
 
Example #10
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(String topicFilter, int qos, IMqttMessageListener messageListener) throws MqttException {
    this.mqttClient.subscribe(topicFilter, qos, messageListener);
}
 
Example #11
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException {
    this.mqttClient.subscribe(topicFilters, qos, messageListeners);
}
 
Example #12
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String topicFilter, IMqttMessageListener messageListener) throws MqttException {
    return this.mqttClient.subscribeWithResponse(topicFilter, messageListener);
}
 
Example #13
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String topicFilter, int qos, IMqttMessageListener messageListener) throws MqttException {
    return this.mqttClient.subscribeWithResponse(topicFilter, qos, messageListener);
}
 
Example #14
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String[] topicFilters, IMqttMessageListener[] messageListeners) throws MqttException {
    return this.mqttClient.subscribeWithResponse(topicFilters, messageListeners);
}
 
Example #15
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException {
    return this.mqttClient.subscribeWithResponse(topicFilters, qos, messageListeners);
}
 
Example #16
Source File: MqttTestClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String s, IMqttMessageListener iMqttMessageListener) throws MqttException {
    return null;
}
 
Example #17
Source File: MqttTestClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String s, int i, IMqttMessageListener iMqttMessageListener) throws MqttException {
    return null;
}
 
Example #18
Source File: MqttTestClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribeWithResponse(String[] strings, IMqttMessageListener[] iMqttMessageListeners) throws MqttException {
    return null;
}
 
Example #19
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(String topicFilter, IMqttMessageListener messageListener) throws MqttException {
    this.mqttClient.subscribe(topicFilter, messageListener);
}
 
Example #20
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribe(String[] topicFilters, int[] qos, Object userContext, IMqttActionListener callback, IMqttMessageListener[] messageListeners)
        throws MqttException {
    return mqttClient.subscribe(topicFilters, qos, userContext, callback, messageListeners);
}
 
Example #21
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribe(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException {
    return mqttClient.subscribe(topicFilters, qos, messageListeners);
}
 
Example #22
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribe(String topicFilter, int qos, IMqttMessageListener messageListener) throws MqttException {
    return mqttClient.subscribe(topicFilter, qos, messageListener);
}
 
Example #23
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttToken subscribe(String topicFilter, int qos, Object userContext, IMqttActionListener callback, IMqttMessageListener messageListener) throws MqttException {
    return mqttClient.subscribe(topicFilter, qos, userContext, callback, messageListener);
}
 
Example #24
Source File: AsyncPubSubITCase.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
private void itCanPubAndSubToBroker(final String brokerUrl)
        throws Throwable {

    // Create async MQTT clients
    final MqttAsyncClient pubClient = new MqttAsyncClient(brokerUrl,
            CLIENT_ID + "-pub");
    AsyncPahoUtils.connect(pubClient);
    final MqttAsyncClient subClient = new MqttAsyncClient(brokerUrl,
            CLIENT_ID + "-sub");
    AsyncPahoUtils.connect(subClient);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<MqttMessage> msg = new AtomicReference<MqttMessage>();

    // Subscribe
    final IMqttMessageListener messageListener = new IMqttMessageListener() {

        @Override
        public void messageArrived(final String topic,
                final MqttMessage message) throws Exception {
            msg.set(message);
            latch.countDown();
        }
    };
    AsyncPahoUtils.subscribe(subClient, TOPIC, messageListener);

    // Publish the sensor data
    final byte[] expectedPayload = new byte[] { 'a', 'b', 'c' };
    AsyncPahoUtils.publish(pubClient, TOPIC, expectedPayload);

    // Await message publish and receipt
    latch.await();

    // Get the message received by the callback
    final MqttMessage receivedMessage = msg.get();
    Assert.assertNotNull(receivedMessage);
    Assert.assertNotNull(receivedMessage.getPayload());
    Assert.assertArrayEquals(expectedPayload, receivedMessage.getPayload());

    // Close the clients
    AsyncPahoUtils.disconnect(pubClient);
    AsyncPahoUtils.disconnect(subClient);

}
 
Example #25
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Subscribe to multiple topics, each of which may include wildcards.
 *
 * <p>Provides an optimized way to subscribe to multiple topics compared to
 * subscribing to each one individually.</p>
 *
 * @see #subscribe(String[], int[], Object, IMqttActionListener)
 *
 * @param topicFilters one or more topics to subscribe to, which can include wildcards
 * @param qos the maximum quality of service at which to subscribe. Messages
 * published at a lower quality of service will be received at the published
 * QoS.  Messages published at a higher quality of service will be received using
 * the QoS specified on the subscribe.
 * @param userContext optional object used to pass context to the callback. Use
 * null if not required.
 * @param callback optional listener that will be notified when subscribe
 * has completed
 * @param messageListeners an array of callbacks to handle incoming messages
 * @return token used to track and wait for the subscribe to complete. The token
 * will be passed to callback methods if set.
 * @throws MqttException if there was an error registering the subscription.
 */
public IMqttToken subscribe(String[] topicFilters, int[] qos, Object userContext, IMqttActionListener callback, IMqttMessageListener[] messageListeners) throws MqttException {
	IMqttToken token = new MqttTokenAndroid(this, userContext, callback, topicFilters);
	String activityToken = storeToken(token);
	mqttService.subscribe(clientHandle, topicFilters, qos, null, activityToken, messageListeners);

	return null;
}
 
Example #26
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Subscribe to multiple topics, each of which may include wildcards.
 *
 * <p>Provides an optimized way to subscribe to multiple topics compared to
 * subscribing to each one individually.</p>
 *
 * @see #subscribe(String[], int[], Object, IMqttActionListener)
 *
 * @param topicFilters one or more topics to subscribe to, which can include wildcards
 * @param qos the maximum quality of service at which to subscribe. Messages
 * published at a lower quality of service will be received at the published
 * QoS.  Messages published at a higher quality of service will be received using
 * the QoS specified on the subscribe.
 * @param messageListeners an array of callbacks to handle incoming messages
 * @return token used to track and wait for the subscribe to complete. The token
 * will be passed to callback methods if set.
 * @throws MqttException if there was an error registering the subscription.
 */
public IMqttToken subscribe(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException {
	
	return subscribe(topicFilters, qos, null, null, messageListeners);
}
 
Example #27
Source File: MqttTestClient.java    From nifi with Apache License 2.0 2 votes vote down vote up
@Override
public void subscribe(String s, IMqttMessageListener iMqttMessageListener) throws MqttException, MqttSecurityException {

}
 
Example #28
Source File: MqttTestClient.java    From nifi with Apache License 2.0 2 votes vote down vote up
@Override
public void subscribe(String[] strings, IMqttMessageListener[] iMqttMessageListeners) throws MqttException {

}
 
Example #29
Source File: MqttTestClient.java    From nifi with Apache License 2.0 2 votes vote down vote up
@Override
public void subscribe(String s, int i, IMqttMessageListener iMqttMessageListener) throws MqttException {

}
 
Example #30
Source File: MqttTestClient.java    From nifi with Apache License 2.0 2 votes vote down vote up
@Override
public void subscribe(String[] strings, int[] ints, IMqttMessageListener[] iMqttMessageListeners) throws MqttException {

}