Java Code Examples for org.eclipse.paho.client.mqttv3.MqttClient#disconnect()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient#disconnect() . 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 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 2
Source File: ManualReceive.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private void receive() throws Exception {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            System.out.println(message);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }

        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC_FILTER);
    client.setCallback(callback);
    System.in.read();
    client.disconnect();
    client.close();
}
 
Example 3
Source File: MqttServerEndpointStatusTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void disconnectedByClient(TestContext context) {

  Async async = context.async();

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    client.disconnect();

    // give more time to the MqttClient to update its connection state
    this.vertx.setTimer(1000, t1 -> {
      async.complete();
    });

    async.await();

    context.assertTrue(!client.isConnected() && !this.endpoint.isConnected());

  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 4
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 5
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 6
Source File: MqttServerSslTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connection(TestContext context) {

  this.async = context.async();

  try {

    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("ssl://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_TLS_PORT), "12345", persistence);

    MqttConnectOptions options = new MqttConnectOptions();
    options.setSocketFactory(this.getSocketFactory("/tls/client-truststore-root-ca.jks", null));
    client.connect(options);

    client.publish(MQTT_TOPIC, MQTT_MESSAGE.getBytes(), 0, false);

    this.async.await();

    client.disconnect();

    context.assertTrue(true);

  } catch (MqttException e) {
    e.printStackTrace();
    context.assertTrue(false);
  } catch (Exception e1) {
    e1.printStackTrace();
    context.assertTrue(false);
  }
}
 
Example 7
Source File: MqttServerDisconnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void disconnect(TestContext context) {

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    client.disconnect();
    context.assertTrue(true);
  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 8
Source File: MqttCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void sendDecanterMessage() throws Exception {
    DispatcherMock dispatcherMock = new DispatcherMock();
    ComponentContext componentContext = new ComponentContextMock();
    componentContext.getProperties().put("server.uri", "tcp://localhost:11883");
    componentContext.getProperties().put("client.id", "decanter");
    componentContext.getProperties().put("topic", "decanter");
    JsonUnmarshaller unmarshaller = new JsonUnmarshaller();
    MqttCollector collector = new MqttCollector();
    collector.dispatcher = dispatcherMock;
    collector.unmarshaller = unmarshaller;
    collector.activate(componentContext);

    MqttClient mqttClient = new MqttClient("tcp://localhost:11883", "client");
    mqttClient.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload("{ \"foo\" : \"bar\" }".getBytes());
    mqttClient.publish("decanter", message);
    mqttClient.disconnect();

    Thread.sleep(200L);

    Assert.assertEquals(1, dispatcherMock.getPostEvents().size());
    Event event = dispatcherMock.getPostEvents().get(0);
    Assert.assertEquals("bar", event.getProperty("foo"));
    Assert.assertEquals("mqtt", event.getProperty("type"));
}
 
Example 9
Source File: CustomAction.java    From itracing2 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    final Matcher matcher = pattern.matcher(this.domain);
    if (matcher.matches()) {
        String login = matcher.group(2);
        String password = matcher.group(3);
        String host = matcher.group(4);
        String port = matcher.group(5);
        String topic = matcher.group(6);

        if (port == null) {
            port = "1883";
        }

        try {
            final MqttClient client = new MqttClient("tcp://" + host + ":" + port,
                    MqttClient.generateClientId(),
                    new MemoryPersistence()
            );
            final MqttConnectOptions options = new MqttConnectOptions();

            if (login != null && password != null) {
                options.setUserName(login);
                options.setPassword(password.toCharArray());
            }

            client.connect(options);
            if (client.isConnected()) {
                client.publish(topic, payload.getBytes(), 0, false);
                client.disconnect();

            }
        } catch (MqttException e) {
            Log.d(TAG, "exception", e);
        }
    }
}
 
Example 10
Source File: PahoMQTTTest.java    From activemq-artemis with Apache License 2.0 5 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");

   consumer.connect();
   consumer.subscribe("test");
   consumer.setCallback(new MqttCallback() {
      @Override
      public void connectionLost(Throwable cause) {

      }

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

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect();
   producer.publish("test", "hello".getBytes(), 1, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
}
 
Example 11
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistConnectAgain() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient client = new MqttClient(this.url, clientId, null);
        client.connect(this.persistOptions);
        client.disconnect();
        client.connect(this.persistOptions);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 12
Source File: MqttConnector.java    From quarks with Apache License 2.0 4 votes vote down vote up
@Override
protected synchronized void doDisconnect(MqttClient client) throws Exception {
    if (client.isConnected())
        client.disconnect();
}
 
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: DeviceTypeManagementJMeterTestCase.java    From product-iots with Apache License 2.0 4 votes vote down vote up
@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods =
        {"DeviceTypeManagementTest"} )
public void testMqttFlow() throws Exception {
    String deviceId = "123422578912";
    String deviceType = "firealarmmqtt";
    String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\"," +
            "\"payLoad\":\"volume:30%\"}}";
    String topic = automationContext.getContextTenant().getDomain() + "/"+deviceType+"/" + deviceId + "/operation/#";
    String clientId = deviceId + ":firealarmmqtt";
    MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload);

    // Allow some time for message delivery
    Thread.sleep(10000);
    ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages();
    Assert.assertEquals("listener did not received mqtt messages ", 1, mqttMessages.size());

    String topicPub = automationContext.getContextTenant().getDomain() + "/"+deviceType+"/"+deviceId+"/events";
    int qos = 2;
    String clientIdPub = deviceId + ":firealarmmqttpub";
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(false);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    for (int i = 0; i < 100; i++) {
        payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}";
        MqttMessage message = new MqttMessage(String.format(payload, i).getBytes());
        message.setQos(qos);
        sampleClient.publish(topicPub, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Allow some time for message delivery
    HttpResponse response = restClient.get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId);
    Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK,
                        response.getResponseCode());
    log.error(response.getData());
    JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count");
    int count = jsonElement.getAsInt();
    Assert.assertTrue("Event count does not match published event count, " + response.getData(),
                      count > 0);

}
 
Example 15
Source File: AndroidSenseEnrollment.java    From product-iots with Apache License 2.0 4 votes vote down vote up
@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);
    }
 
Example 16
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 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: TopicPublisher.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicPublisher initializing...");

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

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldPub");
        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 0 (equivalent to Direct Messaging in Solace)
        message.setQos(0);
        
        System.out.println("Publishing message: " + content);
        
        // Publish the message
        mqttClient.publish("T/GettingStarted/pubsub", 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 19
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 20
Source File: Publisher.java    From mqtt-sample-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MqttException {

    String messageString = "Hello World from Java!";

    if (args.length == 2 ) {
      messageString = args[1];
    }


    System.out.println("== START PUBLISHER ==");


    MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload(messageString.getBytes());
    client.publish("iot_data", message);

    System.out.println("\tMessage '"+ messageString +"' to 'iot_data'");

    client.disconnect();

    System.out.println("== END PUBLISHER ==");

  }