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());
}
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()));
}
}
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());
}
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();
}
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);
}
Aggregations