Search in sources :

Example 51 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project spring-integration by spring-projects.

the class MqttAdapterTests method testOutboundOptionsApplied.

@Test
public void testOutboundOptionsApplied() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);
    factory = spy(factory);
    final MqttAsyncClient client = mock(MqttAsyncClient.class);
    willAnswer(invocation -> client).given(factory).getAsyncClientInstance(anyString(), anyString());
    MqttPahoMessageHandler handler = new MqttPahoMessageHandler("foo", "bar", factory);
    handler.setDefaultTopic("mqtt-foo");
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    final MqttToken token = mock(MqttToken.class);
    final AtomicBoolean connectCalled = new AtomicBoolean();
    willAnswer(invocation -> {
        MqttConnectOptions options = invocation.getArgument(0);
        assertEquals(23, options.getConnectionTimeout());
        assertEquals(45, options.getKeepAliveInterval());
        assertEquals("pass", new String(options.getPassword()));
        assertSame(socketFactory, options.getSocketFactory());
        assertSame(props, options.getSSLProperties());
        assertEquals("user", options.getUserName());
        assertEquals("foo", options.getWillDestination());
        assertEquals("bar", new String(options.getWillMessage().getPayload()));
        assertEquals(2, options.getWillMessage().getQos());
        connectCalled.set(true);
        return token;
    }).given(client).connect(any(MqttConnectOptions.class));
    willReturn(token).given(client).subscribe(any(String[].class), any(int[].class));
    final MqttDeliveryToken deliveryToken = mock(MqttDeliveryToken.class);
    final AtomicBoolean publishCalled = new AtomicBoolean();
    willAnswer(invocation -> {
        assertEquals("mqtt-foo", invocation.getArguments()[0]);
        MqttMessage message = invocation.getArgument(1);
        assertEquals("Hello, world!", new String(message.getPayload()));
        publishCalled.set(true);
        return deliveryToken;
    }).given(client).publish(anyString(), any(MqttMessage.class));
    handler.handleMessage(new GenericMessage<String>("Hello, world!"));
    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) SocketFactory(javax.net.SocketFactory) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) MqttToken(org.eclipse.paho.client.mqttv3.MqttToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttPahoMessageHandler(org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) MqttDeliveryToken(org.eclipse.paho.client.mqttv3.MqttDeliveryToken) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 52 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project spring-integration by spring-projects.

the class MqttPahoMessageHandler method publish.

@Override
protected void publish(String topic, Object mqttMessage, Message<?> message) throws Exception {
    Assert.isInstanceOf(MqttMessage.class, mqttMessage);
    IMqttAsyncClient client = checkConnection();
    IMqttDeliveryToken token = client.publish(topic, (MqttMessage) mqttMessage);
    if (!this.async) {
        token.waitForCompletion(this.completionTimeout);
    } else if (this.asyncEvents && this.applicationEventPublisher != null) {
        this.applicationEventPublisher.publishEvent(new MqttMessageSentEvent(this, message, topic, token.getMessageId(), getClientId(), getClientInstance()));
    }
}
Also used : MqttMessageSentEvent(org.springframework.integration.mqtt.event.MqttMessageSentEvent) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) IMqttAsyncClient(org.eclipse.paho.client.mqttv3.IMqttAsyncClient)

Example 53 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project product-iots by wso2.

the class VirtualFireAlarmTestCase method testPolicyPublishing.

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = { "testEventPublishing" })
public void testPolicyPublishing() throws Exception {
    String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2;
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + "/operation/#";
    String clientId = deviceId2 + ":" + DEVICE_TYPE;
    HttpResponse response = restClient.post("/api/device-mgt/v1.0/policies", PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.VirtualFireAlarmConstants.POLICY_DATA).toString());
    Assert.assertEquals("Policy creation for virtual fire alarm failed", HttpStatus.SC_CREATED, response.getResponseCode());
    JsonObject jsonObject = new JsonParser().parse(response.getData()).getAsJsonObject();
    String policyId = jsonObject.getAsJsonPrimitive("id").getAsString();
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(new JsonPrimitive(policyId));
    response = restClient.post(Constants.VirtualFireAlarmConstants.ACTIVATE_POLICY_ENDPOINT, jsonArray.toString());
    Assert.assertEquals("Policy activation for virtual fire alarm failed", HttpStatus.SC_OK, response.getResponseCode());
    MqttSubscriberClient mqttSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    response = restClient.put(Constants.VirtualFireAlarmConstants.APPLY_CHANGES_ENDPOINT, "");
    Assert.assertEquals("Applying changes to policy for virtual fire alarm failed", HttpStatus.SC_OK, response.getResponseCode());
    // Allow some time for message delivery
    Thread.sleep(20000);
    ArrayList<MqttMessage> mqttMessages = mqttSubscriberClient.getMqttMessages();
    Assert.assertEquals("Policy published message is not received by the mqtt listener. ", 2, mqttMessages.size());
}
Also used : JsonArray(com.google.gson.JsonArray) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) JsonPrimitive(com.google.gson.JsonPrimitive) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) JsonObject(com.google.gson.JsonObject) MqttSubscriberClient(org.wso2.iot.integration.common.MqttSubscriberClient) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Example 54 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project product-iots by wso2.

