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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions#setUserName() . 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: Connection.java    From EMQ-Android-Toolkit with Apache License 2.0 6 votes vote down vote up
public MqttConnectOptions getMqttConnectOptions() {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(isCleanSession());
    options.setConnectionTimeout(getTimeout());
    options.setKeepAliveInterval(getKeepAlive());

    if (!getUsername().isEmpty()) {
        options.setUserName(getUsername());
    }

    if (!getPassword().isEmpty()) {
        options.setPassword(getPassword().toCharArray());
    }

    if (!getLwtTopic().isEmpty() && !getLwtPayload().isEmpty()) {
        options.setWill(getLwtTopic(), getLwtPayload().getBytes(), getLwtQos(), isLwtRetained());
    }

    return options;
}
 
Example 2
Source File: DeviceConfig.java    From iot-java with Eclipse Public License 1.0 6 votes vote down vote up
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException {
	MqttConnectOptions connectOptions = new MqttConnectOptions();

	connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT);

	if (getMqttPassword() != null) {
		connectOptions.setUserName(getMqttUsername());
		connectOptions.setPassword(getMqttPassword().toCharArray());
	}

	connectOptions.setCleanSession(this.options.mqtt.cleanStart);
	connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive);
	connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES);
	connectOptions.setAutomaticReconnect(true);

	if (!Arrays.asList(1883, 80).contains(options.mqtt.port)) {
		SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
		sslContext.init(null, null, null);

		connectOptions.setSocketFactory(sslContext.getSocketFactory());
	}

	return connectOptions;
}
 
Example 3
Source File: MqttService.java    From PresencePublisher with MIT License 6 votes vote down vote up
public void sendMessages(List<Message> messages) throws MqttException {
    HyperLog.i(TAG, "Sending " + messages.size() + " messages to server");
    boolean tls = sharedPreferences.getBoolean(USE_TLS, false);
    String clientCertAlias = sharedPreferences.getString(CLIENT_CERTIFICATE, null);
    String login = sharedPreferences.getString(USERNAME, "");
    String password = securePreferences.getString(PASSWORD, "");

    MqttClient mqttClient = new MqttClient(getMqttUrl(tls), Settings.Secure.ANDROID_ID, new MemoryPersistence());
    MqttConnectOptions options = new MqttConnectOptions();
    options.setConnectionTimeout(5);
    if (!login.isEmpty() && !password.isEmpty()) {
        options.setUserName(login);
        options.setPassword(password.toCharArray());
    }
    if (tls) {
        options.setSocketFactory(factory.getSslSocketFactory(clientCertAlias));
    }
    mqttClient.connect(options);
    for (Message message : messages) {
        mqttClient.publish(message.getTopic(), message.getContent().getBytes(Charset.forName("UTF-8")), 1, false);
    }
    mqttClient.disconnect(5);
    mqttClient.close(true);
    HyperLog.i(TAG, "Sending messages was successful");
}
 
Example 4
Source File: VenvyMqttClientHelper.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
private MqttConnectOptions initMqttOption() {
    // MQTT的连接设置

    MqttConnectOptions connectOption = new MqttConnectOptions();// MQTT参数
    // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
    connectOption.setCleanSession(false);
    // 设置连接的用户名
    connectOption.setUserName(socketKey);
    connectOption.setServerURIs(new String[]{serverUrl});
    // 设置连接的密码
    connectOption.setPassword(socketPassword.toCharArray());
    // 设置超时时间 单位为秒
    connectOption.setConnectionTimeout(15);
    // 设置会话心跳时间 单位为秒 服务器会每隔2*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
    connectOption.setKeepAliveInterval(40);
    return connectOption;
}
 
