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

The following examples show how to use org.eclipse.paho.client.mqttv3.IMqttDeliveryToken. 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: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void publish(String topicName, int qos, byte[] payload, boolean isRetained) throws MqttException {
    // Construct the message to send
    MqttMessage message = new MqttMessage(payload);
    message.setRetained(isRetained);
    message.setQos(qos);

    // Send the message to the server, control is returned as soon
    // as the MQTT client has accepted to deliver the message.
    // Use the delivery token to wait until the message has been
    // delivered
    IMqttDeliveryToken pubToken = client.publish(topicName, message, null, null);
    pubToken.waitForCompletion();
    log.info("Published");
}
 
Example #2
Source File: TestMqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private MqttClient receive(final List<MqttMessage> received) throws MqttException, MqttSecurityException {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {
        
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            received.add(message);
            System.out.println(message);
        }
        
        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
        
        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC);
    client.setCallback(callback);
    return client;
}
 
Example #3
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 6 votes vote down vote up
public MqttAndroidClient createClient(String id, String serverURI, String clientId) {
    MqttClientPersistence mqttClientPersistence = new MemoryPersistence();
    MqttAndroidClient client = new MqttAndroidClient(MyApplication.getContext(), serverURI, clientId, mqttClientPersistence);
    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            LogUtil.e("connectionLost");
            EventBus.getDefault().post(new MQTTActionEvent(Constant.MQTTStatusConstant.CONNECTION_LOST, null, cause));

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            LogUtil.d("topic is " + topic + ",message is " + message.toString() + ", qos is " + message.getQos());
            EventBus.getDefault().postSticky(new MessageEvent(new EmqMessage(topic, message)));

        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            LogUtil.d("deliveryComplete");


        }
    });

    mClients.put(id, client);

    return client;

}
 
Example #4
Source File: MQTTClient.java    From amazon-mq-workshop with Apache License 2.0 6 votes vote down vote up
private static void receiveMessages(final MqttClient client, final MqttConnectOptions options,final  String destination) throws Exception {
    new Thread(new Runnable() {
        public void run() {
            try {
                client.setCallback(new MqttCallback() {
                    public void connectionLost(Throwable cause) {
                    }

                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        System.out.println(String.format("%s - Receiver: received '%s'", df.format(new Date()), new String(message.getPayload())));
                    }

                    public void deliveryComplete(IMqttDeliveryToken token) {
                    }
                });
                client.connect(options);
                System.out.println(String.format("Successfully connected to %s", client.getServerURI()));

                client.subscribe(destination);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }).start();
}
 
Example #5
Source File: PahoMQTTTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);

   MqttClient consumer = createPahoClient("consumerId");
   MqttClient producer = createPahoClient("producerId");

   consumer.connect();
   consumer.subscribe("test");
   consumer.setCallback(new MqttCallback() {
      @Override
      public void connectionLost(Throwable cause) {

      }

      @Override
      public void messageArrived(String topic, MqttMessage message) throws Exception {
         latch.countDown();
      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect();
   producer.publish("test", "hello".getBytes(), 1, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
}
 
Example #6
Source File: MqttConnection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Callback to indicate a message has been delivered (the exact meaning of
 * "has been delivered" is dependent on the QOS value)
 * 
 * @param messageToken
 *            the messge token provided when the message was originally sent
 */
@Override
public void deliveryComplete(IMqttDeliveryToken messageToken) {

	service.traceDebug(TAG, "deliveryComplete(" + messageToken + ")");

	MqttMessage message = savedSentMessages.remove(messageToken);
	if (message != null) { // If I don't know about the message, it's
		// irrelevant
		String topic = savedTopics.remove(messageToken);
		String activityToken = savedActivityTokens.remove(messageToken);
		String invocationContext = savedInvocationContexts
				.remove(messageToken);

		Bundle resultBundle = messageToBundle(null, topic, message);
		if (activityToken != null) {
			resultBundle.putString(MqttServiceConstants.CALLBACK_ACTION,
					MqttServiceConstants.SEND_ACTION);
			resultBundle.putString(
					MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN,
					activityToken);
			resultBundle.putString(
					MqttServiceConstants.CALLBACK_INVOCATION_CONTEXT,
					invocationContext);
	
			service.callbackToActivity(clientHandle, Status.OK,
					resultBundle);
		}
		resultBundle.putString(MqttServiceConstants.CALLBACK_ACTION,
				MqttServiceConstants.MESSAGE_DELIVERED_ACTION);
		service.callbackToActivity(clientHandle, Status.OK, resultBundle);
	}

	// this notification will have kept the connection alive but send the previously sechudled ping anyway
}
 
Example #7
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 #8
Source File: MqttTopicSubscriber.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken deliveryToken) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Message delivery is complete: %s",
                ((deliveryToken != null) ? deliveryToken.toString() : "")));
    }
}
 
