@Test public void checkClientAuthentication() throws Exception { LOG.info("*** checkClientAuthentication ***"); SSLSocketFactory ssf = configureSSLSocketFactory("signedclientkeystore.jks"); MqttConnectOptions options = new MqttConnectOptions(); options.setSocketFactory(ssf); m_client.connect(options); m_client.subscribe("/topic", 0); m_client.disconnect(); }
protected void onStopped() { try { logger.info("Disconnecting client"); mqttClient.disconnect(DISCONNECT_TIMEOUT); } catch(MqttException me) { logger.error("Error disconnecting MQTT client due to {}", new Object[]{me.getMessage()}, me); } try { logger.info("Closing client"); mqttClient.close(); mqttClient = null; } catch (MqttException me) { logger.error("Error closing MQTT client due to {}", new Object[]{me.getMessage()}, me); } }
private void initializeClient(ProcessContext context) { // NOTE: This method is called when isConnected returns false which can happen when the client is null, or when it is // non-null but not connected, so we need to handle each case and only create a new client when it is null try { if (mqttClient == null) { logger.debug("Creating client"); mqttClient = createMqttClient(broker, clientID, persistence); mqttClient.setCallback(this); } if (!mqttClient.isConnected()) { logger.debug("Connecting client"); mqttClient.connect(connOpts); mqttClient.subscribe(topicFilter, qos); } } catch (MqttException e) { logger.error("Connection to {} lost (or was never connected) and connection failed. Yielding processor", new Object[]{broker}, e); context.yield(); } }
@After public void tearDown() throws Exception { if (m_client != null && m_client.isConnected()) { m_client.disconnect(); } if (m_publisher != null && m_publisher.isConnected()) { m_publisher.disconnect(); } stopServer(); }
private void initializeClient(ProcessContext context) { // NOTE: This method is called when isConnected returns false which can happen when the client is null, or when it is // non-null but not connected, so we need to handle each case and only create a new client when it is null try { if (mqttClient == null) { logger.debug("Creating client"); mqttClient = createMqttClient(broker, clientID, persistence); mqttClient.setCallback(this); } if (!mqttClient.isConnected()) { logger.debug("Connecting client"); mqttClient.connect(connOpts); } } catch (MqttException e) { logger.error("Connection to {} lost (or was never connected) and connection failed. Yielding processor", new Object[]{broker}, e); context.yield(); } }
@Test public void testClientDoesntRemainSubscribedAfterASubscriptionAndServerRestart() throws Exception { // subscribe to /topic m_subscriber.connect(); // subscribe /topic m_subscriber.subscribe("/topic", 0); // unsubscribe from /topic m_subscriber.unsubscribe("/topic"); m_subscriber.disconnect(); // shutdown the integration m_server.stopServer(); // restart the integration m_server.startServer(IntegrationUtils.prepareTestProperties()); // subscriber reconnects m_subscriber = new MqttClient("tcp://localhost:1883", "Subscriber", s_dataStore); m_subscriber.setCallback(m_messageCollector); m_subscriber.connect(); // publisher publishes on /topic m_publisher = new MqttClient("tcp://localhost:1883", "Publisher", s_pubDataStore); m_publisher.connect(); m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(UTF_8), 1, false); // Expected // the subscriber doesn't get notified (it's fully unsubscribed) assertNull(m_messageCollector.waitMessage(1)); }
"If no 'url' provided, connectionOptions.getServerURIs() must not be null"); this.client = this.clientFactory.getClientInstance(getUrl(), getClientId()); this.client.setCallback(this); if (this.client instanceof MqttClient) { ((MqttClient) this.client).setTimeToWait(this.completionTimeout); String[] topics = getTopic(); try { this.client.connect(connectionOptions); int[] requestedQos = getQos(); int[] grantedQos = Arrays.copyOf(requestedQos, requestedQos.length); this.client.subscribe(topics, grantedQos); for (int i = 0; i < requestedQos.length; i++) { if (grantedQos[i] != requestedQos[i]) { this.client.disconnectForcibly(this.completionTimeout); try { this.client.setCallback(null); this.client.close(); this.topicLock.unlock(); if (this.client.isConnected()) { this.connected = true; String message = "Connected and subscribed to " + Arrays.toString(topics);
@Test public void checkRestartCleanSubscriptionTree() throws Exception { // subscribe to /topic m_subscriber.connect(CLEAN_SESSION_OPT); m_subscriber.subscribe("/topic", 1); m_subscriber.disconnect(); // shutdown the integration m_server.stopServer(); // restart the integration m_server.startServer(IntegrationUtils.prepareTestProperties()); // reconnect the Subscriber subscribing to the same /topic but different QoS m_subscriber.connect(CLEAN_SESSION_OPT); m_subscriber.subscribe("/topic", 2); // should be just one registration so a publisher receive one notification m_publisher.connect(CLEAN_SESSION_OPT); m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(UTF_8), 1, false); // read the messages MqttMessage msg = m_messageCollector.waitMessage(1); assertEquals("Hello world MQTT!!", new String(msg.getPayload(), UTF_8)); // no more messages on the same topic will be received assertNull(m_messageCollector.waitMessage(1)); }
public void disconnect() { try { if (_listener != null) { _listener.stopReconnect(); } if (_client != null) { if (_client.isConnected()) { _client.disconnect(DISCONNECT_TIME_OUT); } _client.close(); } _config.setStatus(STATE.DOWN, "Stopped."); } catch (Exception ex) { _logger.error("Exception,", ex); } }
_connectOptions.setPassword(_config.getPassword().toCharArray()); _client.connect(_connectOptions); _listener = new MqttListener(_client, _config, _connectOptions, _parser, _queue); _client.setCallback(_listener); _client.subscribe(GatewayUtils.getMqttTopics(_config.getTopicsSubscribe())); _logger.info("MQTT Gateway[name:{}, URI:{}, NetworkType:{}] connected successfully..", _config.getName(), _client.getServerURI(), _config.getNetworkType().getText()); _config.setStatus(STATE.UP, "Connected Successfully"); } catch (MqttException ex) { _logger.error("Unable to connect with MQTT broker _config[{}], Reason Code: {}, " + "Reload _config [Id:{}, Name:{}, NetworkType:{}] service when MQTT Broker comes UP!", _client.getServerURI(), ex.getReasonCode(), _config.getName(), _config.getNetworkType().getText(), ex); } catch (Exception ex) {
while (reconnect) { _logger.debug("Trying to reconnect..."); if (_client.isConnected()) { break; } else { try { _client.connect(_connectOptions); _client.subscribe(GatewayUtils.getMqttTopics(_config.getTopicsSubscribe())); _logger.info("MQTT Gateway[{}] Reconnected successfully...", _client.getServerURI()); _config.setStatus(STATE.UP, "Reconnected successfully..."); if (_client.isConnected()) { break;
@Test public void checkSubscriberQoS0ReceiveQoS1publishes_downgrade() throws Exception { LOG.info("*** checkSubscriberQoS0ReceiveQoS1publishes_downgrade ***"); m_subscriber.subscribe("/topic", 0); m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(UTF_8), 1, false); MqttMessage message = m_callback.waitMessage(1); assertEquals("Hello world MQTT QoS1", message.toString()); assertEquals(0, message.getQos()); }
/** * Connect subscribe to topic and publish on the same topic */ private IMqttClient subscribeAndPublish(String topic) throws Exception { IMqttClient client = new MqttClient("tcp://localhost:1883", "SubPub"); MessageCollector collector = new MessageCollector(); client.setCallback(collector); client.connect(); client.subscribe(topic, 1); client.publish(topic, "Hello world MQTT!!".getBytes(UTF_8), 0, false); MqttMessage msg = collector.waitMessage(1); assertEquals("Hello world MQTT!!", new String(msg.getPayload(), UTF_8)); return client; } }
private void verifyUnsubscribe(IMqttClient client) throws Exception { verify(client).connect(any(MqttConnectOptions.class)); verify(client).subscribe(any(String[].class), any(int[].class)); verify(client).unsubscribe(any(String[].class)); verify(client).disconnectForcibly(anyLong()); }
@Test public void checkDontPublishInactiveClientsAfterServerRestart() throws Exception { IMqttClient conn = subscribeAndPublish("/topic"); conn.disconnect(); // shutdown the integration m_server.stopServer(); // restart the integration m_server.startServer(IntegrationUtils.prepareTestProperties()); m_publisher.connect(); m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(UTF_8), 0, false); }
@Override public Statement apply(Statement base, Description description) { assumeTrue(brokerOnline.get(port)); String url = "tcp://localhost:" + port; IMqttClient client = null; try { client = new DefaultMqttPahoClientFactory().getClientInstance(url, "junit-" + System.currentTimeMillis()); client.connect(); } catch (MqttException e) { logger.warn("Tests not running because no broker on " + url + ":", e); assumeNoException(e); } finally { if (client != null) { try { client.disconnect(); client.close(); } catch (MqttException e) { } } } return super.apply(base, description); }
&& this.cleanSession)) { this.client.unsubscribe(getTopic()); this.client.disconnectForcibly(this.completionTimeout); this.client.setCallback(null); this.client.close();
@Test public void connectWithValidCredentials() throws Exception { LOG.info("*** connectWithCredentials ***"); m_client = new MqttClient("tcp://localhost:1883", "Publisher", s_pubDataStore); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("dbuser"); options.setPassword("password".toCharArray()); m_client.connect(options); assertTrue(true); }
@Before public void setUp() throws Exception { String dbPath = IntegrationUtils.localH2MvStoreDBPath(); File dbFile = new File(dbPath); assertFalse(String.format("The DB storagefile %s already exists", dbPath), dbFile.exists()); startServer(); m_client = new MqttClient("ssl://localhost:8883", "TestClient", s_dataStore); // m_client = new MqttClient("ssl://test.mosquitto.org:8883", "TestClient", s_dataStore); m_callback = new MessageCollector(); m_client.setCallback(m_callback); }
@Before public void setUp() throws Exception { startServer(); m_subscriber = new MqttClient("tcp://localhost:1883", "Subscriber", new MemoryPersistence()); m_callback = new MessageCollector(); m_subscriber.setCallback(m_callback); m_subscriber.connect(); m_publisher = new MqttClient("tcp://localhost:1883", "Publisher", new MemoryPersistence()); m_publisher.connect(); }