Example 5
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
public void run() {
	try {
		// Connect to the MQTT Server
		MqttConnectOptions options = new MqttConnectOptions();
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(2000);	
		client.setCallback(this);
		client.connect(options);
		
		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/+/" + edgeNode, 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/+/" + edgeNode + "/*", 0);
		
		// Loop to receive input commands
		while (true) {
			System.out.print("\n> ");
			
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String line = br.readLine();

			handleCommand(line);
		}
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 6
Source File: MqttUsage.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public MqttUsage(String host, int port, String user, String pwd) {
    try {
        client = new MqttClient("tcp://" + host + ":" + port, UUID.randomUUID().toString());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(user);
        options.setPassword(pwd.toCharArray());
        client.connect(options);
        await().until(client::isConnected);
    } catch (MqttException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: TrainLocationClient.java    From osgi.iot.contest.sdk with Apache License 2.0 5 votes vote down vote up
@Activate
void activate(LocationConfig config) {

    initConfig(config.code2tag());

    BiFunction<String, String, String> getOrDefault = (t, u) -> t != null ? t : u;

    try {
        String brokerUrl = getOrDefault.apply(config.brokerUrl(), BROKER_URL);
        String username = getOrDefault.apply(config.username(), USERNAME);
        String password = getOrDefault.apply(config.password(), PASSWORD);

        MqttConnectOptions options = new MqttConnectOptions();
        if (!username.isEmpty()) {
            options.setUserName(username);
            options.setPassword(password.toCharArray());
        }

        // Connect and start the session
        info("Connecting to MQTT broker <{}>", brokerUrl);
        mqttClient = new MqttClient(brokerUrl, CLIENT_ID);
        mqttClient.setCallback(new MyCallbackHandler());
        mqttClient.connect(options);

        // Subscribe
        String topic = "TrainDemo/#";
        info("Subscribing to topic <{}>", topic);
        mqttClient.subscribe(topic);
    } catch (Exception e) {
        error(e.toString());
        throw new RuntimeException(e);
    }
}
 
Example 8
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 9
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private MqttConnectOptions getConnectionOptions() {
    MobiComUserPreference userPreference = MobiComUserPreference.getInstance(context);
    String authToken = userPreference.getUserAuthToken();

    MqttConnectOptions connOpts = new MqttConnectOptions();

    if (!TextUtils.isEmpty(authToken)) {
        connOpts.setUserName(getApplicationKey(context));
        connOpts.setPassword(authToken.toCharArray());
    }
    connOpts.setConnectionTimeout(60);
    connOpts.setWill(STATUS, (userPreference.getSuUserKeyString() + "," + userPreference.getDeviceKeyString() + "," + "0").getBytes(), 0, true);
    return connOpts;
}
 
Example 10
Source File: MqttSubscriberClient.java    From product-iots with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param serverAddress Mqtt broker address
 * @param clientId Client ID
 * @param topicName Topic Name
 * @throws MqttException Mqtt Exception
 */
public MqttSubscriberClient(String serverAddress, String clientId, String topicName, String accessToken) throws
        MqttException {
    mqttMessages = new ArrayList<>();
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(serverAddress, clientId, persistence);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    client.setCallback(this);
    connectOptions.setUserName(accessToken);
    connectOptions.setPassword("".toCharArray());
    connectOptions.setCleanSession(true);
    connectOptions.setKeepAliveInterval(300);
    client.connect(connectOptions);
    client.subscribe(topicName);
}
 
Example 11
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 12
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 13
Source File: PahoMQTTQOS2SecurityTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);

   MqttClient consumer = createPahoClient("consumerId");
   MqttClient producer = createPahoClient("producerId");
   MqttConnectOptions conOpt = new MqttConnectOptions();
   conOpt.setCleanSession(true);
   conOpt.setUserName(user1);
   conOpt.setPassword(password1.toCharArray());
   consumer.connect(conOpt);
   consumer.subscribe(getQueueName(), 2);
   final boolean[] failed = new boolean[1];
   consumer.setCallback(new MqttCallback() {


      @Override
      public void connectionLost(Throwable cause) {
         cause.printStackTrace();
         failed[0] = true;
         latch.countDown();
      }

      @Override
      public void messageArrived(String topic, MqttMessage message) throws Exception {
         latch.countDown();
      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect(conOpt);
   producer.publish(getQueueName(), "hello".getBytes(), 2, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
   Assert.assertFalse(failed[0]);
}
 
Example 14
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
public void run() {
	try {
		// Random generator and thread pool for outgoing published messages
		executor = Executors.newFixedThreadPool(1);

		// Build up DEATH payload - note DEATH payloads don't have a regular sequence number
		SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
		deathPayload = addBdSeqNum(deathPayload);
		byte[] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());

		MqttConnectOptions options = new MqttConnectOptions();

		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}

		// Connect to the MQTT Server
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(2000);
		client.setCallback(this); // short timeout on failure to connect
		client.connect(options);

		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);

		// Loop forever publishing data every PUBLISH_PERIOD
		while (true) {
			Thread.sleep(PUBLISH_PERIOD);

			if (client.isConnected()) {
				synchronized (seqLock) {
					System.out.println("Connected - publishing new data");
					// Create the payload and add some metrics
					SparkplugBPayload payload = new SparkplugBPayload(new Date(), newComplexTemplateInstance(),
							getSeqNum(), newUUID(), null);

					client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId,
							new SparkplugBPayloadEncoder().getBytes(payload), 0, false);
				}
			} else {
				System.out.println("Not connected - not publishing data");
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: MqttListener.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public void initAsyncClient() {

        mqttAsyncClient = confac.getMqttAsyncClient(this.name);

        MqttClientManager clientManager = MqttClientManager.getInstance();
        String inboundIdentifier = clientManager
                .buildIdentifier(mqttAsyncClient.getClientId(), confac.getServerHost(), confac.getServerPort());

        if (!clientManager.hasMqttCallback(inboundIdentifier)) {
            //registering callback for the first time
            connectOptions = new MqttConnectOptions();
            connectOptions.setCleanSession(cleanSession);
            if (userName != null && password != null) {
                connectOptions.setUserName(userName);
                connectOptions.setPassword(password.toCharArray());
            }
            if (socketFactory != null) {
                connectOptions.setSocketFactory(socketFactory);
            }
            mqttAsyncCallback = new MqttAsyncCallback(mqttAsyncClient, injectHandler, confac, connectOptions,
                                                      mqttProperties);
            mqttAsyncCallback.setName(params.getName());
            connectionConsumer = new MqttConnectionConsumer(connectOptions, mqttAsyncClient, confac, mqttProperties,
                                                            name);
            mqttAsyncCallback.setMqttConnectionConsumer(connectionConsumer);
            mqttAsyncClient.setCallback(mqttAsyncCallback);
            //here we register the callback handler
            clientManager.registerMqttCallback(inboundIdentifier, mqttAsyncCallback);
        } else {
            //has previously registered callback we just update the reference
            //in other words has previous un-destroyed callback
            //this is a manually tenant loading case
            //should clear the previously set tenant loading flags for the inbound identifier
            clientManager.unRegisterInboundTenantLoadingFlag(inboundIdentifier);

            mqttAsyncCallback = clientManager.getMqttCallback(inboundIdentifier);

            mqttAsyncCallback.setName(params.getName());
            connectOptions = mqttAsyncCallback.getMqttConnectionOptions();
            connectionConsumer = mqttAsyncCallback.getMqttConnectionConsumer();

            //but we need to update injectHandler due to recreation of synapse environment
            mqttAsyncCallback.updateInjectHandler(injectHandler);

        }
    }
 
Example 16
Source File: QoS1Producer.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("QoS1Producer initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldQoS1Producer");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());

        // Connect the client
        System.out.println("Connecting to Solace messaging at " + host);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Create a Mqtt message
        String content = "Hello world from MQTT!";
        MqttMessage message = new MqttMessage(content.getBytes());
        // Set the QoS on the Messages - 
        // Here we are using QoS of 1 (equivalent to Persistent Messages in Solace)
        message.setQos(1);

        System.out.println("Publishing message: " + content);

        // Publish the message
        mqttClient.publish("Q/tutorial", message);

        // Disconnect the client
        mqttClient.disconnect();

        System.out.println("Message published. Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
Example 17
Source File: TopicSubscriber.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicSubscriber initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldSub");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        
        // Connect the client
        System.out.println("Connecting to Solace messaging at "+host);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);
        
        // Topic filter the client will subscribe to
        final String subTopic = "T/GettingStarted/pubsub";
        
        // Callback - Anonymous inner-class for receiving messages
        mqttClient.setCallback(new MqttCallback() {

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // Called when a message arrives from the server that
                // matches any subscription made by the client
                String time = new Timestamp(System.currentTimeMillis()).toString();
                System.out.println("\nReceived a Message!" +
                        "\n\tTime:    " + time + 
                        "\n\tTopic:   " + topic + 
                        "\n\tMessage: " + new String(message.getPayload()) + 
                        "\n\tQoS:     " + message.getQos() + "\n");
                latch.countDown(); // unblock main thread
            }

            public void connectionLost(Throwable cause) {
                System.out.println("Connection to Solace messaging lost!" + cause.getMessage());
                latch.countDown();
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });
        
        // Subscribe client to the topic filter and a QoS level of 0
        System.out.println("Subscribing client to topic: " + subTopic);
        mqttClient.subscribe(subTopic, 0);
        System.out.println("Subscribed");

        // Wait for the message to be received
        try {
            latch.await(); // block here until message received, and latch will flip
        } catch (InterruptedException e) {
            System.out.println("I was awoken while waiting");
        }
        
        // Disconnect the client
        mqttClient.disconnect();
        System.out.println("Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
Example 18
Source File: AuthorizationTests.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Test
 public void testPublishAuthentication(TestContext context) throws MqttException {
 	Tester c = null;
 	try {
      String serverURL = "tcp://localhost:"+config.getInteger("tcp_port");
      c = new Tester(1, "Paho", serverURL);

      auth.setLoginRequired(true);
      auth.setDoSubscribeChecks(false);
      auth.setDoPublishChecks(true);

      MqttConnectOptions o = new MqttConnectOptions();
      o.setUserName("user1");
      o.setPassword("secret".toCharArray());
      auth.setUserPass("user1", "secret");
      c.connect(o);
      
      System.out.println("Check that publish to allowed topic works");
      String topic = "valid/topic";
      auth.setAllowedPubTopic(topic);
      c.subscribe(topic);
      int count = (int) c.getMessaggiArrivatiPerClient().values().toArray()[0];
      c.publish(topic);
      count = (int) c.getMessaggiArrivatiPerClient().values().toArray()[0] - count;
      c.unsubcribe(topic);	        
      context.assertNotEquals(count, 0, "Publish to valid topic not received");
      
      System.out.println("Check that publish to illegal topic does not send messages");
      String illegalTopic = "illegal/topic";
      c.subscribe(illegalTopic);
      count = (int) c.getMessaggiArrivatiPerClient().values().toArray()[0];
     	c.publish(illegalTopic);			// Illegal publish fails silently
      count = (int) c.getMessaggiArrivatiPerClient().values().toArray()[0] - count;
      c.unsubcribe(illegalTopic);	        
      context.assertEquals(count, 0, "Publish to illegal topic sent message");
      
 	} catch (Throwable e) {
 		context.fail(e.getMessage());
 	} finally {
try {c.disconnect();} catch (Exception ex){}	        	
 	}
 }
 
Example 19
Source File: SparkplugRaspberryPiExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Establish an MQTT Session with Sparkplug defined Death Certificate. It may not be
 * Immediately intuitive that the Death Certificate is created prior to publishing the
 * Birth Certificate, but the Death Certificate is actually part of the MQTT Session 
 * establishment. For complete details of the actual MQTT wire protocol refer to the 
 * latest OASyS MQTT V3.1.1 standards at:
 * http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html
 * 
 * @return true = MQTT Session Established
 */
public boolean establishMqttSession() {
	try {

		//
		// Setup the MQTT connection parameters using the Paho MQTT Client.
		//
		MqttConnectOptions options = new MqttConnectOptions();
		
		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}
		
		// Autoreconnect enable
		options.setAutomaticReconnect(true);
		// MQTT session parameters Clean Start = true
		options.setCleanSession(true);
		// Session connection attempt timeout period in seconds
		options.setConnectionTimeout(10);
		// MQTT session parameter Keep Alive Period in Seconds
		options.setKeepAliveInterval(30);
		// MQTT Client Username
		options.setUserName(username);
		// MQTT Client Password
		options.setPassword(password.toCharArray());
		//
		// Build up the Death Certificate MQTT Payload. Note that the Death
		// Certificate payload sequence number
		// is not tied to the normal message sequence numbers.
		//
		SparkplugBPayload payload = new SparkplugBPayloadBuilder(getNextSeqNum())
				.setTimestamp(new Date())
				.addMetric(new MetricBuilder("bdSeq",
						MetricDataType.Int64,
						bdSeq)
						.createMetric())
				.createPayload();
		byte[] bytes = new SparkplugBPayloadEncoder().getBytes(payload);
		//
		// Setup the Death Certificate Topic/Payload into the MQTT session
		// parameters
		//
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, bytes, 0, false);

		//
		// Create a new Paho MQTT Client
		//
		client = new MqttClient(serverUrl, clientId);
		//
		// Using the parameters set above, try to connect to the define MQTT
		// server now.
		//
		System.out.println("Trying to establish an MQTT Session to the MQTT Server @ :" + serverUrl);
		client.connect(options);
		System.out.println("MQTT Session Established");
		client.setCallback(this);
		//
		// With a successful MQTT Session in place, now issue subscriptions
		// for the EoN Node and Device "Command" Topics of 'NCMD' and 'DCMD'
		// defined in Sparkplug
		//
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);
	} catch (Exception e) {
		System.out.println("Error Establishing an MQTT Session:");
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 20
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void connect(String brokerURL, String userName, String password, 
			boolean ssl, boolean cleanSession) throws Exception {
		MqttConnectOptions connOpt = new MqttConnectOptions();

		connOpt.setCleanSession(cleanSession);
		connOpt.setKeepAliveInterval(keepAliveInterval);

		if (userName != null) {
			connOpt.setUserName(userName);
		}
		if  (password != null) {
			connOpt.setPassword(password.toCharArray());
		}

		if(ssl) {
//			SSLContext sslContext = SSLContext.getInstance("TLS");
//			TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//			KeyStore keyStore = KeyStore.getInstance("JKS");
//			InputStream in = new FileInputStream(KEY_STORE_LOCATION);
//			keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
//			
//			trustManagerFactory.init(keyStore);
//			sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
//			 
//			connOpt.setSocketFactory(sslContext.getSocketFactory());
			
			
//			connOpt.setSocketFactory(SSLSocketFactory.getDefault());
		}
		
		
//		mqttClient = new MqttAsyncClient(brokerURL, clientID);
		mqttClient = new MqttClient(brokerURL, clientID);
		mqttClient.setCallback(this);
		mqttClient.connect(connOpt);
//		mqttClient.connect(connOpt, new IMqttActionListener() {
//
//			@Override
//			public void onSuccess(IMqttToken asyncActionToken) {
//				// TODO Auto-generated method stub
//				try {
//					setSubscribe();
//				} catch (Exception e) {
//					log.error("Subscription exception: ", e);
//				}
//			}
//
//			@Override
//			public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//		});
		log.debug("MQTT] connected to mqtt borker.");
	
//		pingSender = new TimerPingSender();
//		pingSender.schedule((keepAliveInterval-5)*1000);
//		pingSender.start();
		
//		MqttDeliveryToken token = new MqttDeliveryToken(getClientId());
//		MqttPingReq pingMsg = new MqttPingReq();
//		mqttClient. sendNoWait(pingMsg, token);
		
	}