Search in sources :

Example 21 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project kafka-connect-mqtt by jcustenborder.

the class MqttSinkTask method put.

@Override
public void put(Collection<SinkRecord> records) {
    try {
        for (SinkRecord record : records) {
            MqttMessage message = this.converter.convert(record.valueSchema(), record.value());
            this.client.publish(record.topic(), message);
        }
    } catch (MqttException e) {
        throw new RetriableException(e);
    }
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttException(org.eclipse.paho.client.mqttv3.MqttException) SinkRecord(org.apache.kafka.connect.sink.SinkRecord) RetriableException(org.apache.kafka.connect.errors.RetriableException)

Example 22 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project kafka-connect-mqtt by jcustenborder.

the class SinkConverter method convert.

public MqttMessage convert(Schema schema, Object value) {
    final byte[] payload;
    if (null != schema) {
        if (Schema.Type.BYTES == schema.type()) {
            payload = (byte[]) value;
        } else if (Schema.Type.STRING == schema.type()) {
            payload = ((String) value).getBytes(Charsets.UTF_8);
        } else {
            throw new UnsupportedOperationException(String.format("%s is not a supported type.", schema.type()));
        }
    } else {
        if (value instanceof byte[]) {
            payload = (byte[]) value;
        } else if (value instanceof String) {
            payload = ((String) value).getBytes(Charsets.UTF_8);
        } else {
            throw new UnsupportedOperationException(String.format("%s is not a supported type.", value.getClass().getName()));
        }
    }
    MqttMessage message = new MqttMessage();
    message.setPayload(payload);
    message.setQos(this.config.qos);
    message.setRetained(this.config.retained);
    return message;
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage)

Example 23 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project wildfly-camel by wildfly-extras.

the class PahoIntegrationTest method testPahoConsumer.

@Test
public void testPahoConsumer() throws Exception {
    String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("paho:" + BrokerSetup.TEST_TOPIC + "?brokerUrl=" + conUrl).transform(body().prepend("Hello ")).to("seda:end");
        }
    });
    camelctx.start();
    try {
        PollingConsumer consumer = camelctx.getEndpoint("seda:end").createPollingConsumer();
        consumer.start();
        MqttClient client = null;
        try {
            client = new MqttClient(conUrl, "MqttClient", new MemoryPersistence());
            MqttConnectOptions opts = new MqttConnectOptions();
            opts.setCleanSession(true);
            client.connect(opts);
            MqttMessage message = new MqttMessage("Kermit".getBytes());
            message.setQos(2);
            client.publish(BrokerSetup.TEST_TOPIC, message);
        } finally {
            client.disconnect();
        }
        String result = consumer.receive(3000).getIn().getBody(String.class);
        Assert.assertEquals("Hello Kermit", result);
    } finally {
        camelctx.stop();
    }
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) PollingConsumer(org.apache.camel.PollingConsumer) RouteBuilder(org.apache.camel.builder.RouteBuilder) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Test(org.junit.Test)

Example 24 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project wildfly-camel by wildfly-extras.

the class PahoIntegrationTest method testMQTTProducer.

@Test
public void testMQTTProducer() throws Exception {
    String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").transform(body().prepend("Hello ")).to("paho:" + BrokerSetup.TEST_TOPIC + "?brokerUrl=" + conUrl);
        }
    });
    camelctx.start();
    try {
        MqttClient client = new MqttClient(conUrl, "MqttClient", new MemoryPersistence());
        MqttConnectOptions opts = new MqttConnectOptions();
        opts.setCleanSession(true);
        client.connect(opts);
        client.subscribe(BrokerSetup.TEST_TOPIC, 2);
        final List<String> result = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(1);
        client.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable cause) {
            }

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

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });
        ProducerTemplate producer = camelctx.createProducerTemplate();
        producer.asyncSendBody("direct:start", "Kermit");
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertEquals("One message", 1, result.size());
        Assert.assertEquals("Hello Kermit", result.get(0));
    } finally {
        camelctx.stop();
    }
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) ProducerTemplate(org.apache.camel.ProducerTemplate) RouteBuilder(org.apache.camel.builder.RouteBuilder) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) ArrayList(java.util.ArrayList) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) CountDownLatch(java.util.concurrent.CountDownLatch) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) Test(org.junit.Test)