the class VirtualFireAlarmTestCase method testEventPublishing.

@Test(description = "Test whether the publishing to a mqtt broker works fine without exceptions", dependsOnMethods = { "testEnrollment" })
public void testEventPublishing() throws Exception {
    String deviceId1 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId1 : VirtualFireAlarmTestCase.deviceId1;
    String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2;
    // Publishing message as a device with simple agent (device 1)
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId1 + "/temperature";
    int qos = 2;
    String clientId = deviceId1 + ":" + DEVICE_TYPE;
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(true);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    JsonObject fireAlarmPayload = PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION);
    JsonObject eventPayload = fireAlarmPayload.getAsJsonObject("event");
    JsonObject metaDataPayload = eventPayload.getAsJsonObject("metaData");
    metaDataPayload.addProperty("deviceId", deviceId1);
    eventPayload.add("metaData", metaDataPayload);
    fireAlarmPayload.add("event", eventPayload);
    MqttMessage message;
    for (int i = 0; i < 100; i++) {
        message = new MqttMessage(fireAlarmPayload.toString().getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        Thread.sleep(1000);
    }
    log.info("Message is published to Mqtt Client");
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Publishing message as a device with simple agent (device 2)
    topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + "/temperature";
    clientId = deviceId2 + ":" + DEVICE_TYPE;
    persistence = new MemoryPersistence();
    sampleClient = new MqttClient(broker, clientId, persistence);
    connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(true);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    fireAlarmPayload = PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION);
    eventPayload = fireAlarmPayload.getAsJsonObject("event");
    metaDataPayload = eventPayload.getAsJsonObject("metaData");
    metaDataPayload.addProperty("deviceId", deviceId2);
    eventPayload.add("metaData", metaDataPayload);
    fireAlarmPayload.add("event", eventPayload);
    for (int i = 0; i < 100; i++) {
        message = new MqttMessage(fireAlarmPayload.toString().getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        Thread.sleep(1000);
    }
    log.info("Message is published to Mqtt Client");
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    currentTime = System.currentTimeMillis();
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) JsonObject(com.google.gson.JsonObject) Test(org.testng.annotations.Test)

Example 55 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project product-iots by wso2.

the class DeviceTypeManagementJMeterTestCase method testMqttFlow.

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = { "DeviceTypeManagementTest" })
public void testMqttFlow() throws Exception {
    String deviceId = "123422578912";
    String deviceType = "firealarmmqtt";
    String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\"," + "\"payLoad\":\"volume:30%\"}}";
    String topic = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId + "/operation/#";
    String clientId = deviceId + ":firealarmmqtt";
    MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload);
    // Allow some time for message delivery
    Thread.sleep(10000);
    ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages();
    Assert.assertEquals("listener did not recieve mqtt messages ", 1, mqttMessages.size());
    String topicPub = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId + "/events";
    int qos = 2;
    String clientIdPub = deviceId + ":firealarmmqttpub";
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(false);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    for (int i = 0; i < 100; i++) {
        payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}";
        MqttMessage message = new MqttMessage(String.format(payload, i).getBytes());
        message.setQos(qos);
        sampleClient.publish(topicPub, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Allow some time for message delivery
    HttpResponse response = restClient.get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId);
    Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK, response.getResponseCode());
    log.error(response.getData());
    JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count");
    int count = jsonElement.getAsInt();
    Assert.assertTrue("Event count does not match published event count, " + response.getData(), count > 0);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) JsonElement(com.google.gson.JsonElement) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) MqttSubscriberClient(org.wso2.iot.integration.common.MqttSubscriberClient) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test) JMeterTest(org.wso2.carbon.automation.extensions.jmeter.JMeterTest)

Aggregations

MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)64 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