Search in sources :

Example 1 with MqttConnectOptions

use of org.eclipse.paho.client.mqttv3.MqttConnectOptions in project openhab1-addons by openhab.

the class MqttBrokerConnection method openConnection.

/**
     * Open an MQTT client connection.
     * 
     * @throws Exception
     */
private void openConnection() throws Exception {
    if (client != null && client.isConnected()) {
        return;
    }
    if (StringUtils.isBlank(url)) {
        throw new Exception("Missing url");
    }
    if (client == null) {
        if (StringUtils.isBlank(clientId) || clientId.length() > 23) {
            clientId = MqttClient.generateClientId();
        }
        String tmpDir = System.getProperty("java.io.tmpdir") + "/" + name;
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        logger.debug("Creating new client for '{}' using id '{}' and file store '{}'", url, clientId, tmpDir);
        client = new MqttClient(url, clientId, dataStore);
        client.setCallback(this);
    }
    MqttConnectOptions options = new MqttConnectOptions();
    if (!StringUtils.isBlank(user)) {
        options.setUserName(user);
    }
    if (!StringUtils.isBlank(password)) {
        options.setPassword(password.toCharArray());
    }
    if (url.toLowerCase().contains("ssl")) {
        if (StringUtils.isNotBlank(System.getProperty("com.ibm.ssl.protocol"))) {
            // get all com.ibm.ssl properties from the system properties
            // and set them as the SSL properties to use.
            Properties sslProps = new Properties();
            addSystemProperty("com.ibm.ssl.protocol", sslProps);
            addSystemProperty("com.ibm.ssl.contextProvider", sslProps);
            addSystemProperty("com.ibm.ssl.keyStore", sslProps);
            addSystemProperty("com.ibm.ssl.keyStorePassword", sslProps);
            addSystemProperty("com.ibm.ssl.keyStoreType", sslProps);
            addSystemProperty("com.ibm.ssl.keyStoreProvider", sslProps);
            addSystemProperty("com.ibm.ssl.trustStore", sslProps);
            addSystemProperty("com.ibm.ssl.trustStorePassword", sslProps);
            addSystemProperty("com.ibm.ssl.trustStoreType", sslProps);
            addSystemProperty("com.ibm.ssl.trustStoreProvider", sslProps);
            addSystemProperty("com.ibm.ssl.enabledCipherSuites", sslProps);
            addSystemProperty("com.ibm.ssl.keyManager", sslProps);
            addSystemProperty("com.ibm.ssl.trustManager", sslProps);
            options.setSSLProperties(sslProps);
        } else {
            // use standard JSSE available in the runtime and
            // use TLSv1.2 which is the default for a secured mosquitto
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, new TrustManager[] { getVeryTrustingTrustManager() }, new java.security.SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            options.setSocketFactory(socketFactory);
        }
    }
    if (lastWill != null) {
        options.setWill(lastWill.getTopic(), lastWill.getPayload(), lastWill.getQos(), lastWill.isRetain());
    }
    options.setKeepAliveInterval(keepAliveInterval);
    client.connect(options);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SSLContext(javax.net.ssl.SSLContext) Properties(java.util.Properties) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttDefaultFilePersistence(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)

Example 2 with MqttConnectOptions

use of org.eclipse.paho.client.mqttv3.MqttConnectOptions in project azure-iot-sdk-java by Azure.

the class MqttTest method connectionLostAttemptsToReconnect.

/*
    **Tests_SRS_Mqtt_25_026: [**The function shall notify all its concrete classes by calling abstract method onReconnect at the entry of the function**]**
     */
/*
    **Tests_SRS_Mqtt_25_029: [**The function shall notify all its concrete classes by calling abstract method onReconnectComplete at the exit of the function**]**
     */
@Test
public void connectionLostAttemptsToReconnect() throws IOException, MqttException {
    //arrange
    Mqtt mockMqtt = null;
    Throwable t = new Throwable();
    try {
        new StrictExpectations() {

            {
                new MemoryPersistence();
                result = mockMemoryPersistence;
                new MqttAsyncClient(serverUri, clientId, mockMemoryPersistence);
                result = mockMqttAsyncClient;
                mockMqttAsyncClient.setCallback((Mqtt) any);
                new MqttConnectOptions();
                result = mockMqttConnectionOptions;
                mockMqttConnectionOptions.setKeepAliveInterval(anyInt);
                mockMqttConnectionOptions.setCleanSession(anyBoolean);
                mockMqttConnectionOptions.setMqttVersion(anyInt);
                mockMqttConnectionOptions.setUserName(anyString);
                mockMqttConnectionOptions.setPassword(password.toCharArray());
                mockMqttConnectionOptions.setSocketFactory(mockIotHubSSLContext.getIotHubSSlContext().getSocketFactory());
                mockMqttAsyncClient.isConnected();
                result = false;
                mockMqttAsyncClient.isConnected();
                result = false;
                mockMqttAsyncClient.connect(mockMqttConnectionOptions);
                result = mockMqttToken;
                mockMqttToken.waitForCompletion();
                mockMqttAsyncClient.isConnected();
                result = true;
            }
        };
        //act
        try {
            mockMqtt = instantiateMqtt(true);
            mockMqtt.connectionLost(t);
        } catch (Exception e) {
            System.out.print("Completed throwing exception - " + e.getCause() + e.getMessage());
        }
    } finally {
        testCleanUp(mockMqtt);
    }
}
Also used : Mqtt(com.microsoft.azure.sdk.iot.device.transport.mqtt.Mqtt) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) IOException(java.io.IOException) InvalidParameterException(java.security.InvalidParameterException) Test(org.junit.Test)