Example #9
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
	// TODO Auto-generated method stub
	log.debug("[MqttClientHandler.deliveryComplete] deliveryComplete, topic : " +  Arrays.toString(token.getTopics()));

	if (serverListener != null)
	{
		serverListener.completedMqttDelivery(token.getMessageId());
	}
}
 
Example #10
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
	// TODO Auto-generated method stub
	log.debug("[MqttClientHandler.deliveryComplete] deliveryComplete, topic : " +  Arrays.toString(token.getTopics()));

	if (serverListener != null)
	{
		serverListener.completedMqttDelivery(token.getMessageId());
	}
}
 
Example #11
Source File: MqttCallBackImplTest.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@BeforeClass
  public static void setUpClass()
          throws Exception {
clientMock = Mockito.mock(IMqttAsyncClient.class);
messageMock = Mockito.mock(MqttMessage.class);
tokenMock = Mockito.mock(IMqttDeliveryToken.class);
causeMock = Mockito.mock(Throwable.class);
  }
 
Example #12
Source File: MqttAsyncClientEx.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos, boolean retained, Object userContext,
        IMqttActionListener callback) throws MqttException, MqttPersistenceException {

    if (connection.publishSuccess) {
        callback.onSuccess(getToken(userContext, callback, topic));
    } else {
        callback.onFailure(getToken(userContext, callback, topic), new MqttException(0));
    }
    return getDeliveryToken(userContext, callback, topic);
}
 
Example #13
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Publish a message to the broker with the given QoS and retained flag.
 *
 * @param topic The topic
 * @param payload The message payload
 * @param qos The quality of service for this message
 * @param retain Set to true to retain the message on the broker
 * @param listener A listener to be notified of success or failure of the delivery.
 */
public void publish(String topic, byte[] payload, int qos, boolean retain, MqttActionCallback listener) {
    MqttAsyncClient client_ = client;
    if (client_ == null) {
        listener.onFailure(topic, new MqttException(0));
        return;
    }
    try {
        IMqttDeliveryToken deliveryToken = client_.publish(topic, payload, qos, retain, listener, actionCallback);
        logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        listener.onFailure(topic, new MqttException(e));
    }
}
 
Example #14
Source File: PushListActivity.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void configureMqttClient() {
    try {
        mqttClient = new MqttAsyncClient("tcp://test-io.Pushfish.api.push.fish:1883", "android", new MemoryPersistence());
        mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                Log.i(PushListActivity.class.getName(), "MQTT Connection successful!");
            }

            @Override
            public void connectionLost(Throwable cause) {
                Log.w(PushListActivity.class.getName(), "MQTT Connection was lost!");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                handleMessage(topic, message);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: MqttSubscriberClient.java    From product-iots with Apache License 2.0 4 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    // Not implemented
}
 
Example #16
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 4 votes vote down vote up
public void deliveryComplete(IMqttDeliveryToken token) {
}
 
Example #17
Source File: Mqttv3Client.java    From jframe with Apache License 2.0 4 votes vote down vote up
IMqttDeliveryToken publish(String id, String topic, MqttMessage message, Object userContext,
IMqttActionListener callback);
 
Example #18
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttDeliveryToken publish(String topic, MqttMessage message, Object userContext, IMqttActionListener callback) throws MqttException, MqttPersistenceException {
    return mqttClient.publish(topic, message, userContext, callback);
}
 
Example #19
Source File: DefaultMqttHandler.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    System.out.println("deliveryComplete ==> "+ iMqttDeliveryToken.getMessageId());
}
 
