CloudAMQP with MQTT and Java Getting started

The by far best MQTT client for Java/JVM is Paho. Add the dependencys for the library or download the jar files and include them into the project. The following code snippet show how you can connect to a server and publish/subscribe a message. Check the webpage linked above for futher information.

ClientId is the unique MQTT client id to use for the device. If set to "" or None, the Paho library will generate a client id automatically.

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MQTTSample {
  public static void main(String[] args) {
  String topic        = "CloudAMQP";
  String content      = "Hello CloudAMQP";
  int qos             = 1;
  String broker       = "tcp://CloudAMQP_server:CloudAMQP_port";

  //MQTT client id to use for the device. "" will generate a client id automatically
  String clientId     = "ClientId";

  MemoryPersistence persistence = new MemoryPersistence();
  try {
    MqttClient mqttClient = new MqttClient(broker, clientId, persistence);
    mqttClient.setCallback(new MqttCallback() {
      public void messageArrived(String topic, MqttMessage msg)
                throws Exception {
                    System.out.println("Recived:" + topic);
                    System.out.println("Recived:" + new String(msg.getPayload()));
              }

      public void deliveryComplete(IMqttDeliveryToken arg0) {
                  System.out.println("Delivary complete");
              }

      public void connectionLost(Throwable arg0) {
                  // TODO Auto-generated method stub
              }
    });

    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setCleanSession(true);
    connOpts.setUserName("CloudAMQP_username");
    connOpts.setPassword(new char[]{'p', 'a', 's', 's', 'w', 'r', 'd'});
    mqttClient.connect(connOpts);
    MqttMessage message = new MqttMessage(content.getBytes());
    message.setQos(qos);
    System.out.println("Publish message: " + message);
    mqttClient.subscribe(topic, qos);
    mqttClient.publish(topic, message);
    mqttClient.disconnect();
    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();
  }
}
}