Example 3 with MqttConnectOptions

use of org.eclipse.paho.client.mqttv3.MqttConnectOptions in project azure-iot-sdk-java by Azure.

the class MqttTest method connectionLostAttemptsToReconnectAgainIfConnectFails.

/*
    **Tests_SRS_Mqtt_25_027: [**The function shall attempt to reconnect to the IoTHub in a loop with exponential backoff until it succeeds**]**
     */
@Test
public void connectionLostAttemptsToReconnectAgainIfConnectFails() throws IOException, MqttException {
    //arrange
    Mqtt mockMqtt = null;
    Throwable t = new Throwable();
    try {
        new StrictExpectations() {

            {
                new MemoryPersistence();
                result = mockMemoryPersistence;
                new MqttAsyncClient(serverUri, clientId, mockMemoryPersistence);
                result = mockMqttAsyncClient;
                mockMqttAsyncClient.setCallback((Mqtt) any);
                new MqttConnectOptions();
                result = mockMqttConnectionOptions;
                mockMqttConnectionOptions.setKeepAliveInterval(anyInt);
                mockMqttConnectionOptions.setCleanSession(anyBoolean);
                mockMqttConnectionOptions.setMqttVersion(anyInt);
                mockMqttConnectionOptions.setUserName(anyString);
                mockMqttConnectionOptions.setPassword(password.toCharArray());
                mockMqttConnectionOptions.setSocketFactory(mockIotHubSSLContext.getIotHubSSlContext().getSocketFactory());
                mockMqttAsyncClient.isConnected();
                result = false;
                mockMqttAsyncClient.isConnected();
                result = false;
                mockMqttAsyncClient.connect(mockMqttConnectionOptions);
                result = mockMqttException;
                mockMqttAsyncClient.isConnected();
                result = false;
                mockMqttAsyncClient.isConnected();
                result = false;
                mockMqttAsyncClient.connect(mockMqttConnectionOptions);
                result = mockMqttToken;
                mockMqttToken.waitForCompletion();
                mockMqttAsyncClient.isConnected();
                result = true;
            }
        };
        //act
        try {
            mockMqtt = instantiateMqtt(true);
            mockMqtt.connectionLost(t);
        } catch (Exception e) {
            System.out.print("Completed throwing exception - " + e.getCause() + e.getMessage());
        }
    } finally {
        testCleanUp(mockMqtt);
    }
}
Also used : Mqtt(com.microsoft.azure.sdk.iot.device.transport.mqtt.Mqtt) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) IOException(java.io.IOException) InvalidParameterException(java.security.InvalidParameterException) Test(org.junit.Test)

