use of org.eclipse.paho.client.mqttv3.MqttClient 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.MqttClient in project pentaho-kettle by pentaho.
the class MQTTProducerTest method testProcessFirstRow.
@Test
public void testProcessFirstRow() throws Exception {
StepMetaDataCombi combi = trans.getSteps().get(1);
MQTTProducer step = (MQTTProducer) combi.step;
step.first = true;
PowerMockito.mockStatic(MQTTClientBuilder.class);
MQTTClientBuilder clientBuilder = spy(MQTTClientBuilder.class);
MqttClient mqttClient = mock(MqttClient.class);
doReturn(mqttClient).when(clientBuilder).buildAndConnect();
PowerMockito.when(MQTTClientBuilder.builder()).thenReturn(clientBuilder);
trans.startThreads();
trans.waitUntilFinished();
assertFalse(step.first);
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project pentaho-kettle by pentaho.
the class MQTTProducerTest method testErrorOnPublishStopsAll.
@Test
public void testErrorOnPublishStopsAll() throws Exception {
MqttException mqttException = mock(MqttException.class);
when(mqttException.getMessage()).thenReturn("publish failed");
when(mqttClient.isConnected()).thenReturn(true, false);
doThrow(mqttException).when(mqttClient).publish(any(), any());
trans.startThreads();
trans.waitUntilFinished();
verify(mqttClient).disconnect();
verify(logChannel).logError("MQTT Producer - Recieved an exception publishing the message." + " Check that Quality of Service level ${qos} is supported by your MQTT Broker");
verify(logChannel).logError("publish failed", mqttException);
assertEquals(0, trans.getSteps().get(1).step.getLinesOutput());
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project pentaho-kettle by pentaho.
the class MQTTStreamSourceTest method publish.
private void publish(String topic, String... messages) throws MqttException {
MqttClient pub = null;
try {
pub = new MqttClient("tcp://127.0.0.1:" + port, "producer", new MemoryPersistence());
pub.connect();
for (String msg : messages) {
pub.publish(topic, new MqttMessage(msg.getBytes(defaultCharset())));
}
} finally {
assert pub != null;
pub.disconnect();
pub.close();
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project nifi by apache.
the class PublishMQTT method onTrigger.
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile flowfile = session.get();
if (flowfile == null) {
return;
}
if (mqttClient == null || !mqttClient.isConnected()) {
logger.info("Was disconnected from client or was never connected, attempting to connect.");
try {
reconnect();
} catch (MqttException e) {
context.yield();
session.transfer(flowfile, REL_FAILURE);
logger.error("MQTT client is disconnected and re-connecting failed. Transferring FlowFile to fail and yielding", e);
return;
}
}
// get the MQTT topic
String topic = context.getProperty(PROP_TOPIC).evaluateAttributeExpressions(flowfile).getValue();
if (topic == null || topic.isEmpty()) {
logger.warn("Evaluation of the topic property returned null or evaluated to be empty, routing to failure");
session.transfer(flowfile, REL_FAILURE);
return;
}
// do the read
final byte[] messageContent = new byte[(int) flowfile.getSize()];
session.read(flowfile, new InputStreamCallback() {
@Override
public void process(final InputStream in) throws IOException {
StreamUtils.fillBuffer(in, messageContent, true);
}
});
int qos = context.getProperty(PROP_QOS).evaluateAttributeExpressions(flowfile).asInteger();
final MqttMessage mqttMessage = new MqttMessage(messageContent);
mqttMessage.setQos(qos);
mqttMessage.setPayload(messageContent);
mqttMessage.setRetained(context.getProperty(PROP_RETAIN).evaluateAttributeExpressions(flowfile).asBoolean());
try {
mqttClientConnectLock.readLock().lock();
final StopWatch stopWatch = new StopWatch(true);
try {
/*
* Underlying method waits for the message to publish (according to set QoS), so it executes synchronously:
* MqttClient.java:361 aClient.publish(topic, message, null, null).waitForCompletion(getTimeToWait());
*/
mqttClient.publish(topic, mqttMessage);
} finally {
mqttClientConnectLock.readLock().unlock();
}
session.getProvenanceReporter().send(flowfile, broker, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
session.transfer(flowfile, REL_SUCCESS);
} catch (MqttException me) {
logger.error("Failed to publish message.", me);
session.transfer(flowfile, REL_FAILURE);
}
}
Aggregations