Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 43be0ecb3c45548f355a2af683d7315e0fb428a2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package org.eclipse.om2m.binding.mqtt.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;

public final class QueueSender {
	
	private static final Log LOGGER = LogFactory.getLog(QueueSender.class);
	private static ExecutorService threadPool;

	static {
		int queueSize = MqttConstants.MQTT_QUEUE_SENDER_SIZE <= 2 ? 2
				: MqttConstants.MQTT_QUEUE_SENDER_SIZE;
		threadPool = new ThreadPoolExecutor(2, queueSize, 1, TimeUnit.MINUTES,
				new SynchronousQueue<Runnable>());
	}

	public static void queue(MqttClient mqttClient, String topic, byte[] payload){
		LOGGER.debug("Sending MQTT message to " + mqttClient.getServerURI() + " topic: " + topic);
		threadPool.execute(new MqttSender(mqttClient, topic, payload));
	}
	
	private static class MqttSender implements Runnable {

		private MqttClient mqttClient;
		private String topic;
		private byte[] payload;

		public MqttSender(MqttClient mqttClient, String topic, byte[] payload) {
			super();
			this.mqttClient = mqttClient;
			this.topic = topic;
			this.payload = payload;
		}

		@Override
		public void run() {
			try {
				this.mqttClient.publish(topic, payload, 1, false);
			} catch (MqttException e) {
				LOGGER.warn("Error publishing on topic: " + this.topic
						+ " of broker " + this.mqttClient.getServerURI()
						+ ". Error: " + e.getMessage());
			}
		}

	}
	
	private QueueSender(){
		// Empty and private constructor to avoid class creation
	}

}

Back to the top