Example 4 with MqttConnectOptions

use of org.eclipse.paho.client.mqttv3.MqttConnectOptions in project Tusky by Vavassor.

the class PushNotificationClient method connect.

/** Connect to the MQTT broker. */
public void connect(Context context) {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(true);
    options.setCleanSession(false);
    try {
        String password = context.getString(R.string.tusky_api_keystore_password);
        InputStream keystore = context.getResources().openRawResource(R.raw.keystore_tusky_api);
        try {
            options.setSocketFactory(mqttAndroidClient.getSSLSocketFactory(keystore, password));
        } finally {
            IOUtils.closeQuietly(keystore);
        }
        mqttAndroidClient.connect(options).setActionCallback(new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                DisconnectedBufferOptions bufferOptions = new DisconnectedBufferOptions();
                bufferOptions.setBufferEnabled(true);
                bufferOptions.setBufferSize(100);
                bufferOptions.setPersistBuffer(false);
                bufferOptions.setDeleteOldestMessages(false);
                mqttAndroidClient.setBufferOpts(bufferOptions);
                onConnectionSuccess();
                flushQueuedActions();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.e(TAG, "An exception occurred while connecting. " + exception.getMessage() + " " + exception.getCause());
                onConnectionFailure();
            }
        });
    } catch (MqttException e) {
        Log.e(TAG, "An exception occurred while connecpting. " + e.getMessage());
        onConnectionFailure();
    }
}
Also used : IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) InputStream(java.io.InputStream) MqttException(org.eclipse.paho.client.mqttv3.MqttException) DisconnectedBufferOptions(org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken)

Example 5 with MqttConnectOptions

use of org.eclipse.paho.client.mqttv3.MqttConnectOptions in project ignite by apache.

the class IgniteMqttStreamerTest method testSingleTopic_NoQoS_ConnectOptions_Durable.

/**
     * @throws Exception If failed.
     */
public void testSingleTopic_NoQoS_ConnectOptions_Durable() throws Exception {
    // configure streamer
    streamer.setSingleTupleExtractor(singleTupleExtractor());
    streamer.setTopic(SINGLE_TOPIC_NAME);
    MqttConnectOptions connOptions = new MqttConnectOptions();
    connOptions.setCleanSession(false);
    streamer.setConnectOptions(connOptions);
    // subscribe to cache PUT events
    CountDownLatch latch = subscribeToPutEvents(50);
    // action time
    streamer.start();
    // send messages
    sendMessages(Arrays.asList(SINGLE_TOPIC_NAME), 0, 50, false);
    // assertions
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertCacheEntriesLoaded(50);
    // explicitly stop the streamer
    streamer.stop();
    // send messages while stopped
    sendMessages(Arrays.asList(SINGLE_TOPIC_NAME), 50, 50, false);
    latch = subscribeToPutEvents(50);
    // start the streamer again
    streamer.start();
    // assertions - make sure that messages sent during disconnection were also received
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertCacheEntriesLoaded(100);
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)3 Mqtt (com.microsoft.azure.sdk.iot.device.transport.mqtt.Mqtt)2 IOException (java.io.IOException)2 InvalidParameterException (java.security.InvalidParameterException)2 MqttException (org.eclipse.paho.client.mqttv3.MqttException)2 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)2 Test (org.junit.Test)2 InputStream (java.io.InputStream)1 Properties (java.util.Properties)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 SSLContext (javax.net.ssl.SSLContext)1 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)1 DisconnectedBufferOptions (org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions)1 IMqttActionListener (org.eclipse.paho.client.mqttv3.IMqttActionListener)1 IMqttToken (org.eclipse.paho.client.mqttv3.IMqttToken)1 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)1 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)1