Search in sources :

Example 26 with MqttClient

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));
    }
}
Also used : 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) Properties(java.util.Properties) InvocationTargetException(java.lang.reflect.InvocationTargetException) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) CallsRealMethods(org.mockito.internal.stubbing.answers.CallsRealMethods) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 27 with MqttClient

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);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) JsonArray(com.google.gson.JsonArray) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) Timestamp(java.sql.Timestamp) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Example 28 with MqttClient

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());
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 29 with MqttClient

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);
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 30 with MqttClient

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;
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions)

Aggregations

MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)46 MqttException (org.eclipse.paho.client.mqttv3.MqttException)37 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)23 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)23 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)18 Test (org.junit.Test)12 Properties (java.util.Properties)6 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)6 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)5 IOException (java.io.IOException)4 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)4 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 JsonArray (com.google.gson.JsonArray)3 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 SSLSecurityManager (it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3