Example 25 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project joynr by bmwcarit.

the class MqttPahoClient method publishMessage.

@Override
public void publishMessage(String topic, byte[] serializedMessage, int qosLevel) {
    if (messagingSkeleton == null) {
        throw new JoynrDelayMessageException("MQTT Publish failed: messagingSkeleton has not been set yet");
    }
    if (maxMsgSizeBytes != 0 && serializedMessage.length > maxMsgSizeBytes) {
        throw new JoynrMessageNotSentException("MQTT Publish failed: maximum allowed message size of " + maxMsgSizeBytes + " bytes exceeded, actual size is " + serializedMessage.length + " bytes");
    }
    try {
        MqttMessage message = new MqttMessage();
        message.setPayload(serializedMessage);
        message.setQos(qosLevel);
        message.setRetained(false);
        logger.debug("MQTT Publish to: {}", topic);
        mqttClient.publish(topic, message);
    } catch (MqttException e) {
        logger.debug("MQTT Publish failed: {}. Error code {}", e.getMessage(), e.getReasonCode(), e);
        switch(e.getReasonCode()) {
            case MqttException.REASON_CODE_CLIENT_EXCEPTION:
                Throwable cause = e.getCause();
                if (cause != null) {
                    throw new JoynrDelayMessageException("MqttException: " + cause.getMessage());
                } else {
                    throw new JoynrDelayMessageException("MqttException: " + e.getMessage());
                }
            case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
            case MqttException.REASON_CODE_CLIENT_DISCONNECTING:
            case MqttException.REASON_CODE_CLIENT_NOT_CONNECTED:
            case MqttException.REASON_CODE_CLIENT_TIMEOUT:
            case MqttException.REASON_CODE_CONNECTION_LOST:
            case MqttException.REASON_CODE_MAX_INFLIGHT:
            case MqttException.REASON_CODE_NO_MESSAGE_IDS_AVAILABLE:
            case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
            case MqttException.REASON_CODE_UNEXPECTED_ERROR:
            case MqttException.REASON_CODE_WRITE_TIMEOUT:
            case MqttException.REASON_CODE_CONNECT_IN_PROGRESS:
                throw new JoynrDelayMessageException("MqttException: " + e.getMessage());
            default:
                throw new JoynrMessageNotSentException(e.getMessage());
        }
    } catch (Exception e) {
        throw new JoynrMessageNotSentException(e.getMessage(), e);
    }
    logger.debug("Published message: " + new String(serializedMessage, Charsets.UTF_8));
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) JoynrDelayMessageException(io.joynr.exceptions.JoynrDelayMessageException) MqttException(org.eclipse.paho.client.mqttv3.MqttException) JoynrMessageNotSentException(io.joynr.exceptions.JoynrMessageNotSentException) URISyntaxException(java.net.URISyntaxException) JoynrMessageNotSentException(io.joynr.exceptions.JoynrMessageNotSentException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) MqttException(org.eclipse.paho.client.mqttv3.MqttException) JoynrRuntimeException(io.joynr.exceptions.JoynrRuntimeException) JoynrDelayMessageException(io.joynr.exceptions.JoynrDelayMessageException) JoynrIllegalStateException(io.joynr.exceptions.JoynrIllegalStateException) MqttSecurityException(org.eclipse.paho.client.mqttv3.MqttSecurityException)

Aggregations

MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)65 MqttException (org.eclipse.paho.client.mqttv3.MqttException)28 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)19 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)16 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)16 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)15 Test (org.junit.Test)14 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)8 CountDownLatch (java.util.concurrent.CountDownLatch)4 JsonParser (com.google.gson.JsonParser)3 IOException (java.io.IOException)3 MqttAsyncClient (org.eclipse.paho.client.mqttv3.MqttAsyncClient)3 JSONObject (org.json.JSONObject)3 Test (org.testng.annotations.Test)3 JsonArray (com.google.gson.JsonArray)2 JsonObject (com.google.gson.JsonObject)2 MISTEdge (edu.snu.mist.common.graph.MISTEdge)2 ArrayList (java.util.ArrayList)2 Properties (java.util.Properties)2 CamelContext (org.apache.camel.CamelContext)2