use of org.eclipse.paho.client.mqttv3.MqttClient in project pentaho-kettle by pentaho.
the class MQTTStreamSourceTest method testMQTTOpenException.
@Test
public void testMQTTOpenException() throws Exception {
PowerMockito.mockStatic(MQTTClientBuilder.class);
MQTTClientBuilder.ClientFactory clientFactory = mock(MQTTClientBuilder.ClientFactory.class);
MqttClient mqttClient = mock(MqttClient.class);
MQTTClientBuilder builder = spy(MQTTClientBuilder.class);
MqttException mqttException = mock(MqttException.class);
when(clientFactory.getClient(any(), any(), any())).thenReturn(mqttClient);
when(mqttException.toString()).thenReturn("There is an error connecting");
doThrow(mqttException).when(builder).buildAndConnect();
PowerMockito.when(MQTTClientBuilder.builder()).thenReturn(builder);
MQTTStreamSource source = new MQTTStreamSource(consumerMeta, mqttConsumer);
source.open();
verify(mqttConsumer).stopAll();
verify(mqttConsumer).logError("There is an error connecting");
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project wso2-axis2-transports by wso2.
the class MqttConnectionFactory method createMqttClient.
private MqttClient createMqttClient(String hostName, String port, String sslEnable, String uniqueClientId, int qos, String tempStore) {
MqttDefaultFilePersistence dataStore = getDataStore(uniqueClientId, qos, tempStore);
String mqttEndpointURL = hostName + ":" + port;
// If SSL is enabled in the config, Use SSL tranport
if (sslEnable != null && sslEnable.equalsIgnoreCase("true")) {
mqttEndpointURL = "ssl://" + mqttEndpointURL;
} else {
mqttEndpointURL = "tcp://" + mqttEndpointURL;
}
MqttClient mqttClient;
if (log.isDebugEnabled()) {
log.debug("ClientId " + uniqueClientId);
}
try {
mqttClient = new MqttClient(mqttEndpointURL, uniqueClientId, dataStore);
} catch (MqttException e) {
log.error("Error while creating the MQTT client...", e);
throw new AxisMqttException("Error while creating the MQTT client", e);
}
return mqttClient;
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project wso2-axis2-transports by wso2.
the class MqttConnectionFactory method createMqttAsyncClient.
private MqttAsyncClient createMqttAsyncClient(String uniqueClientId, int qos) {
String sslEnable = parameters.get(MqttConstants.MQTT_SSL_ENABLE);
String tempStore = parameters.get(MqttConstants.MQTT_TEMP_STORE);
MqttDefaultFilePersistence dataStore = getDataStore(uniqueClientId, qos, tempStore);
String mqttEndpointURL = "tcp://" + parameters.get(MqttConstants.MQTT_SERVER_HOST_NAME) + ":" + parameters.get(MqttConstants.MQTT_SERVER_PORT);
// If SSL is enabled in the config, Use SSL tranport
if (sslEnable != null && sslEnable.equalsIgnoreCase("true")) {
mqttEndpointURL = "ssl://" + parameters.get(MqttConstants.MQTT_SERVER_HOST_NAME) + ":" + parameters.get(MqttConstants.MQTT_SERVER_PORT);
}
MqttAsyncClient mqttClient = null;
try {
mqttClient = new MqttAsyncClient(mqttEndpointURL, uniqueClientId, dataStore);
} catch (MqttException e) {
log.error("Error while creating the MQTT client...", e);
}
return mqttClient;
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project ignite by apache.
the class IgniteMqttStreamerTest method beforeTest.
/**
* @throws Exception If failed.
*/
@Before
@SuppressWarnings("unchecked")
public void beforeTest() throws Exception {
grid().<Integer, String>getOrCreateCache(defaultCacheConfiguration());
// find an available local port
try (ServerSocket ss = new ServerSocket(0)) {
port = ss.getLocalPort();
}
// create the broker
broker = new BrokerService();
broker.setDeleteAllMessagesOnStartup(true);
broker.setPersistent(false);
broker.setPersistenceAdapter(null);
broker.setPersistenceFactory(null);
PolicyMap plcMap = new PolicyMap();
PolicyEntry plc = new PolicyEntry();
plc.setQueuePrefetch(1);
broker.setDestinationPolicy(plcMap);
broker.getDestinationPolicy().setDefaultEntry(plc);
broker.setSchedulerSupport(false);
// add the MQTT transport connector to the broker
broker.addConnector("mqtt://localhost:" + port);
broker.setStartAsync(false);
broker.start(true);
// create the broker URL
brokerUrl = "tcp://localhost:" + port;
// create the client and connect
client = new MqttClient(brokerUrl, UUID.randomUUID().toString(), new MemoryPersistence());
client.connect();
// create mqtt streamer
dataStreamer = grid().dataStreamer(DEFAULT_CACHE_NAME);
streamer = createMqttStreamer(dataStreamer);
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project java-docs-samples by GoogleCloudPlatform.
the class MqttExample method main.
// [END iot_mqtt_configcallback]
/**
* Parse arguments, configure MQTT, and publish messages.
*/
public static void main(String[] args) throws Exception {
// [START iot_mqtt_configuremqtt]
MqttExampleOptions options = MqttExampleOptions.fromFlags(args);
if (options == null) {
// Could not parse.
System.exit(1);
}
// 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", options.mqttBridgeHostname, options.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", options.projectId, options.cloudRegion, options.registryId, options.deviceId);
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");
DateTime iat = new DateTime();
if (options.algorithm.equals("RS256")) {
connectOptions.setPassword(createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
} 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'.");
}
// [END iot_mqtt_configuremqtt]
// [START iot_mqtt_publish]
// 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 (!client.isConnected() && totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) {
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, options.deviceId);
// Publish to the events or state topic based on the flag.
String subTopic = options.messageType.equals("event") ? "events" : options.messageType;
// The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
// required to be in the format below. Note that this is not the same as the device registry's
// Cloud Pub/Sub topic.
String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);
// Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
for (int i = 1; i <= options.numMessages; ++i) {
String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i);
System.out.format("Publishing %s message %d/%d: '%s'\n", options.messageType, i, options.numMessages, payload);
// Refresh the connection credentials before the JWT expires.
// [START iot_mqtt_jwt_refresh]
long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
if (secsSinceRefresh > (options.tokenExpMins * 60)) {
System.out.format("\tRefreshing token after: %d seconds\n", secsSinceRefresh);
iat = new DateTime();
if (options.algorithm.equals("RS256")) {
connectOptions.setPassword(createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
} 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'.");
}
client.disconnect();
client.connect();
attachCallback(client, options.deviceId);
}
// [END iot_mqtt_jwt_refresh]
// Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
// also supports qos=0 for at most once delivery.
MqttMessage message = new MqttMessage(payload.getBytes());
message.setQos(1);
client.publish(mqttTopic, message);
if (options.messageType.equals("event")) {
// Send telemetry events every second
Thread.sleep(1000);
} else {
// Note: Update Device state less frequently than with telemetry events
Thread.sleep(5000);
}
}
// Disconnect the client if still connected, and finish the run.
if (client.isConnected()) {
client.disconnect();
}
System.out.println("Finished loop successfully. Goodbye!");
// [END iot_mqtt_publish]
}
Aggregations