Search in sources :

Example 6 with MqttClient

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;
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttClientPersistence(org.eclipse.paho.client.mqttv3.MqttClientPersistence) BaseMessages.getString(org.pentaho.di.i18n.BaseMessages.getString) MqttDefaultFilePersistence(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)

Example 7 with MqttClient

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);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) StepMetaDataCombi(org.pentaho.di.trans.step.StepMetaDataCombi) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 8 with MqttClient

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());
}
Also used : MqttException(org.eclipse.paho.client.mqttv3.MqttException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 9 with MqttClient

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();
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Matchers.anyString(org.mockito.Matchers.anyString)

Example 10 with MqttClient

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);
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttException(org.eclipse.paho.client.mqttv3.MqttException) InputStream(java.io.InputStream) InputStreamCallback(org.apache.nifi.processor.io.InputStreamCallback) IOException(java.io.IOException) StopWatch(org.apache.nifi.util.StopWatch)

Aggregations

MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)46 MqttException (org.eclipse.paho.client.mqttv3.MqttException)37 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)23 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)23 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)18 Test (org.junit.Test)12 Properties (java.util.Properties)6 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)6 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)5 IOException (java.io.IOException)4 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)4 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 JsonArray (com.google.gson.JsonArray)3 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 SSLSecurityManager (it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3