use of org.eclipse.paho.client.mqttv3.MqttClientPersistence in project pentaho-kettle by pentaho.
the class MQTTClientBuilder method buildAndConnect.
public MqttClient buildAndConnect() throws MqttException {
validateArgs();
String broker = getProtocol() + getBroker();
MqttClientPersistence persistence = new MemoryPersistence();
String storageLevelOption = variableSpace.environmentSubstitute(storageLevel);
if (StringUtil.isEmpty(storageLevelOption)) {
logChannel.logDebug("Using Memory Storage Level");
} else {
logChannel.logDebug("Using File Storage Level to " + storageLevelOption);
persistence = new MqttDefaultFilePersistence(storageLevelOption);
}
if (StringUtil.isEmpty(clientId)) {
clientId = MqttAsyncClient.generateClientId();
}
MqttClient client = clientFactory.getClient(broker, clientId, persistence);
client.setCallback(callback);
logChannel.logDebug("Subscribing to topics with a quality of service level of " + variableSpace.environmentSubstitute(qos));
logChannel.logDebug("Server URIs is set to " + variableSpace.environmentSubstitute(serverUris));
logChannel.logDebug("Max Inflight is set to " + variableSpace.environmentSubstitute(maxInflight));
logChannel.logDebug("Automatic Reconnect is set to " + variableSpace.environmentSubstitute(automaticReconnect));
logChannel.logDebug(loggableOptions().toString());
client.connect(getOptions());
if (topics != null && topics.size() > 0) {
client.subscribe(variableSpace.environmentSubstitute(topics.toArray(new String[topics.size()])), initializedIntAray(Integer.parseInt(variableSpace.environmentSubstitute(this.qos))));
}
return client;
}
use of org.eclipse.paho.client.mqttv3.MqttClientPersistence in project smarthome by eclipse.
the class MqttBrokerConnection method start.
/**
* This will establish a connection to the MQTT broker and if successful, notify all
* publishers and subscribers that the connection has become active. This method will
* do nothing if there is already an active connection.
*
* If you want a synchronised way of establishing a broker connection, you can use the
* following pattern:
*
* Object o = new Object();
* conn.addConnectionObserver((isConnected, error) -> o.notify() );
* conn.start();
* o.wait(timeout_in_ms);
* boolean success = conn.connectionState()==MqttConnectionState.CONNECTED;
*
* @throws MqttException If a communication error occurred, this exception is thrown.
* @throws ConfigurationException If no url is given or parameters are invalid, this exception is thrown.
*/
public synchronized void start() throws MqttException, ConfigurationException {
if (connectionState() != MqttConnectionState.DISCONNECTED) {
return;
}
// Ensure the reconnect strategy is started
if (reconnectStrategy != null) {
reconnectStrategy.start();
}
// Storage
String tmpDir = System.getProperty("java.io.tmpdir") + "/" + host;
MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
StringBuilder serverURI = new StringBuilder();
serverURI.append((secure ? "ssl://" : "tcp://"));
serverURI.append(host);
serverURI.append(":");
serverURI.append(port);
// Close client if there is still one existing
if (client != null) {
try {
client.close();
} catch (org.eclipse.paho.client.mqttv3.MqttException ignore) {
}
client = null;
}
// Create new client connection
MqttAsyncClient _client;
try {
_client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore);
client = _client;
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
throw new MqttException(e);
}
_client.setCallback(clientCallbacks);
logger.info("Starting MQTT broker connection to '{}' with clientid {} and file store '{}'", host, getClientId(), tmpDir);
// Perform the connection attempt
isConnecting = true;
try {
_client.connect(createMqttOptions(), null, createConnectionListener());
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
throw new MqttException(e);
}
}
use of org.eclipse.paho.client.mqttv3.MqttClientPersistence in project spring-integration by spring-projects.
the class BackToBackAdapterTests method testAsyncPersisted.
@Test
public void testAsyncPersisted() throws Exception {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
MqttClientPersistence persistence = new MqttDefaultFilePersistence(folder.getRoot().getAbsolutePath());
factory.setPersistence(persistence);
MqttPahoMessageHandler adapter = new MqttPahoMessageHandler("tcp://localhost:1883", "si-test-out", factory);
adapter.setDefaultTopic("mqtt-foo");
adapter.setBeanFactory(mock(BeanFactory.class));
adapter.setAsync(true);
adapter.setAsyncEvents(true);
adapter.setDefaultQos(1);
EventPublisher publisher1 = new EventPublisher();
adapter.setApplicationEventPublisher(publisher1);
adapter.afterPropertiesSet();
adapter.start();
MqttPahoMessageDrivenChannelAdapter inbound = new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "si-test-in", "mqtt-foo", "mqtt-bar");
QueueChannel outputChannel = new QueueChannel();
inbound.setOutputChannel(outputChannel);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
inbound.setTaskScheduler(taskScheduler);
inbound.setBeanFactory(mock(BeanFactory.class));
inbound.afterPropertiesSet();
inbound.start();
Message<String> message1 = new GenericMessage<String>("foo");
adapter.handleMessage(message1);
verifyEvents(adapter, publisher1, message1);
Message<String> message2 = MessageBuilder.withPayload("bar").setHeader(MqttHeaders.TOPIC, "mqtt-bar").build();
EventPublisher publisher2 = new EventPublisher();
adapter.setApplicationEventPublisher(publisher2);
adapter.handleMessage(message2);
verifyEvents(adapter, publisher2, message2);
verifyMessageIds(publisher1, publisher2);
int clientInstance = publisher1.delivered.getClientInstance();
adapter.stop();
// new client instance
adapter.start();
publisher1 = new EventPublisher();
adapter.setApplicationEventPublisher(publisher1);
adapter.handleMessage(message1);
verifyEvents(adapter, publisher1, message1);
publisher2 = new EventPublisher();
adapter.setApplicationEventPublisher(publisher2);
adapter.handleMessage(message2);
verifyEvents(adapter, publisher2, message2);
verifyMessageIds(publisher1, publisher2);
assertNotEquals(clientInstance, publisher1.delivered.getClientInstance());
Message<?> out = null;
for (int i = 0; i < 4; i++) {
out = outputChannel.receive(20000);
assertNotNull(out);
if ("foo".equals(out.getPayload())) {
assertEquals("mqtt-foo", out.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
} else if ("bar".equals(out.getPayload())) {
assertEquals("mqtt-bar", out.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
} else {
fail("unexpected payload " + out.getPayload());
}
}
adapter.stop();
inbound.stop();
}
Aggregations