mqtt.setWillTopic(willTestamentTopic); m_publisher = mqtt.blockingConnection(); m_publisher.connect(); m_mqtt.setClientId("Subscriber"); m_subscriber = m_mqtt.blockingConnection(); m_subscriber.connect(); Topic[] topics = new Topic[]{new Topic(willTestamentTopic, QoS.AT_MOST_ONCE)}; m_subscriber.subscribe(topics); m_publisher.kill(); Message msg = m_subscriber.receive(1, TimeUnit.SECONDS); // wait the flush interval (1 sec) assertNotNull("We should get notified with 'Will' message", msg); msg.ack();
@Override public void run() { try { LOG.info("Shutting down MQTT client..."); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } });
/** * Publishes topics on connection. * @throws Exception if an exception during publishing occurs */ public static void publish() throws Exception { String topic = "/users/tgoetz/office/1234"; Random rand = new Random(); LOG.info("Publishing to topic {}", topic); LOG.info("Cntrl+C to exit."); while (true) { int temp = rand.nextInt(TEMPERATURE_MAX); int hum = rand.nextInt(HUMIDITY_MAX); String payload = temp + "/" + hum; connection.publish(topic, payload.getBytes(), QoS.AT_LEAST_ONCE, false); Thread.sleep(WAIT_MILLIS_DEFAULT); } }
@Override public void run() { this.running = true; MQTT mqtt = new MQTT(); try { mqtt.setHost(broker); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); Topic[] topics = {new Topic(topic, QoS.AT_LEAST_ONCE)}; byte[] qoses = connection.subscribe(topics); while(running && ((maxElementsToReceive == -1) || (this.messageCount <= maxElementsToReceive))) { Message message = connection.receive(); byte[] payload = message.getPayload(); consumer.onEvent(payload); message.ack(); this.messageCount++; } connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
@Test(timeout = 60 * 1000) public void testRepeatedLinkStealing() throws Exception { final String clientId = "duplicateClient"; final AtomicReference<BlockingConnection> oldConnection = new AtomicReference<>(); final String TOPICA = "TopicA"; for (int i = 1; i <= 10; ++i) { LOG.info("Creating MQTT Connection {}", i); MQTT mqtt = createMQTTConnection(clientId, false); mqtt.setKeepAlive((short) 2); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); connection.publish(TOPICA, TOPICA.getBytes(), QoS.EXACTLY_ONCE, true); assertTrue("Client connect failed for attempt: " + i, Wait.waitFor(() -> connection.isConnected(), 3000, 200)); if (oldConnection.get() != null) { assertTrue("Old client still connected on attempt: " + i, Wait.waitFor(() -> !oldConnection.get().isConnected(), 3000, 200)); } oldConnection.set(connection); } oldConnection.get().publish(TOPICA, TOPICA.getBytes(), QoS.EXACTLY_ONCE, true); oldConnection.get().disconnect(); }
@Test(timeout = 60 * 1000) public void testPingKeepsInactivityMonitorAlive() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("foo"); mqtt.setKeepAlive((short) 2); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); assertTrue("KeepAlive didn't work properly", Wait.waitFor(() -> connection.isConnected())); connection.disconnect(); }
@Test(timeout = 60 * 1000) public void testClientConnectionFailure() throws Exception { MQTT mqtt = createMQTTConnection("reconnect", false); mqtt.setKeepAlive((short) 1); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); Wait.waitFor(() -> connection.isConnected()); final String TOPIC = "TopicA"; final byte[] qos = connection.subscribe(new Topic[]{new Topic(TOPIC, QoS.EXACTLY_ONCE)}); assertEquals(QoS.EXACTLY_ONCE.ordinal(), qos[0]); connection.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false); // kill transport connection.kill(); // FIXME Wait for the previous connection to timeout. This is not required in ActiveMQ. Needs investigating. Thread.sleep(10000); final BlockingConnection newConnection = mqtt.blockingConnection(); newConnection.connect(); Wait.waitFor(() -> newConnection.isConnected()); assertEquals(QoS.EXACTLY_ONCE.ordinal(), qos[0]); Message msg = newConnection.receive(1000, TimeUnit.MILLISECONDS); assertNotNull(msg); assertEquals(TOPIC, new String(msg.getPayload())); msg.ack(); newConnection.disconnect(); }
mqtt.setKeepAlive((short) 2); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); connection.publish("test/foo", "hello world".getBytes(), QoS.AT_LEAST_ONCE, false); connection.disconnect();
@Test(timeout = 60 * 1000) public void testReuseConnection() throws Exception { MQTT mqtt = createMQTTConnection(); mqtt.setClientId("Test-Client"); { BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); connection.disconnect(); Thread.sleep(1000); } { BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); connection.disconnect(); Thread.sleep(1000); } }
private void initializeConnection() throws Exception { connection = client.blockingConnection(); connection.connect(); if (!topicMap.isEmpty()) { Topic[] topics = new Topic[topicMap.size()]; int i = 0; for (Map.Entry<String, QoS> entry : topicMap.entrySet()) { topics[i++] = new Topic(entry.getKey(), entry.getValue()); } connection.subscribe(topics); } }
public void connectMqtt(String clientId) throws Exception { MQTT client = MqttUtils.configureClient(this.options, clientId, this.keyStoreLoader); this.connection = client.blockingConnection(); this.connection.connect(); } }
@Test(timeout = 60 * 1000) public void testBrokerRestartAfterSubHashWithConfigurationQueues() throws Exception { // Add some pre configured queues CoreQueueConfiguration coreQueueConfiguration = new CoreQueueConfiguration(); coreQueueConfiguration.setName("DLQ"); coreQueueConfiguration.setRoutingType(RoutingType.ANYCAST); coreQueueConfiguration.setAddress("DLA"); CoreAddressConfiguration coreAddressConfiguration = new CoreAddressConfiguration(); coreAddressConfiguration.setName("DLA"); coreAddressConfiguration.addRoutingType(RoutingType.ANYCAST); coreAddressConfiguration.addQueueConfiguration(coreQueueConfiguration); getServer().getConfiguration().getAddressConfigurations().add(coreAddressConfiguration); getServer().stop(); getServer().start(); getServer().waitForActivation(10, TimeUnit.SECONDS); for (int i = 0; i < 2; i++) { MQTT mqtt = createMQTTConnection("myClient", false); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); connection.subscribe(new Topic[]{new Topic("#", QoS.AT_MOST_ONCE)}); connection.disconnect(); getServer().stop(); getServer().start(); getServer().waitForActivation(10, TimeUnit.SECONDS); } }
@Override public Serializable doSend(Message message, MeasurementUnit measurementUnit) throws Exception { String response = null; mqttConnection.publish(topicName, message.getPayload().toString().getBytes(Utils.getDefaultEncoding()), QoS.valueOf(qos.toUpperCase()), false); if (isResponseExpected) { mqttResponse = mqttResponseConnection.receive(); if (mqttResponse != null) { response = new String(mqttResponse.getPayload(), Utils.getDefaultEncoding()); } } return response; }
@Override public void run() { try { int i = 0; Topic[] topics = new Topic[sendingData.size()]; for (String key : sendingData.keySet()) { topics[i++] = new Topic(key, QoS.AT_MOST_ONCE); } connection.subscribe(topics); while (receivedData.size() < sendingData.size()) { Message msg = connection.receive(); receivedData.put(msg.getTopic(), new String(msg.getPayload())); } } catch (Exception ex) { throw new RuntimeException(ex); } }
@Test(timeout = 30 * 1000) public void testDefaultKeepAliveWhenClientSpecifiesZero() throws Exception { stopBroker(); protocolConfig = "transport.defaultKeepAlive=2000"; startBroker(); MQTT mqtt = createMQTTConnection(); mqtt.setClientId("foo"); mqtt.setKeepAlive((short) 0); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); assertTrue("KeepAlive didn't work properly", Wait.waitFor(() -> connection.isConnected())); }
@Override public void run() { while (true) { try { Message msg = connection.receive(); holdingBuffer.add(msg); } catch (Exception ex) { LOG.error("Trouble receiving", ex); } } }
@Override public void subscribe(String topic, int qos) throws Exception { Topic[] topics = {new Topic(utf8(topic), QoS.values()[qos])}; connection.subscribe(topics); }
@Override public void run() { this.running = true; MQTT mqtt = new MQTT(); try { mqtt.setHost(broker); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); Topic[] topics = {new Topic(topic, QoS.AT_LEAST_ONCE)}; byte[] qoses = connection.subscribe(topics); while(running && ((maxElementsToReceive == -1) || (this.messageCount <= maxElementsToReceive))) { Message message = connection.receive(); byte[] payload = message.getPayload(); consumer.onEvent(payload); message.ack(); this.messageCount++; } connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
mqtt.setPassword(PASSWORD); subscribeConnection = mqtt.blockingConnection(); subscribeConnection.connect(); subscribeConnection.subscribe(new Topic[]{outputTopic}); publishConnection.connect(); publishConnection.publish(TOPIC_INPUT, MESSAGE_INPUT.getBytes(), QoS.AT_LEAST_ONCE, false); if (publishConnection != null && publishConnection.isConnected()) { publishConnection.disconnect(); if (subscribeConnection != null && subscribeConnection.isConnected()) { subscribeConnection.disconnect();
@Test(timeout = 30000) public void testConnection() throws Exception { for (String version : Arrays.asList("3.1", "3.1.1")) { BlockingConnection connection = null; try { MQTT mqtt = createMQTTConnection("test-" + version, true); mqtt.setUserName(fullUser); mqtt.setPassword(fullPass); mqtt.setConnectAttemptsMax(1); mqtt.setVersion(version); connection = mqtt.blockingConnection(); connection.connect(); BlockingConnection finalConnection = connection; assertTrue("Should be connected", Wait.waitFor(() -> finalConnection.isConnected(), 5000, 100)); } finally { if (connection != null && connection.isConnected()) connection.disconnect(); } } }