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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions#setMqttVersion() . 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: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnect31() {
    try {
        // client id must less then 23 bytes in 3.1
        String clientId = UUID.randomUUID().toString().split("-")[0];
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setConnectionTimeout(this.actionTimeout);
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        mqttClient.connect(connOpts);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 2
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testWill() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setConnectionTimeout(this.actionTimeout);
        connectOptions.setKeepAliveInterval(this.actionTimeout);
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        connectOptions.setWill(this.topicName, this.content.getBytes(), 1, false);
        connectOptions.setCleanSession(true);
        mqttClient.connect(this.cleanupOptions);
        mqttClient.disconnect();

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 3
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnect31() {
    try {
        // client id must less then 23 bytes in 3.1
        String clientId = UUID.randomUUID().toString().split("-")[0];
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setConnectionTimeout(this.actionTimeout);
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        mqttClient.connect(connOpts);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 4
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testWill() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setConnectionTimeout(this.actionTimeout);
        connectOptions.setKeepAliveInterval(this.actionTimeout);
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        connectOptions.setWill(this.topicName, this.content.getBytes(), 1, false);
        connectOptions.setCleanSession(true);
        mqttClient.connect(this.cleanupOptions);
        mqttClient.disconnect();

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 5
Source File: IotCoreClient.java    From cloud-iot-core-androidthings with Apache License 2.0 6 votes vote down vote up
private MqttConnectOptions configureConnectionOptions() throws JoseException {
    MqttConnectOptions options = new MqttConnectOptions();

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

    // Cloud IoT Core ignores the user name field, but Paho requires a user name in order
    // to send the password field. We set the user name because we need the password to send a
    // JWT to authorize the device.
    options.setUserName("unused");

    // generate the jwt password
    options.setPassword(mJwtGenerator.createJwt().toCharArray());

    return options;
}
 
Example 6
Source File: MqttClientService.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() throws MqttException {
   final String serverURI = "tcp://localhost:1883";
   final MqttConnectOptions options = new MqttConnectOptions();
   options.setAutomaticReconnect(true);
   options.setCleanSession(false);
   options.setMaxInflight(1000);
   options.setServerURIs(new String[] {serverURI});
   options.setMqttVersion(MQTT_VERSION_3_1_1);

   final ThreadFactory threadFactory = new DefaultThreadFactory("mqtt-client-exec");
   executorService = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
   mqttClient = new MqttClient(serverURI, clientId, persistence, executorService);
   mqttClient.setTimeToWait(-1);
   mqttClient.connect(options);
   mqttClient.setCallback(this);
   log.debugf("[MQTT][Connected][client: %s]", clientId);
}
 
Example 7
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedUnacceptableProtocolVersion(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    // trying the old 3.1
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION);
  }
}
 
Example 8
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedClientIdZeroBytes(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(false);
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
    context.assertNotNull(rejection);
  }
}
 
Example 9
Source File: MqttServerClientIdentifierTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "invalid-id-with-24-chars", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(false);

  } catch (MqttException ignore) {
    context.assertTrue(true);
  }
}
 
Example 10
Source File: MqttServerClientIdentifierTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "id-madeof-23-characters", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(true);

  } catch (MqttException ignore) {
    context.assertTrue(false);
  }
}
 
Example 11
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test(expected = MqttException.class)
public void testConnect31ClientTooLong() throws MqttException {
    // client id must less then 23 bytes in 3.1
    String clientId = UUID.randomUUID().toString();
    MqttClient mqttClient = new MqttClient(this.url, clientId, null);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setConnectionTimeout(this.actionTimeout);
    connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    mqttClient.connect(connOpts);

    Assert.assertTrue(true);
}
 
Example 12
Source File: MqttFacade.java    From iaf with Apache License 2.0 5 votes vote down vote up
public void configure() throws ConfigurationException {
	if (StringUtils.isEmpty(getClientId())) {
		throw new ConfigurationException("clientId must be specified");
	}
	if (StringUtils.isEmpty(getBrokerUrl())) {
		throw new ConfigurationException("brokerUrl must be specified");
	}
	if (StringUtils.isEmpty(getTopic())) {
		throw new ConfigurationException("topic must be specified");
	}
	if (StringUtils.isEmpty(getPersistenceDirectory())) {
		throw new ConfigurationException("persistenceDirectory must be specified");
	}
	connectOptions = new MqttConnectOptions();
	connectOptions.setCleanSession(isCleanSession());
	connectOptions.setAutomaticReconnect(isAutomaticReconnect());
	connectOptions.setConnectionTimeout(getTimeout());
	connectOptions.setKeepAliveInterval(getKeepAliveInterval());
	connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_DEFAULT); //Default: 0, V3.1: 3, V3.1.1: 4

	if(!StringUtils.isEmpty(getAuthAlias()) || (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword()))) {
		CredentialFactory credentialFactory = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
		connectOptions.setUserName(credentialFactory.getUsername());
		connectOptions.setPassword(credentialFactory.getPassword().toCharArray());
	}

	MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(getPersistenceDirectory());
	try {
		client = new MqttClient(brokerUrl, clientId, dataStore);
	} catch (MqttException e) {
		throw new ConfigurationException("Could not create client", e);
	}
}
 
Example 13
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 14
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 15
Source File: PushListActivity.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private MqttConnectOptions constructConnectionOtions() {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setMqttVersion(3);
    options.setCleanSession(true);
    options.setKeepAliveInterval(60);
    return options;
}
 
Example 16
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test(expected = MqttException.class)
public void testConnect31ClientTooLong() throws MqttException {
    // client id must less then 23 bytes in 3.1
    String clientId = UUID.randomUUID().toString();
    MqttClient mqttClient = new MqttClient(this.url, clientId, null);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setConnectionTimeout(this.actionTimeout);
    connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    mqttClient.connect(connOpts);

    Assert.assertTrue(true);
}
 
Example 17
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 18
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);
}
 
Example 19
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 20
Source File: MQTTClientBuilder.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private MqttConnectOptions getOptions() {
  MqttConnectOptions options = new MqttConnectOptions();

  if ( isSecure ) {
    setSSLProps( options );
  }
  if ( !StringUtil.isEmpty( username ) ) {
    options.setUserName( username );
  }
  if ( !StringUtil.isEmpty( password ) ) {
    options.setPassword( password.toCharArray() );
  }

  if ( !StringUtil.isEmpty( keepAliveInterval ) ) {
    options.setKeepAliveInterval( Integer.parseInt( keepAliveInterval ) );
  }

  if ( !StringUtil.isEmpty( maxInflight ) ) {
    options.setMaxInflight( Integer.parseInt( maxInflight ) );
  }

  if ( !StringUtil.isEmpty( connectionTimeout ) ) {
    options.setConnectionTimeout( Integer.parseInt( connectionTimeout ) );
  }

  if ( !StringUtil.isEmpty( cleanSession ) ) {
    options.setCleanSession( BooleanUtils.toBoolean( cleanSession ) );
  }

  if ( !StringUtil.isEmpty( serverUris ) ) {
    options.setServerURIs(
      Arrays.stream( serverUris.split( ";" ) ).map( uri -> getProtocol() + uri ).toArray( String[]::new ) );
  }

  if ( !StringUtil.isEmpty( mqttVersion ) ) {
    options.setMqttVersion( Integer.parseInt( mqttVersion ) );
  }

  if ( !StringUtil.isEmpty( automaticReconnect ) ) {
    options.setAutomaticReconnect( BooleanUtils.toBoolean( automaticReconnect ) );
  }

  return options;
}