Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setSSLProperties()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions#setSSLProperties() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ManagerMQTT.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void connect() {

    String[] listtopics = worktopics.toArray(new String[worktopics.size()]);
    int[] listqos = new int[workqos.size()];
    for (int i = 0; i < workqos.size(); i++) {
        listqos[i] = workqos.get(i);
    }

    try {
        mqttClient = new MqttClient(url, clientid, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        if (!Strings.isNullOrEmpty(username)) {
            options.setUserName(username);
            options.setPassword(password.toCharArray());
        }
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepalive);
        options.setMqttVersion(version);
        options.setCleanSession(true);
        options.setAutomaticReconnect(false);
        options.setMaxInflight(maxinflight);
        options.setSSLProperties(sslproperties);
        options.setWill(topicsys + "app/" + clientid, new StringFormatSwitch().devalue(MiniVarBoolean.FALSE), 0, true);
        mqttClient.connect(options);
        mqttClient.setCallback(this);
        if (listtopics.length > 0) {
            mqttClient.subscribe(listtopics, listqos);
        }
        statusPublish(MiniVarBoolean.TRUE);
    } catch (MqttException ex) {
        logger.log(Level.WARNING, null, ex);
        throw new RuntimeException(String.format(resources.getString("exception.mqtt"), url), ex);
    }
}
 
Example 2
Source File: AbstractMQTTProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void onScheduled(final ProcessContext context){
    broker = context.getProperty(PROP_BROKER_URI).getValue();
    clientID = context.getProperty(PROP_CLIENTID).evaluateAttributeExpressions().getValue();

    if (clientID == null) {
        clientID = UUID.randomUUID().toString();
    }

    connOpts = new MqttConnectOptions();
    connOpts.setCleanSession(context.getProperty(PROP_CLEAN_SESSION).asBoolean());
    connOpts.setKeepAliveInterval(context.getProperty(PROP_KEEP_ALIVE_INTERVAL).asInteger());
    connOpts.setMqttVersion(context.getProperty(PROP_MQTT_VERSION).asInteger());
    connOpts.setConnectionTimeout(context.getProperty(PROP_CONN_TIMEOUT).asInteger());

    PropertyValue sslProp = context.getProperty(PROP_SSL_CONTEXT_SERVICE);
    if (sslProp.isSet()) {
        Properties sslProps = transformSSLContextService((SSLContextService) sslProp.asControllerService());
        connOpts.setSSLProperties(sslProps);
    }

    PropertyValue lastWillTopicProp = context.getProperty(PROP_LAST_WILL_TOPIC);
    if (lastWillTopicProp.isSet()){
        String lastWillMessage = context.getProperty(PROP_LAST_WILL_MESSAGE).getValue();
        PropertyValue lastWillRetain = context.getProperty(PROP_LAST_WILL_RETAIN);
        Integer lastWillQOS = context.getProperty(PROP_LAST_WILL_QOS).asInteger();
        connOpts.setWill(lastWillTopicProp.getValue(), lastWillMessage.getBytes(), lastWillQOS, lastWillRetain.isSet() ? lastWillRetain.asBoolean() : false);
    }


    PropertyValue usernameProp = context.getProperty(PROP_USERNAME);
    if(usernameProp.isSet()) {
        connOpts.setUserName(usernameProp.getValue());
        connOpts.setPassword(context.getProperty(PROP_PASSWORD).getValue().toCharArray());
    }
}
 
Example 3
Source File: MqttPahoClient.java    From joynr with Apache License 2.0 5 votes vote down vote up
private MqttConnectOptions getConnectOptions() {
    MqttConnectOptions options = new MqttConnectOptions();
    if (username != null && !username.isEmpty()) {
        if (password == null || password.isEmpty()) {
            throw new JoynrIllegalStateException("MQTT password not configured or empty");
        }
        options.setUserName(username);
        options.setPassword(password.toCharArray());
    }
    options.setAutomaticReconnect(false);
    options.setConnectionTimeout(connectionTimeoutSec);
    options.setKeepAliveInterval(keepAliveTimerSec);
    options.setMaxInflight(maxMsgsInflight);
    options.setCleanSession(cleanSession);

    if (isSecureConnection) {
        // Set global SSL properties for all Joynr SSL clients
        Properties sslClientProperties = new Properties();
        sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTORETYPE, keyStoreType);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTORE, keyStorePath);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTOREPWD, keyStorePWD);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTORETYPE, trustStoreType);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTORE, trustStorePath);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTOREPWD, trustStorePWD);
        options.setSSLProperties(sslClientProperties);
    }

    return options;
}
 
Example 4
Source File: MQTTClientBuilder.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void setSSLProps( MqttConnectOptions options ) {
  Properties props = new Properties();
  props.putAll(
    sslConfig.entrySet().stream()
      .filter( entry -> !isNullOrEmpty( entry.getValue() ) )
      .collect( Collectors.toMap( e -> SSL_PROP_PREFIX + e.getKey(),
        Map.Entry::getValue ) ) );
  options.setSSLProperties( props );
}
 
Example 5
Source File: AbstractMQTTProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected void buildClient(ProcessContext context){
    try {
        broker = context.getProperty(PROP_BROKER_URI).getValue();
        clientID = context.getProperty(PROP_CLIENTID).getValue();

        connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(context.getProperty(PROP_CLEAN_SESSION).asBoolean());
        connOpts.setKeepAliveInterval(context.getProperty(PROP_KEEP_ALIVE_INTERVAL).asInteger());
        connOpts.setMqttVersion(context.getProperty(PROP_MQTT_VERSION).asInteger());
        connOpts.setConnectionTimeout(context.getProperty(PROP_CONN_TIMEOUT).asInteger());

        PropertyValue sslProp = context.getProperty(PROP_SSL_CONTEXT_SERVICE);
        if (sslProp.isSet()) {
            Properties sslProps = transformSSLContextService((SSLContextService) sslProp.asControllerService());
            connOpts.setSSLProperties(sslProps);
        }

        PropertyValue lastWillTopicProp = context.getProperty(PROP_LAST_WILL_TOPIC);
        if (lastWillTopicProp.isSet()){
            String lastWillMessage = context.getProperty(PROP_LAST_WILL_MESSAGE).getValue();
            PropertyValue lastWillRetain = context.getProperty(PROP_LAST_WILL_RETAIN);
            Integer lastWillQOS = context.getProperty(PROP_LAST_WILL_QOS).asInteger();
            connOpts.setWill(lastWillTopicProp.getValue(), lastWillMessage.getBytes(), lastWillQOS, lastWillRetain.isSet() ? lastWillRetain.asBoolean() : false);
        }


        PropertyValue usernameProp = context.getProperty(PROP_USERNAME);
        if(usernameProp.isSet()) {
            connOpts.setUserName(usernameProp.getValue());
            connOpts.setPassword(context.getProperty(PROP_PASSWORD).getValue().toCharArray());
        }

        mqttClientConnectLock.writeLock().lock();
        try{
            mqttClient = getMqttClient(broker, clientID, persistence);

        } finally {
            mqttClientConnectLock.writeLock().unlock();
        }
    } catch(MqttException me) {
        logger.error("Failed to initialize the connection to the  " + me.getMessage());
    }
}
 
Example 6
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Connects the gateway to the MQTT bridge. */
protected static MqttClient startMqtt(
    String mqttBridgeHostname,
    int mqttBridgePort,
    String projectId,
    String cloudRegion,
    String registryId,
    String gatewayId,
    String privateKeyFile,
    String algorithm)
    throws NoSuchAlgorithmException, IOException, MqttException, InterruptedException,
        InvalidKeySpecException {
  // [START iot_gateway_start_mqtt]

  // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
  // connections are accepted. For server authentication, the JVM's root certificates
  // are used.
  final String mqttServerAddress =
      String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);

  // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
  // Google Cloud IoT Core, it must be in the format below.
  final String mqttClientId =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, gatewayId);

  MqttConnectOptions connectOptions = new MqttConnectOptions();
  // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
  // explictly set this. If you don't set MQTT version, the server will immediately close its
  // connection to your device.
  connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

  Properties sslProps = new Properties();
  sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
  connectOptions.setSSLProperties(sslProps);

  // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
  // Paho client library to send the password field. The password field is used to transmit a JWT
  // to authorize the device.
  connectOptions.setUserName("unused");

  if ("RS256".equals(algorithm)) {
    connectOptions.setPassword(createJwtRsa(projectId, privateKeyFile).toCharArray());
  } else if ("ES256".equals(algorithm)) {
    connectOptions.setPassword(createJwtEs(projectId, privateKeyFile).toCharArray());
  } else {
    throw new IllegalArgumentException(
        "Invalid algorithm " + algorithm + ". Should be one of 'RS256' or 'ES256'.");
  }

  System.out.println(String.format("%s", mqttClientId));

  // Create a client, and connect to the Google MQTT bridge.
  MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());

  // Both connect and publish operations may fail. If they do, allow retries but with an
  // exponential backoff time period.
  long initialConnectIntervalMillis = 500L;
  long maxConnectIntervalMillis = 6000L;
  long maxConnectRetryTimeElapsedMillis = 900000L;
  float intervalMultiplier = 1.5f;

  long retryIntervalMs = initialConnectIntervalMillis;
  long totalRetryTimeMs = 0;

  while ((totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) && !client.isConnected()) {
    try {
      client.connect(connectOptions);
    } catch (MqttException e) {
      int reason = e.getReasonCode();

      // If the connection is lost or if the server cannot be connected, allow retries, but with
      // exponential backoff.
      System.out.println("An error occurred: " + e.getMessage());
      if (reason == MqttException.REASON_CODE_CONNECTION_LOST
          || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
        System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
        Thread.sleep(retryIntervalMs);
        totalRetryTimeMs += retryIntervalMs;
        retryIntervalMs *= intervalMultiplier;
        if (retryIntervalMs > maxConnectIntervalMillis) {
          retryIntervalMs = maxConnectIntervalMillis;
        }
      } else {
        throw e;
      }
    }
  }

  attachCallback(client, gatewayId);

  // The topic gateways receive error updates on. QoS must be 0.
  String errorTopic = String.format("/devices/%s/errors", gatewayId);
  System.out.println(String.format("Listening on %s", errorTopic));

  client.subscribe(errorTopic, 0);

  return client;
  // [END iot_gateway_start_mqtt]
}
 
Example 7
Source File: CloudiotPubsubExampleMqttDevice.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Entry point for CLI. */
public static void main(String[] args) throws Exception {
  CloudiotPubsubExampleMqttDeviceOptions options =
      CloudiotPubsubExampleMqttDeviceOptions.fromFlags(args);
  if (options == null) {
    System.exit(1);
  }
  final Device device = new Device(options);
  final String mqttTelemetryTopic = String.format("/devices/%s/events", options.deviceId);
  // This is the topic that the device will receive configuration updates on.
  final String mqttConfigTopic = String.format("/devices/%s/config", options.deviceId);

  final String mqttServerAddress =
      String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);
  final String mqttClientId =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          options.projectId, options.cloudRegion, options.registryId, options.deviceId);
  MqttConnectOptions connectOptions = new MqttConnectOptions();
  connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

  Properties sslProps = new Properties();
  sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
  connectOptions.setSSLProperties(sslProps);

  connectOptions.setUserName("unused");
  if (options.algorithm.equals("RS256")) {
    System.out.println(options.privateKeyFile);

    connectOptions.setPassword(
        createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
    System.out.println(
        String.format(
            "Creating JWT using RS256 from private key file %s", options.privateKeyFile));
  } else if (options.algorithm.equals("ES256")) {
    connectOptions.setPassword(
        createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
  } else {
    throw new IllegalArgumentException(
        "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
  }

  device.isConnected = true;

  MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());

  try {
    client.setCallback(device);
    client.connect(connectOptions);
  } catch (MqttException e) {
    e.printStackTrace();
  }

  // wait for it to connect
  device.waitForConnection(5);

  client.subscribe(mqttConfigTopic, 1);

  for (int i = 0; i < options.numMessages; i++) {
    device.updateSensorData();

    JSONObject payload = new JSONObject();
    payload.put("temperature", device.temperature);
    System.out.println("Publishing payload " + payload.toString());
    MqttMessage message = new MqttMessage(payload.toString().getBytes());
    message.setQos(1);
    client.publish(mqttTelemetryTopic, message);
    Thread.sleep(1000);
  }
  client.disconnect();

  System.out.println("Finished looping successfully : " + options.mqttBridgeHostname);
}