Java Code Examples for org.eclipse.paho.client.mqttv3.MqttException#printStackTrace()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttException#printStackTrace() . 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: 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 2
Source File: MqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try {
            MqttMessage message = new MqttMessage();
            String jsonSt = marshaller.marshal(event);
            message.setPayload(jsonSt.getBytes(StandardCharsets.UTF_8));
            client.publish(
                    getValue(config, TOPIC_PROPERTY, TOPIC_DEFAULT),
                    message);
        } catch (Exception e) {
            LOGGER.warn("Error sending to MQTT server " + client.getServerURI(), e);
            try {
                client.disconnect();
                client.connect();
            } catch (MqttException e1) {
                e1.printStackTrace();
            }
        }
    }
}
 
Example 3
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 5 votes vote down vote up
public void subscribe(String topic, int qos) {
	try {
		LOG.info("Subscribe to :: "+ topic);
		mqttClient.subscribe(topic, qos);
	} catch (MqttException me) {
		LOG.error("reason "+me.getReasonCode());
		LOG.error("msg "+me.getMessage());
		LOG.error("loc "+me.getLocalizedMessage());
		LOG.error("cause "+me.getCause());
		LOG.error("excep "+me);
           me.printStackTrace();
	}
}
 
Example 4
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 5 votes vote down vote up
public void publish(String topic, String content) {
	try {
		MqttMessage message = new MqttMessage(content.getBytes());
           message.setQos(QOS);
           LOG.info("publish :: {"+topic+" ["+message+" ]}");
		mqttClient.publish(topic, message);
	} catch (MqttException me) {
		LOG.error("reason "+me.getReasonCode());
		LOG.error("msg "+me.getMessage());
		LOG.error("loc "+me.getLocalizedMessage());
		LOG.error("cause "+me.getCause());
		LOG.error("excep "+me);
           me.printStackTrace();
	}
}
 
