String clinetId = "JavaSampleConsumer"; MemoryPersistence persistence = new MemoryPersistence(); MqttClient sampleClient = new MqttClient(broker, clinetId, persistence); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(true); log.info("Connecting to broker: " + broker); sampleClient.connect(connectOptions); log.info("Connected"); sampleClient.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable throwable) { sampleClient.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);
String clientId = "JavaSampleProducer"; MemoryPersistence persistence = new MemoryPersistence(); MqttClient sampleClient = new MqttClient(broker, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); log.info("Connecting to broker: " + broker); sampleClient.connect(connOpts); log.info("Connected"); log.info("Publishing message: " + messageContent); MqttMessage message = new MqttMessage(messageContent.getBytes()); message.setQos(qos); sampleClient.publish(topic, message); log.info("Message published"); sampleClient.disconnect(); log.info("Disconnected"); System.exit(0); } 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);
tmpDir + File.separator + "clientForSubscribe1"); MqttClient clientForSubscribe1 = new MqttClient("tcp://localhost:1883", "clientForSubscribe1", dsSubscriberA); MessageCollector cbSubscriber1 = new MessageCollector(); clientForSubscribe1.setCallback(cbSubscriber1); clientForSubscribe1.connect(); clientForSubscribe1.subscribe("topic", 0); MqttClient clientForSubscribe2 = new MqttClient("tcp://localhost:1883", "clientForSubscribe2", dsSubscriberB); MessageCollector cbSubscriber2 = new MessageCollector(); clientForSubscribe2.setCallback(cbSubscriber2); clientForSubscribe2.connect(); clientForSubscribe2.subscribe("topic", 0); MqttClient clientForPublish = new MqttClient("tcp://localhost:1883", "clientForPublish", dsSubscriberPUB); clientForPublish.connect(); clientForPublish.publish("topic", "Hello".getBytes(UTF_8), 2, true); LOG.info("Before waiting to receive 1 sec from {}", clientForSubscribe1.getClientId()); assertFalse(clientForSubscribe1.isConnected()); assertTrue(clientForSubscribe2.isConnected()); LOG.info("Waiting to receive 1 sec from {}", clientForSubscribe2.getClientId()); MqttMessage messageOnB = cbSubscriber2.waitMessage(1); assertEquals("Hello", new String(messageOnB.getPayload(), UTF_8));
public MQTTPublisher(String address, String clientId, boolean cleanSession, int qos) throws MqttException { this.clientId = clientId; this.qos = qos; this.client = new MqttClient(address, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(cleanSession); this.client.connect(); }
@Override public void onOpen(Emitter emitter) throws IOException { this.emitter = emitter; try { this.mqttClient = new MqttClient(DAO.getConfig("stream.mqtt.address", "tcp://127.0.0.1:1883"), "loklak_server_subscriber"); this.mqttClient.connect(); this.mqttClient.setCallback(this); this.mqttClient.subscribe(this.channel); } catch (MqttException e) { this.emitter.close(); } }
@Override public void onClose() { try { this.mqttClient.close(); this.mqttClient.disconnect(); } catch (MqttException e) { DAO.severe("Error terminating the stream client for API request", e); } }
@Test public void refusedIdentifierRejected(TestContext context) { this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED; 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.fail(); } catch (MqttException e) { context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID); } }
@Override public void connect() throws ConnectionUnavailableException { try { MqttDefaultFilePersistence persistence = new MqttDefaultFilePersistence(); if (clientId.isEmpty()) { clientId = MqttClient.generateClientId(); } client = new MqttClient(brokerURL, clientId, persistence); MqttConnectOptions connectionOptions = new MqttConnectOptions(); connectionOptions.setUserName(userName); connectionOptions.setPassword(userPassword.toCharArray()); connectionOptions.setCleanSession(cleanSession); connectionOptions.setKeepAliveInterval(keepAlive); connectionOptions.setConnectionTimeout(connectionTimeout); client.connect(connectionOptions); } catch (MqttException e) { throw new ConnectionUnavailableException( "Error while connecting with the Mqtt server, Check the broker url = " + brokerURL + " defined in " + streamDefinition, e); } }
private void publish(TestContext context, String topic, String message, int qos) { this.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.publish(topic, message.getBytes(), qos, false); this.async.await(); context.assertTrue(true); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }
@Test public void testSubscribeFailure() throws Exception { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(false); connectOptions.setConnectionTimeout(23); connectOptions.setKeepAliveInterval(45); connectOptions.setPassword("pass".toCharArray()); MemoryPersistence persistence = new MemoryPersistence(); factory.setPersistence(persistence); final SocketFactory socketFactory = SocketFactory.getDefault(); final MqttClient client = mock(MqttClient.class); willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString()); given(client.isConnected()).willReturn(true); new DirectFieldAccessor(client).setPropertyValue("aClient", aClient); willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class)); willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class)); willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any()); assertThat(((MqttException) e.getCause()).getReasonCode(), equalTo((int) MqttException.REASON_CODE_SUBSCRIBE_FAILED));
MQTTManagedConnection(MQTTManagedConnectionFactory aThis, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { cf = aThis; listeners = new HashSet<>(); MqttClientPersistence persistence = new MemoryPersistence(); if (cf.getFilePersistance()) { persistence = new MqttDefaultFilePersistence(cf.getPersistenceDirectory()); String clientId = cf.getClientId(); if (clientId == null) { clientId = MqttClient.generateClientId(); theClient = new MqttClient("tcp://localhost:1883", clientId,persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(cf.getAutomaticReconnect()); options.setCleanSession(cf.getCleanSession()); options.setServerURIs(cf.getServerURIs().split(",")); options.setConnectionTimeout(cf.getConnectionTimeout()); options.setUserName(cf.getUserName()); theClient.connect(options); } catch (MqttException ex) { throw new ResourceException("Unable to build the MQTT Client connection",ex);
public MQTTHandler(NamedIP aConfig) { super(); log.info("Setting up handler for name: " + aConfig.getName()); MemoryPersistence persistence = new MemoryPersistence(); myConfig = aConfig; try { myClient = new MqttClient("tcp://" + myConfig.getIp(), myConfig.getName(), persistence); } catch (MqttException e) { log.error("Could not create MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage()); } MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); connOpts.setAutomaticReconnect(true); if(aConfig.getUsername() != null && aConfig.getUsername().trim().length() > 0) { if(aConfig.getPassword() != null && aConfig.getPassword().trim().length() > 0) { connOpts.setUserName(aConfig.getUsername().trim()); connOpts.setPassword(aConfig.getPassword().trim().toCharArray()); } } try { myClient.connect(connOpts); } catch (MqttException e) { log.error("Could not connect MQTT client for name: " + myConfig.getName() + " and ip: " + myConfig.getIp() + " with message: " + e.getMessage()); } }
public MqttJsonServer(String mqttUrl) throws UnknownHostException, MqttException { mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(), new MemoryPersistence()); mqttClient.setCallback(this); MqttConnectOptions con_opts = new MqttConnectOptions(); con_opts.setAutomaticReconnect(true); con_opts.setCleanSession(true); Logger.debug("Connecting to {}...", mqttUrl); mqttClient.connect(con_opts); Logger.debug("Connected to {}", mqttUrl); }
final MqttClient client = new MqttClient("tcp://" + host + ":" + port, MqttClient.generateClientId(), new MemoryPersistence() ); final MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(login); options.setPassword(password.toCharArray()); client.connect(options); if (client.isConnected()) { client.publish(topic, payload.getBytes(), 0, false); client.disconnect();
@Test @Ignore public void clientTopicListener() throws Exception { MqttClient client = new MqttClient(BROKER_URI, MqttClient.generateClientId(), new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(BROKER_USER); options.setPassword(BROKER_PASSWORD.toCharArray()); client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { String fileName = topicTranslator(topic); writeMessageToFile(fileName, message.getPayload()); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); client.connect(options); client.subscribe(EDC_TOPIC_FILTER, DEFAULT_QOS); Thread.sleep(WAIT_FOR_MESSAGE_MILLIS); }
@Test public void testValidClientIdentifier(TestContext context) throws Exception { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "id-madeof-23-characters", persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setMqttVersion(MQTT_VERSION_3_1); try { client.connect(options); context.assertTrue(true); } catch (MqttException ignore) { context.assertTrue(false); } }
public MqttTestClient(String mqttUrl) throws MqttException { mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence()); mqttClient.setCallback(this); MqttConnectOptions con_opts = new MqttConnectOptions(); con_opts.setAutomaticReconnect(true); con_opts.setCleanSession(true); mqttClient.connect(con_opts); Logger.debug("Connected to {}", mqttUrl); lock = new ReentrantLock(); conditions = new HashMap<>(); responses = new HashMap<>(); // Subscribe Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC); mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC); Logger.debug("Subscribed"); }
@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); }
@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(); } }
@Test public void disconnect(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.disconnect(); context.assertTrue(true); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }