use of org.eclipse.paho.client.mqttv3.MqttClient in project spring-integration by spring-projects.
the class MqttAdapterTests method testSubscribeFailure.
@Test
public void testSubscribeFailure() 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);
MqttAsyncClient aClient = mock(MqttAsyncClient.class);
final MqttClient client = mock(MqttClient.class);
willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
given(client.isConnected()).willReturn(true);
new DirectFieldAccessor(client).setPropertyValue("aClient", aClient);
willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class));
willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class));
willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any());
IMqttToken token = mock(IMqttToken.class);
given(token.getGrantedQos()).willReturn(new int[] { 0x80 });
willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), any(), any());
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
AtomicReference<Method> method = new AtomicReference<>();
ReflectionUtils.doWithMethods(MqttPahoMessageDrivenChannelAdapter.class, m -> {
m.setAccessible(true);
method.set(m);
}, m -> m.getName().equals("connectAndSubscribe"));
assertNotNull(method.get());
try {
method.get().invoke(adapter);
fail("Expected InvocationTargetException");
} catch (InvocationTargetException e) {
assertThat(e.getCause(), instanceOf(MqttException.class));
assertThat(((MqttException) e.getCause()).getReasonCode(), equalTo((int) MqttException.REASON_CODE_SUBSCRIBE_FAILED));
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient 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.MqttClient in project syndesis by syndesisio.
the class MqttVerifierExtension method verifyCredentials.
private void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) {
String brokerUrl = (String) parameters.get("brokerUrl");
if (ObjectHelper.isNotEmpty(brokerUrl)) {
try {
// Create MQTT client
MqttClient client = new MqttClient(brokerUrl, MqttClient.generateClientId());
client.connect();
client.disconnect();
} catch (MqttException e) {
builder.error(ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE, "Unable to connect to MQTT broker").parameterKey("brokerUrl").build());
}
} else {
builder.error(ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE, "Invalid blank MQTT brokerUrl ").parameterKey("brokerUrl").build());
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient 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);
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project activemq-artemis by apache.
the class MqttAcknowledgementTest method createMqttClient.
private MqttClient createMqttClient(String clientId) throws MqttException {
MqttClient client = new MqttClient("tcp://localhost:" + getPort(), clientId, new MemoryPersistence());
client.setCallback(createCallback());
client.setManualAcks(true);
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
client.connect(options);
return client;
}
Aggregations