Example #20
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttDeliveryToken[] getPendingDeliveryTokens() {
    return this.mqttClient.getPendingDeliveryTokens();
}
 
Example #21
Source File: MqttAsyncCallback.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
 
Example #22
Source File: MQTTStreamSource.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Override public void deliveryComplete( IMqttDeliveryToken token ) {
  // no op
}
 
Example #23
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 #24
Source File: SparkplugRaspberryPiExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
public void deliveryComplete(IMqttDeliveryToken token) {
	// System.out.println("Published message: " + token);
}
 
Example #25
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Publishes a message to a topic on the server.
 * <p>
 * A convenience method, which will create a new {@link MqttMessage} object
 * with a byte array payload, the specified QoS and retained, then publish it.
 * </p>
 * 
 * @param topic
 *            to deliver the message to, for example "finance/stock/ibm".
 * @param payload
 *            the byte array to use as the payload
 * @param qos
 *            the Quality of Service to deliver the message at. Valid values
 *            are 0, 1 or 2.
 * @param retained
 *            whether or not this message should be retained by the server.
 * @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 message delivery
 *            has completed to the requested quality of service
 * @return token used to track and wait for the publish to complete. The
 *         token will be passed to any callback that has been set.
 * @throws MqttPersistenceException
 *             when a problem occurs storing the message
 * @throws IllegalArgumentException
 *             if value of QoS is not 0, 1 or 2.
 * @throws MqttException
 *             for other errors encountered while publishing the message.
 *             For instance client not connected.
 * @see #publish(String, MqttMessage, Object, IMqttActionListener)
 */
@Override
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos,
		boolean retained, Object userContext, IMqttActionListener callback)
		throws MqttException, MqttPersistenceException {

	MqttMessage message = new MqttMessage(payload);
	message.setQos(qos);
	message.setRetained(retained);
	MqttDeliveryTokenAndroid token = new MqttDeliveryTokenAndroid(
			this, userContext, callback, message);
	String activityToken = storeToken(token);
	IMqttDeliveryToken internalToken = mqttService.publish(clientHandle,
			topic, payload, qos, retained, null, activityToken);
	token.setDelegate(internalToken);
	return token;
}
 
Example #26
Source File: Mqttv3ClientImpl.java    From jframe with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttDeliveryToken publish(String id, String topic, MqttMessage message) {
    return publish(id, topic, message, null, null);
}
 
Example #27
Source File: ActorPushService.java    From actor-platform with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public synchronized void deliveryComplete(IMqttDeliveryToken token) {
    // Ignore
}
 
Example #28
Source File: TopicSubscriber.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicSubscriber initializing...");

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

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldSub");
        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);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);
        
        // Topic filter the client will subscribe to
        final String subTopic = "T/GettingStarted/pubsub";
        
        // 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) {
            }

        });
        
        // Subscribe client to the topic filter and a QoS level of 0
        System.out.println("Subscribing client to topic: " + subTopic);
        mqttClient.subscribe(subTopic, 0);
        System.out.println("Subscribed");

        // 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 #29
Source File: MqttTestClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public IMqttDeliveryToken[] getPendingDeliveryTokens() {
    return new IMqttDeliveryToken[0];
}
 
Example #30
Source File: MQTTWrapper.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
	//MQTTWrapper doesn't publish		
}