use of org.eclipse.paho.client.mqttv3.MqttMessage in project spring-integration by spring-projects.
the class MqttAdapterTests method testInboundOptionsApplied.
@Test
public void testInboundOptionsApplied() 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 IMqttClient client = mock(IMqttClient.class);
willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
final AtomicBoolean connectCalled = new AtomicBoolean();
final AtomicBoolean failConnection = new AtomicBoolean();
final CountDownLatch waitToFail = new CountDownLatch(1);
final CountDownLatch failInProcess = new CountDownLatch(1);
final CountDownLatch goodConnection = new CountDownLatch(2);
final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
willAnswer(invocation -> {
if (failConnection.get()) {
failInProcess.countDown();
waitToFail.await(10, TimeUnit.SECONDS);
throw reconnectException;
}
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);
goodConnection.countDown();
return null;
}).given(client).connect(any(MqttConnectOptions.class));
final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
willAnswer(invocation -> {
callback.set(invocation.getArgument(0));
return null;
}).given(client).setCallback(any(MqttCallback.class));
given(client.isConnected()).willReturn(true);
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
QueueChannel outputChannel = new QueueChannel();
adapter.setOutputChannel(outputChannel);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.setBeanFactory(mock(BeanFactory.class));
ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
willAnswer(invocation -> {
events.add(invocation.getArgument(0));
return null;
}).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
adapter.setApplicationEventPublisher(applicationEventPublisher);
adapter.setRecoveryInterval(500);
adapter.afterPropertiesSet();
adapter.start();
verify(client, times(1)).connect(any(MqttConnectOptions.class));
assertTrue(connectCalled.get());
MqttMessage message = new MqttMessage("qux".getBytes());
callback.get().messageArrived("baz", message);
Message<?> outMessage = outputChannel.receive(0);
assertNotNull(outMessage);
assertEquals("qux", outMessage.getPayload());
MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
assertThat(event, instanceOf(MqttSubscribedEvent.class));
assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
// lose connection and make first reconnect fail
failConnection.set(true);
RuntimeException e = new RuntimeException("foo");
adapter.connectionLost(e);
event = events.poll(10, TimeUnit.SECONDS);
assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
assertSame(event.getCause(), e);
assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
waitToFail.countDown();
failConnection.set(false);
event = events.poll(10, TimeUnit.SECONDS);
assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
assertSame(event.getCause(), reconnectException);
// reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
int n = 0;
while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
event = events.poll(10, TimeUnit.SECONDS);
}
assertThat(event, instanceOf(MqttSubscribedEvent.class));
assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
taskScheduler.destroy();
}
use of org.eclipse.paho.client.mqttv3.MqttMessage in project spring-integration by spring-projects.
the class DefaultPahoMessageConverter method fromMessage.
@Override
public MqttMessage fromMessage(Message<?> message, Class<?> targetClass) {
byte[] payloadBytes = messageToMqttBytes(message);
MqttMessage mqttMessage = new MqttMessage(payloadBytes);
Integer qos = this.qosProcessor.processMessage(message);
mqttMessage.setQos(qos == null ? this.defaultQos : qos);
Boolean retained = this.retainedProcessor.processMessage(message);
mqttMessage.setRetained(retained == null ? this.defaultRetained : retained);
return mqttMessage;
}
use of org.eclipse.paho.client.mqttv3.MqttMessage in project product-iots by wso2.
the class AndroidSenseEnrollment method testEventPublishing.
@Test(description = "Test an Android sense device data publishing.", dependsOnMethods = { "testEnrollment" })
public void testEventPublishing() throws Exception {
String DEVICE_TYPE = "android_sense";
String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + DEVICE_ID + "/data";
int qos = 2;
String broker = "tcp://localhost:1886";
String clientId = DEVICE_ID + ":" + 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");
MqttMessage message = new MqttMessage(PayloadGenerator.getJsonArray(Constants.AndroidSenseEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION).toString().getBytes());
message.setQos(qos);
for (int i = 0; i < 100; i++) {
sampleClient.publish(topic, message);
log.info("Message is published to Mqtt Client");
Thread.sleep(1000);
}
sampleClient.disconnect();
HttpResponse response = analyticsClient.get(Constants.AndroidSenseEnrollment.IS_TABLE_EXIST_CHECK_URL + "?table=" + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME);
Assert.assertEquals("ORG_WSO2_IOT_ANDROID_BATTERY_STATS table does not exist. Problem with the android sense " + "analytics", HttpStatus.SC_OK, response.getResponseCode());
// Allow some time to perform the analytics tasks.
log.info("Mqtt Client is Disconnected");
String url = Constants.AndroidSenseEnrollment.RETRIEVER_ENDPOINT + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME + "/";
Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 3600000);
url += timestamp.getTime() + "/" + new Timestamp(System.currentTimeMillis()).getTime() + "/0/100";
response = analyticsClient.get(url);
JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray();
// TODO: temporarily commenting out untill new changes are merged
// Assert.assertEquals(
// "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
// HttpStatus.SC_OK, response.getResponseCode());
// Assert.assertTrue(
// "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
// jsonArray.size() > 0);
}
use of org.eclipse.paho.client.mqttv3.MqttMessage in project xian by happyyangyuan.
the class IMqttPublisher method p2pPublish.
/*, IMsgPublisher*/
// 点对点发布消息,返回一个callback
default boolean p2pPublish(String xianPid, String payload) {
LOG.debug("MQ发送消息>>> " + xianPid + " >>> " + payload);
final long start = System.nanoTime();
MqttMessage message = new MqttMessage(payload.getBytes());
message.setQos(getQos());
message.setRetained(false);
String wrappedTargetId = wrap(xianPid);
boolean msgPublished = false;
LOG.debug("原来重发次数是5,现改为fast-fail模式,不再重试,直接返回失败给上层应用,优先保证服务器不会过载");
short count = 0, MAX_RETRY = 0;
do {
try {
msgPublished = true;
count++;
getSampleClient().publish(wrappedTargetId, message).setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
if (System.nanoTime() - start > 1000000 * 1000)
LOG.cost("mqttPub", start, System.nanoTime());
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LOG.error(exception);
LOG.cost("mqttPub", start, System.nanoTime());
}
});
} catch (MqttException e) {
LOG.error(e);
if (MqttException.REASON_CODE_CLIENT_NOT_CONNECTED == e.getReasonCode()) {
LOG.debug("注意:这里只针对客户端未连接这一种异常设置消息重发,其他不重发!");
msgPublished = false;
/*reconnect();*/
}
}
} while (!msgPublished && count < MAX_RETRY);
return true;
}
use of org.eclipse.paho.client.mqttv3.MqttMessage in project java-docs-samples by GoogleCloudPlatform.
the class MqttExample method attachCallback.
/**
* Attaches the callback used when configuration changes occur.
*/
public static void attachCallback(MqttClient client, String deviceId) throws MqttException {
mCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
// Do nothing...
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String payload = new String(message.getPayload());
System.out.println("Payload : " + payload);
// TODO: Insert your parsing / handling of the configuration message here.
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Do nothing;
}
};
String configTopic = String.format("/devices/%s/config", deviceId);
client.subscribe(configTopic, 1);
client.setCallback(mCallback);
}
Aggregations