Example 5
Source File: MqttServerEndpointStatusTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connected(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();
    context.assertTrue(client.isConnected() && this.endpoint.isConnected());
  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 6
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Publish event, on the behalf of a device, to the IBM Watson IoT Platform.
 * <br>
 * This method will attempt to create a JSON obejct out of the payload
 * 
 * @param typeId   object of String which denotes deviceType
 * @param deviceId object of String which denotes deviceId
 * @param eventId  object of String which denotes event
 * @param data     Payload data
 * @param qos      Quality of Service, in int - can have values 0,1,2
 * 
 * @return Whether the send was successful.
 */
@SuppressWarnings("unchecked")
public boolean publishEvent(String typeId, String deviceId, String eventId, Object data, int qos) {
	if (data == null) {
		throw new NullPointerException("Data object for event publish can not be null");
	}

	// Find the codec for the data class
	@SuppressWarnings("rawtypes")
	MessageCodec codec = messageCodecs.get(data.getClass());

	// Check that a codec is registered
	if (codec == null) {
		LOG.warn("Unable to encode event data of class " + data.getClass().getName());
		return false;
	}

	byte[] payload = codec.encode(data, new DateTime());
	String topic = "iot-2/type/" + typeId + "/id/" + deviceId + "/evt/" + eventId + "/fmt/"
			+ codec.getMessageFormat();
	LOG.debug("Publishing event to " + topic);

	MqttMessage msg = new MqttMessage(payload);
	msg.setQos(qos);
	msg.setRetained(false);

	try {
		mqttAsyncClient.publish(topic, msg);
	} catch (MqttException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 7
Source File: HomeDashService.java    From homeDash with Apache License 2.0 5 votes vote down vote up
private void publishMessage(byte[] message, String topicPostfix){
    if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {
        try {
            String test = new String(message, StandardCharsets.UTF_8);
            Log.i(TAG,test);
            mqttAndroidClient.publish(topicPrefix+"sensor/"+topicPostfix, message, 0, false);

        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
 
Example 8
Source File: MqttServerUnsubscribeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void unsubscribe(TestContext context) {

  this.subscribeAsync = context.async();
  this.unsubscribeAsync = 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();

    String[] topics = new String[]{MQTT_TOPIC};
    int[] qos = new int[]{0};
    client.subscribe(topics, qos);

    this.subscribeAsync.await();

    client.unsubscribe(topics);

    this.unsubscribeAsync.await();

    context.assertTrue(true);

  } catch (MqttException e) {

    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 9
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Unsubscribe from device commands of the IBM Watson IoT Platform. <br>
 * 
 * @param typeId    object of String which denotes deviceType
 * @param deviceId  object of String which denotes deviceId
 * @param commandId object of String which denotes command
 */
public void unsubscribeFromDeviceCommands(String typeId, String deviceId, String commandId) {
	try {
		String topic = "iot-2/type/" + typeId + "/id/" + deviceId + "/cmd/" + commandId + "/fmt/json";
		subscriptions.remove(topic);
		mqttAsyncClient.unsubscribe(topic).waitForCompletion(DEFAULT_ACTION_TIMEOUT);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 10
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 5 votes vote down vote up
public void destroy() {
	try {
           LOG.info("Disconnecting " + endpointID + " from broker");
           mqttClient.disconnect();
           mqttClient.close();
	} catch(MqttException me) {
		LOG.error("reason "+me.getReasonCode());
		LOG.error("msg "+me.getMessage());
		LOG.error("loc "+me.getLocalizedMessage());
		LOG.error("cause "+me.getCause());
		LOG.error("excep "+me);
           me.printStackTrace();
       }
	
}
 
Example 11
Source File: GatewayClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Unsubscribe from device commands, on the behalf of a device, from the IBM
 * Watson IoT Platform.
 * 
 * @param typeId    object of String which denotes deviceType
 * @param deviceId  object of String which denotes deviceId
 * @param commandId object of String which denotes command name
 */
public void unsubscribeFromDeviceCommands(String typeId, String deviceId, String commandId) {
	try {
		String newTopic = "iot-2/type/" + typeId + "/id/" + deviceId + "/cmd/" + commandId + "/fmt/json";
		mqttAsyncClient.unsubscribe(newTopic).waitForCompletion(DEFAULT_ACTION_TIMEOUT);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 12
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Unsubscribe from application status of the IBM Watson IoT Platform. <br>
 * 
 * @param appId object of String which denotes the application uniquely in the
 *              organization
 */
public void unSubscribeFromApplicationStatus(String appId) {
	try {
		String topic = "iot-2/app/" + appId + "/mon";
		mqttAsyncClient.unsubscribe(topic).waitForCompletion(DEFAULT_ACTION_TIMEOUT);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 13
Source File: DeviceClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void connectComplete(boolean reconnect, String serverURI) {
	if (reconnect) {
		LOG.info("Reconnected to " + serverURI);
		if (!config.getOrgId().equals("quickstart")) {
			try {
				subscribeToCommands();
			} catch (MqttException e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example 14
Source File: MqttServerDisconnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void bruteDisconnect(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.close();
    context.assertTrue(false);
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_CLIENT_CONNECTED);
    e.printStackTrace();
  }
}
 
Example 15
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Subscribe to application status of the IBM Watson IoT Platform. <br>
 * 
 * @param appId object of String which denotes the application uniquely in the
 *              organization
 */
public void subscribeToApplicationStatus(String appId) {
	try {
		String newTopic = "iot-2/app/" + appId + "/mon";
		subscriptions.put(newTopic, new Integer(0));
		mqttAsyncClient.subscribe(newTopic, 0).waitForCompletion(DEFAULT_ACTION_TIMEOUT);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: MainActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 5 votes vote down vote up
private void startConnect(String clientID, String serverIP, String port) {
    //服务器地址
    String  uri ="tcp://";
    uri=uri+serverIP+":"+port;
    Log.d("MainActivity",uri+"  "+clientID);
    /**
     * 连接的选项
     */
    MqttConnectOptions conOpt = new MqttConnectOptions();
    /**设计连接超时时间*/
    conOpt.setConnectionTimeout(3000);
    /**设计心跳间隔时间300秒*/
    conOpt.setKeepAliveInterval(300);
    /**
     * 创建连接对象
     */
     client = new MqttAndroidClient(this,uri, clientID);
    /**
     * 连接后设计一个回调
     */
    client.setCallback(new MqttCallbackHandler(this, clientID));
    /**
     * 开始连接服务器,参数:ConnectionOptions,  IMqttActionListener
     */
    try {
        client.connect(conOpt, null, new ConnectCallBackHandler(this));
    } catch (MqttException e) {
        e.printStackTrace();
    }

}
 
Example 17
Source File: MainActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();
    if(client!=null)
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
}
 
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: QoS1Consumer.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("QoS1Consumer initializing...");

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

    try {
        // Create an Mqtt client
        MqttAsyncClient mqttClient = new MqttAsyncClient(host, "HelloWorldQoS1Consumer");
        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);
        IMqttToken conToken = mqttClient.connect(connOpts);
        conToken.waitForCompletion(10000);
        if (!conToken.isComplete() || conToken.getException() != null) {
            System.out.println("Error connecting: " + conToken.getException());
            System.exit(-1);
        }
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);

        // 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) {
            }

        });

        // Topic filter the client will subscribe to
        final String subTopic = "Q/tutorial";

        // Subscribe client to the topic filter with QoS level of 1
        System.out.println("Subscribing client to topic: " + subTopic);
        IMqttToken subToken = mqttClient.subscribe(subTopic, 1);
        subToken.waitForCompletion(10000);
        if (!subToken.isComplete() || subToken.getException() != null) {
            System.out.println("Error subscribing: " + subToken.getException());
            System.exit(-1);
        }
        if (subToken.getGrantedQos()[0] != 1) {
            System.out.println("Expected OoS level 1 but got OoS level: " + subToken.getGrantedQos()[0]);
            System.exit(-1);
        }
        System.out.println("Subscribed with OoS level 1 and waiting to receive msgs");

        // 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 20
Source File: GatewayClient.java    From iot-java with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Subscribe to device commands, on the behalf of a device, to the IBM Watson
 * IoT Platform. <br>
 * 
 * @param tpyeId    object of String which denotes deviceType
 * @param deviceId  object of String which denotes deviceId
 * @param commandId object of String which denotes command
 * @param format    object of String which denotes format, typical example of
 *                  format could be json
 * @param qos       Quality of Service, in int - can have values 0,1,2
 */
public void subscribeToDeviceCommands(String tpyeId, String deviceId, String commandId, String format, int qos) {
	try {
		String newTopic = "iot-2/type/" + tpyeId + "/id/" + deviceId + "/cmd/" + commandId + "/fmt/" + format;
		mqttAsyncClient.subscribe(newTopic, qos).waitForCompletion(DEFAULT_ACTION_TIMEOUT);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}