public MqttClientPersistence getPersistence() { if (StringUtils.isEmpty(type) || type.equals("memory")) { log.info("Initializing default memory persistence!"); return new MemoryPersistence(); } else if (type.equals("file")) { if (StringUtils.isEmpty(path)) { log.info("Initializing default file persistence!"); return new MqttDefaultFilePersistence(); } else { log.info("Initializing file persistence using directory: {}", path); return new MqttDefaultFilePersistence(path); } } else { log.error("Unknown persistence option: {}. Only 'memory' and 'file' are supported at the moment!", type); throw new IllegalArgumentException("Unknown persistence option: " + type + "!"); } }
@Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setServerURIs(mqttProperties.getUrl()); factory.setUserName(mqttProperties.getUsername()); factory.setPassword(mqttProperties.getPassword()); factory.setCleanSession(mqttProperties.isCleanSession()); factory.setConnectionTimeout(mqttProperties.getConnectionTimeout()); factory.setKeepAliveInterval(mqttProperties.getKeepAliveInterval()); if (ObjectUtils.nullSafeEquals(mqttProperties.getPersistence(), "file")) { factory.setPersistence(new MqttDefaultFilePersistence(mqttProperties.getPersistenceDirectory())); } else if (ObjectUtils.nullSafeEquals(mqttProperties.getPersistence(), "memory")) { factory.setPersistence(new MemoryPersistence()); } return factory; }
/** * 服务初始化回调函数 */ @Override public void onCreate() { super.onCreate(); /**创建一个Handler*/ mConnHandler = new Handler(); try { /**新建一个本地临时存储数据的目录,该目录存储将要发送到服务器的数据,直到数据被发送到服务器*/ mDataStore = new MqttDefaultFilePersistence(getCacheDir().getAbsolutePath()); } catch(Exception e) { e.printStackTrace(); /**新建一个内存临时存储数据的目录*/ mDataStore = null; mMemStore = new MemoryPersistence(); } /**连接的参数选项*/ mOpts = new MqttConnectOptions(); /**删除以前的Session*/ mOpts.setCleanSession(MQTT_CLEAN_SESSION); // Do not set keep alive interval on mOpts we keep track of it with alarm's /**定时器用来实现心跳*/ mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); /**管理网络连接*/ mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); }
/** * * */ private void connect() throws MqttException { connOpt = new MqttConnectOptions(); connOpt.setCleanSession(true); connOpt.setKeepAliveInterval(3600); connOpt.setConnectionTimeout(3600); connOpt.setUserName(sharedPref.getString("pref_username", "")); connOpt.setPassword(sharedPref.getString("pref_password", "").toCharArray()); String tmpDir = createTempDir().getPath(); //System.getProperty("java.io.tmpdir"); Log.i(TAG, "Persistence will be done in " + tmpDir); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); // Connect to Broker mClient = new MqttClient(sharedPref.getString("pref_url", "") + ":" + sharedPref.getString("pref_port", "1883"), android_id + "_client", dataStore); mClient.setCallback(this); mClient.connect(connOpt); Log.i(TAG, "Connected to " + sharedPref.getString("pref_url", "")); }
/** * Generate a MQTT client with given parameters * * @param brokerURL url of MQTT provider * @param userName username to connect to MQTT provider * @param password password to connect to MQTT provider * @param clientId unique id for the publisher/subscriber client * @throws MqttException in case of issue of connect/publish/consume */ public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException { this.brokerURL = brokerURL; //Store messages until server fetches them MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId); mqttClient = new MqttClient(brokerURL, clientId, dataStore); SimpleMQTTCallback callback = new SimpleMQTTCallback(); mqttClient.setCallback(callback); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(userName); connectOptions.setPassword(password); connectOptions.setCleanSession(true); mqttClient.connect(connectOptions); log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL); }
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; }
private static void startClientsTesting() throws MqttException, InterruptedException { String host = "localhost"; int numToSend = 10; int messagesPerSecond = 10000; String dialog_id = "test1"; String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); MqttAsyncClient pub = new MqttAsyncClient("tcp://" + host + ":1883", "PublisherClient" + dialog_id, dataStore); MqttDefaultFilePersistence dataStoreSub = new MqttDefaultFilePersistence(tmpDir); MqttAsyncClient sub = new MqttAsyncClient("tcp://" + host + ":1883", "SubscriberClient" + dialog_id, dataStoreSub); BenchmarkSubscriber suscriberBench = new BenchmarkSubscriber(sub, dialog_id); suscriberBench.connect(); BenchmarkPublisher publisherBench = new BenchmarkPublisher(pub, numToSend, messagesPerSecond, dialog_id); publisherBench.connect(); publisherBench.firePublishes(); suscriberBench.waitFinish(); publisherBench.waitFinish(); System.out.println("Started clients (sub/pub) for testing"); }
private boolean doConnectBroker() { try { LOG.debug("{} > connect..", url); final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setUserName("admin"); mqttConnectOptions.setPassword("admin".toCharArray()); mqttConnectOptions.setCleanSession(true); mqttConnectOptions.setWill(pubTopic2Mqtt, "Bye, bye Baby!".getBytes(), 0, false); // client final String tmpDir = System.getProperty("java.io.tmpdir"); final MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); LOG.info("creating MqttAsyncClient for {} and {}", url, clientId); mqttAsyncClient = new MqttAsyncClient(url, clientId, dataStore); // callback mqttAsyncClient.setCallback(this); // connect mqttAsyncClient.connect(mqttConnectOptions).waitForCompletion(); // subscriptions for (final String subTopic : subTopics) { LOG.info("client {} subscribing to {}", clientId, subTopic); mqttAsyncClient.subscribe(subTopic, 0); } LOG.info("{} > mqtt connection established for {}.", url, clientId); return true; } catch (final Throwable throwable) { LOG.error("{} > connection failed. ({})", url, throwable.getMessage()); close(); return false; } }
protected MqttClientPersistence resolvePersistence() { if (persistence == PahoPersistence.MEMORY) { return new MemoryPersistence(); } else { if (filePersistenceDirectory != null) { return new MqttDefaultFilePersistence(filePersistenceDirectory); } else { return new MqttDefaultFilePersistence(); } } }
/** * Initializes an object that can be used for sending messages to the broker * which is running on localhost. */ public MoquetteProxyContext() { try { this.dataStore = new MqttDefaultFilePersistence(); this.client = new MqttAsyncClient(getFullMqttBrokerUrl(), MQTT_CLIENT_NAME, dataStore); } catch (MqttException e) { // The exception is thrown when there is an unrecognized MQTT Message in the persistant // storage location. Messages are removed from persistant storage once the broker // sends the message to subscribers (does not wait for confirmation) throw new IllegalStateException("Unrecognized message in the persistent data store location." + " Consider clearing the default persistent storage location."); } }
/** * Initializes an object that can be used for sending messages to the broker * which is running on localhost. * * @param persistenceDir the location of the persistent storage used by the MQTT client library. */ public MoquetteProxyContext(String persistenceDir) { try { dataStore = new MqttDefaultFilePersistence(checkNotNull(persistenceDir)); client = new MqttAsyncClient(getFullMqttBrokerUrl(), MQTT_CLIENT_NAME, dataStore); } catch (MqttException e) { // The exception is thrown when there is an unrecognized MQTT Message in the persistant // storage location. Messages are removed from persistant storage once the broker // sends the message to subscribers (does not wait for confirmation) throw new IllegalStateException("Unrecognized message in the persistent data store location." + " Consider clearing the default persistent storage location."); } }
@Override protected synchronized void doStart() throws FlumeException { if (client == null) { try { new File(journalDir).mkdirs(); client = new MqttClient(providerUrl, getName(), new MqttDefaultFilePersistence(journalDir)); if (LOG.isInfoEnabled()) { LOG.info("MQTT client created with [" + providerUrl + "/" + destinationName + "]"); } } catch (Exception e) { throw new FlumeException("MQTT client create failed with [" + providerUrl + "/" + destinationName + "]", e); } } }
@Override public void start(boolean asyncMode) throws IOException, MqttException { publishService = Executors.newSingleThreadExecutor(); //This sample stores in a temporary directory... where messages temporarily // stored until the message has been delivered to the server. //..a real application ought to store them somewhere // where they are not likely to get deleted or tampered with String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); // Construct the connection options object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if (password != null) { conOpt.setPassword(this.password.toCharArray()); } if (userName != null) { conOpt.setUserName(this.userName); } // Construct an MQTT blocking mode client if(clientID == null) { InetAddress addr = InetAddress.getLocalHost(); clientID = "Parser-" + addr.getHostAddress(); } client = new MqttClient(this.brokerURL, clientID, dataStore); // Set this wrapper as the callback handler client.setCallback(this); }
/** * Constructs an instance of the sample client wrapper * * @param brokerUrl * the url of the server to connect to * @param clientId * the client id to connect with * @param cleanSession * clear state at end of connection or not (durable or non-durable * subscriptions) * @param quietMode * whether debug should be printed to standard out * @param userName * the username to connect with * @param password * the password for the user * @throws MqttException if an error happens */ public Sample(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException { this.brokerUrl = brokerUrl; this.quietMode = quietMode; this.clean = cleanSession; this.password = password; this.userName = userName; // This sample stores in a temporary directory... where messages temporarily // stored until the message has been delivered to the server. // ..a real application ought to store them somewhere // where they are not likely to get deleted or tampered with String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); try { // Construct the connection options object that contains connection // parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if (password != null) { conOpt.setPassword(this.password.toCharArray()); } if (userName != null) { conOpt.setUserName(this.userName); } // Construct an MQTT blocking mode client client = new MqttClient(this.brokerUrl, clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); } catch (MqttException e) { e.printStackTrace(); log("Unable to set up client: " + e.toString()); System.exit(1); } }
public MqttClient build() { MqttClient client; try { if (memoryPersistence) { client = new MqttClient(uri, clientUID, new MemoryPersistence()); } else { client = new MqttClient(uri, clientUID, new MqttDefaultFilePersistence()); } } catch (MqttException e) { e.printStackTrace(); client = null; } return client; }
/** * Constructs an instance of the sample client wrapper * * @param brokerUrl the url to connect to * @param clientId the client id to connect with * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions) * @param userName the username to connect with * @param password the password for the user */ public Chii2MQTTClient(String brokerUrl, String clientId, boolean cleanSession, String userName, String password) { this.brokerUrl = brokerUrl; this.clean = cleanSession; this.userName = userName; this.password = password; // Persistence Directory String dir = System.getProperty("user.dir") + File.separator + "data" + File.separator + "mqtt" + File.separator + "client"; MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(dir); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if (password != null) { conOpt.setPassword(this.password.toCharArray()); } if (userName != null) { conOpt.setUserName(this.userName); } // Construct a non-blocking MQTT client instance client = new MqttAsyncClient(this.brokerUrl, clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); } catch (MqttException e) { logger.error("Error when create MQTT client: {}", ExceptionUtils.getMessage(e)); } }
/** * subscriber A connect and subscribe on "a/b" QoS 1 subscriber B connect and subscribe on "a/+" * BUT with QoS 2 publisher connects and send a message "hello" on "a/b" subscriber A must * receive a notification with QoS1 subscriber B must receive a notification with QoS2 */ @Test public void checkSubscribersGetCorrectQosNotifications() throws Exception { LOG.info("*** checkSubscribersGetCorrectQosNotifications ***"); String tmpDir = System.getProperty("java.io.tmpdir"); MqttClientPersistence dsSubscriberA = new MqttDefaultFilePersistence(tmpDir + File.separator + "subscriberA"); MqttClient subscriberA = new MqttClient("tcp://localhost:1883", "SubscriberA", dsSubscriberA); MessageCollector cbSubscriberA = new MessageCollector(); subscriberA.setCallback(cbSubscriberA); subscriberA.connect(); subscriberA.subscribe("a/b", 1); MqttClientPersistence dsSubscriberB = new MqttDefaultFilePersistence(tmpDir + File.separator + "subscriberB"); MqttClient subscriberB = new MqttClient("tcp://localhost:1883", "SubscriberB", dsSubscriberB); MessageCollector cbSubscriberB = new MessageCollector(); subscriberB.setCallback(cbSubscriberB); subscriberB.connect(); subscriberB.subscribe("a/+", 2); m_client.connect(); m_client.publish("a/b", "Hello world MQTT!!".getBytes(), 2, false); MqttMessage messageOnA = cbSubscriberA.waitMessage(1); assertEquals("Hello world MQTT!!", new String(messageOnA.getPayload())); assertEquals(1, messageOnA.getQos()); subscriberA.disconnect(); MqttMessage messageOnB = cbSubscriberB.waitMessage(1); assertEquals("Hello world MQTT!!", new String(messageOnB.getPayload())); assertEquals(2, messageOnB.getQos()); subscriberB.disconnect(); }
protected MqttClient createClient(String clientName, String storeSuffix, MessageCollector cb) throws MqttException { String tmpDir = System.getProperty("java.io.tmpdir"); // clientX connect and subscribe to /topic QoS2 MqttClientPersistence dsClient = new MqttDefaultFilePersistence( tmpDir + File.separator + storeSuffix + clientName); MqttClient client = new MqttClient("tcp://localhost:1883", clientName, dsClient); if (cb != null) { client.setCallback(cb); } client.connect(); return client; }
@BeforeClass public static void beforeTests() throws NoSuchAlgorithmException, SQLException, ClassNotFoundException { String tmpDir = System.getProperty("java.io.tmpdir"); s_dataStore = new MqttDefaultFilePersistence(tmpDir); s_pubDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "publisher"); dbAuthenticatorTest = new DBAuthenticatorTest(); dbAuthenticatorTest.setup(); }
@BeforeClass public static void beforeTests() { String tmpDir = System.getProperty("java.io.tmpdir"); s_dataStore = new MqttDefaultFilePersistence(tmpDir); s_pubDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "publisher"); CLEAN_SESSION_OPT.setCleanSession(false); }
public void configure() throws ConfigurationException { if (StringUtils.isEmpty(getClientId())) { throw new ConfigurationException("clientId must be specified"); } if (StringUtils.isEmpty(getBrokerUrl())) { throw new ConfigurationException("brokerUrl must be specified"); } if (StringUtils.isEmpty(getTopic())) { throw new ConfigurationException("topic must be specified"); } if (StringUtils.isEmpty(getPersistenceDirectory())) { throw new ConfigurationException("persistenceDirectory must be specified"); } connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(isCleanSession()); connectOptions.setAutomaticReconnect(isAutomaticReconnect()); connectOptions.setConnectionTimeout(getTimeout()); connectOptions.setKeepAliveInterval(getKeepAliveInterval()); connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_DEFAULT); //Default: 0, V3.1: 3, V3.1.1: 4 if(!StringUtils.isEmpty(getAuthAlias()) || (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword()))) { CredentialFactory credentialFactory = new CredentialFactory(getAuthAlias(), getUsername(), getPassword()); connectOptions.setUserName(credentialFactory.getUsername()); connectOptions.setPassword(credentialFactory.getPassword().toCharArray()); } MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(getPersistenceDirectory()); try { client = new MqttClient(brokerUrl, clientId, dataStore); } catch (MqttException e) { throw new ConfigurationException("Could not create client", e); } }
@CliCommand(value = { "connect" }, help = "Connect to an MQTT Broker") public String connect( @CliOption(key = { "", "host" }, mandatory = false, specifiedDefaultValue = "localhost", unspecifiedDefaultValue = "localhost", help = "Host address") String hostname, @CliOption(key = { "port" }, mandatory = false, specifiedDefaultValue = "1883", unspecifiedDefaultValue = "1883") int port, @CliOption(key = { "ssl" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") boolean ssl, @CliOption(key = { "username" }, mandatory = false, specifiedDefaultValue = "anonymous", unspecifiedDefaultValue = "") String username, @CliOption(key = { "password" }, mandatory = false, specifiedDefaultValue = "", unspecifiedDefaultValue = "") String password, @CliOption(key = { "client-id" }, mandatory = false, specifiedDefaultValue = "mqtt-cli", unspecifiedDefaultValue = "mqtt-cli") String clientId) { try { String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); options = new MqttConnectOptions(); options.setCleanSession(true); if (StringUtils.hasText(username)) { options.setUserName(username); } if (StringUtils.hasText(password)) { options.setPassword(password.toCharArray()); } String scheme = (ssl ? "ssl" : "tcp"); String uri = String.format("%s://%s:%s", scheme, hostname, port); this.client = new MqttClient(uri, clientId, dataStore); client.setCallback(this); client.connect(options); if (client.isConnected()) { multicaster.multicastEvent(new ConnectionEvent(client, true, hostname, username)); } return String.format("%sConnected to %s", (client.isConnected() ? "" : "NOT "), hostname); } catch (MqttException e) { LOG.error("Connection error", e); return e.getMessage(); } }
/** * Constructs an instance of the sample client wrapper * @param brokerUrl the url of the server to connect to * @param clientId the client id to connect with * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions) * @param quietMode whether debug should be printed to standard out * @param userName the username to connect with * @param password the password for the user * @throws MqttException */ public Sample(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException { this.brokerUrl = brokerUrl; this.quietMode = quietMode; this.clean = cleanSession; this.password = password; this.userName = userName; //This sample stores in a temporary directory... where messages temporarily // stored until the message has been delivered to the server. //..a real application ought to store them somewhere // where they are not likely to get deleted or tampered with String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if(password != null ) { conOpt.setPassword(this.password.toCharArray()); } if(userName != null) { conOpt.setUserName(this.userName); } // Construct an MQTT blocking mode client client = new MqttClient(this.brokerUrl,clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); } catch (MqttException e) { e.printStackTrace(); log("Unable to set up client: "+e.toString()); System.exit(1); } }
/** * Constructs an instance of the sample client wrapper * @param brokerUrl the url to connect to * @param clientId the client id to connect with * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions) * @param quietMode whether debug should be printed to standard out * @param userName the username to connect with * @param password the password for the user * @throws MqttException */ public SampleAsyncCallBack(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException { this.brokerUrl = brokerUrl; this.quietMode = quietMode; this.clean = cleanSession; this.password = password; this.userName = userName; //This sample stores in a temporary directory... where messages temporarily // stored until the message has been delivered to the server. //..a real application ought to store them somewhere // where they are not likely to get deleted or tampered with String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); try { // Construct the object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if(password != null ) { conOpt.setPassword(this.password.toCharArray()); } if(userName != null) { conOpt.setUserName(this.userName); } // Construct the MqttClient instance client = new MqttAsyncClient(this.brokerUrl,clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); } catch (MqttException e) { e.printStackTrace(); log("Unable to set up client: "+e.toString()); System.exit(1); } }
/** * Constructs an instance of the sample client wrapper * @param brokerUrl the url to connect to * @param clientId the client id to connect with * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions) * @param quietMode whether debug should be printed to standard out * @param userName the username to connect with * @param password the password for the user * @throws MqttException */ public SampleAsyncWait(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException { this.brokerUrl = brokerUrl; this.quietMode = quietMode; this.clean = cleanSession; this.userName = userName; this.password = password; //This sample stores in a temporary directory... where messages temporarily // stored until the message has been delivered to the server. //..a real application ought to store them somewhere // where they are not likely to get deleted or tampered with String tmpDir = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if(password != null ) { conOpt.setPassword(this.password.toCharArray()); } if(userName != null) { conOpt.setUserName(this.userName); } // Construct a non-blocking MQTT client instance client = new MqttAsyncClient(this.brokerUrl,clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); } catch (MqttException e) { e.printStackTrace(); log("Unable to set up client: "+e.toString()); System.exit(1); } }
@BeforeClass public static void beforeTests() { String tmpDir = System.getProperty("java.io.tmpdir"); s_dataStore = new MqttDefaultFilePersistence(tmpDir); s_pubDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "publisher"); }
@Test public void testSubcriptionDoesntStayActiveAfterARestart() throws Exception { LOG.info("*** testSubcriptionDoesntStayActiveAfterARestart ***"); String tmpDir = System.getProperty("java.io.tmpdir"); // clientForSubscribe1 connect and subscribe to /topic QoS2 MqttClientPersistence dsSubscriberA = new MqttDefaultFilePersistence( 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); // server stop m_server.stopServer(); System.out.println("\n\n SEVER REBOOTING \n\n"); // server start startServer(); // clientForSubscribe2 connect and subscribe to /topic QoS2 MqttClientPersistence dsSubscriberB = new MqttDefaultFilePersistence( tmpDir + File.separator + "clientForSubscribe2"); MqttClient clientForSubscribe2 = new MqttClient("tcp://localhost:1883", "clientForSubscribe2", dsSubscriberB); MessageCollector cbSubscriber2 = new MessageCollector(); clientForSubscribe2.setCallback(cbSubscriber2); clientForSubscribe2.connect(); clientForSubscribe2.subscribe("topic", 0); // clientForPublish publish on /topic with QoS2 a message MqttClientPersistence dsSubscriberPUB = new MqttDefaultFilePersistence( tmpDir + File.separator + "clientForPublish"); MqttClient clientForPublish = new MqttClient("tcp://localhost:1883", "clientForPublish", dsSubscriberPUB); clientForPublish.connect(); clientForPublish.publish("topic", "Hello".getBytes(), 2, true); // verify clientForSubscribe1 doesn't receive a notification but clientForSubscribe2 yes 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())); }
@BeforeClass public static void beforeTests() throws NoSuchAlgorithmException, SQLException, ClassNotFoundException { String tmpDir = System.getProperty("java.io.tmpdir"); s_dataStore = new MqttDefaultFilePersistence(tmpDir); s_pubDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "publisher"); }
@BeforeClass public static void beforeTests() { String tmpDir = System.getProperty("java.io.tmpdir"); s_dataStore = new MqttDefaultFilePersistence(tmpDir); backup = System.getProperty("moquette.path"); }
@BeforeClass public static void beforeTests() { String tmpDir = System.getProperty("java.io.tmpdir"); s_subDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "subscriber"); s_pubDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "publisher"); }
public MQTTClient(MQTTBrokerConnectionConfig mqttBrokerConnectionConfig, String mqttClientId, String topic) { //Initializing the variables locally this.brokerUrl = mqttBrokerConnectionConfig.getBrokerUrl(); this.mqttClientId = mqttClientId; // this.quietMode = quietMode; this.cleanSession = mqttBrokerConnectionConfig.isCleanSession(); this.password = mqttBrokerConnectionConfig.getBrokerPassword(); this.userName = mqttBrokerConnectionConfig.getBrokerUsername(); // this.mqttAaction = action; this.topicName = topic; // this.qos = qos; // this.messagePayLoad = payload; //Sotring messages until the server fetches them String temp_directory = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(temp_directory); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); if (password != null) { connectionOptions.setPassword(this.password.toCharArray()); } if (userName != null) { connectionOptions.setUserName(this.userName); } // Construct an MQTT blocking mode client mqttClient = new MqttClient(this.brokerUrl, mqttClientId, dataStore); // Set this wrapper as the callback handler mqttClient.setCallback(this); // Connect to the MQTT server mqttClient.connect(connectionOptions); mqttClient.subscribe("iot/demo"); } catch (MqttException e) { e.printStackTrace(); } }
public MQTTListener(MQTTBrokerConnectionConfig mqttBrokerConnectionConfig, String mqttClientId, String topic, InputEventAdaptorListener inputEventAdaptorListener) { log.info("creating MQTT Listener " + mqttClientId); //Initializing the variables locally this.brokerUrl = mqttBrokerConnectionConfig.getBrokerUrl(); this.mqttClientId = mqttClientId; // this.quietMode = quietMode; this.cleanSession = mqttBrokerConnectionConfig.isCleanSession(); this.password = mqttBrokerConnectionConfig.getBrokerPassword(); this.userName = mqttBrokerConnectionConfig.getBrokerUsername(); // this.mqttAaction = action; this.topic = topic; // this.qos = qos; // this.messagePayLoad = payload; eventAdaptorListener = inputEventAdaptorListener; //Sotring messages until the server fetches them String temp_directory = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(temp_directory); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); if (password != null) { connectionOptions.setPassword(this.password.toCharArray()); } if (userName != null) { connectionOptions.setUserName(this.userName); } // Construct an MQTT blocking mode client mqttClient = new MqttClient(this.brokerUrl, mqttClientId, dataStore); // Set this wrapper as the callback handler mqttClient.setCallback(this); } catch (MqttException e) { e.printStackTrace(); } }
@BeforeClass public static void beforeTests() { String tmpDir = System.getProperty("java.io.tmpdir"); s_dataStore = new MqttDefaultFilePersistence(tmpDir); }
/** * Create an MqttAsyncClient that is used to communicate with an MQTT server. * <p> * The address of a server can be specified on the constructor. Alternatively * a list containing one or more servers can be specified using the * {@link MqttConnectOptions#setServerURIs(String[]) setServerURIs} method * on MqttConnectOptions. * <p/> * <p>The <code>serverURI</code> parameter is typically used with the * the <code>clientId</code> parameter to form a key. The key * is used to store and reference messages while they are being delivered. * Hence the serverURI specified on the constructor must still be specified even if a list * of servers is specified on an MqttConnectOptions object. * The serverURI on the constructor must remain the same across * restarts of the client for delivery of messages to be maintained from a given * client to a given server or set of servers. * <p/> * <p>The address of the server to connect to is specified as a URI. Two types of * connection are supported <code>tcp://</code> for a TCP connection and * <code>ssl://</code> for a TCP connection secured by SSL/TLS. * For example: * <ul> * <li><code>tcp://localhost:1883</code></li> * <li><code>ssl://localhost:8883</code></li> * </ul> * If the port is not specified, it will * default to 1883 for <code>tcp://</code>" URIs, and 8883 for <code>ssl://</code> URIs. * </p> * <p/> * <p> * A client identifier <code>clientId</code> must be specified and be less that 23 characters. * It must be unique across all clients connecting to the same * server. The clientId is used by the server to store data related to the client, * hence it is important that the clientId remain the same when connecting to a server * if durable subscriptions or reliable messaging are required. * <p>A convenience method is provided to generate a random client id that * should satisfy this criteria - {@link #generateClientId()}. As the client identifier * is used by the server to identify a client when it reconnects, the client must use the * same identifier between connections if durable subscriptions or reliable * delivery of messages is required. * </p> * <p> * In Java SE, SSL can be configured in one of several ways, which the * client will use in the following order: * </p> * <ul> * <li><strong>Supplying an <code>SSLSocketFactory</code></strong> - applications can * use {@link MqttConnectOptions#setSocketFactory(SocketFactory)} to supply * a factory with the appropriate SSL settings.</li> * <li><strong>SSL Properties</strong> - applications can supply SSL settings as a * simple Java Properties using {@link MqttConnectOptions#setSSLProperties(Properties)}.</li> * <li><strong>Use JVM settings</strong> - There are a number of standard * Java system properties that can be used to configure key and trust stores.</li> * </ul> * <p/> * <p>In Java ME, the platform settings are used for SSL connections.</p> * <p/> * <p>An instance of the default persistence mechanism {@link MqttDefaultFilePersistence} * is used by the client. To specify a different persistence mechanism or to turn * off persistence, use the {@link #MqttAsyncClient(String, String, MqttClientPersistence)} * constructor. * * @param serverURI the address of the server to connect to, specified as a URI. Can be overridden using * {@link MqttConnectOptions#setServerURIs(String[])} * @param clientId a client identifier that is unique on the server being connected to * @throws IllegalArgumentException if the URI does not start with * "tcp://", "ssl://" or "local://". * @throws IllegalArgumentException if the clientId is null or is greater than 23 characters in length * @throws MqttException if any other problem was encountered */ public MqttAsyncClient(String serverURI, String clientId) throws MqttException { this(serverURI, clientId, new MqttDefaultFilePersistence()); }
/** * Create an MqttClient that can be used to communicate with an MQTT server. * <p> * The address of a server can be specified on the constructor. Alternatively * a list containing one or more servers can be specified using the * {@link MqttConnectOptions#setServerURIs(String[]) setServerURIs} method * on MqttConnectOptions. * <p/> * <p>The <code>serverURI</code> parameter is typically used with the * the <code>clientId</code> parameter to form a key. The key * is used to store and reference messages while they are being delivered. * Hence the serverURI specified on the constructor must still be specified even if a list * of servers is specified on an MqttConnectOptions object. * The serverURI on the constructor must remain the same across * restarts of the client for delivery of messages to be maintained from a given * client to a given server or set of servers. * <p/> * <p>The address of the server to connect to is specified as a URI. Two types of * connection are supported <code>tcp://</code> for a TCP connection and * <code>ssl://</code> for a TCP connection secured by SSL/TLS. * For example: * <ul> * <li><code>tcp://localhost:1883</code></li> * <li><code>ssl://localhost:8883</code></li> * </ul> * If the port is not specified, it will * default to 1883 for <code>tcp://</code>" URIs, and 8883 for <code>ssl://</code> URIs. * </p> * <p/> * <p> * A client identifier <code>clientId</code> must be specified and be less that 23 characters. * It must be unique across all clients connecting to the same * server. The clientId is used by the server to store data related to the client, * hence it is important that the clientId remain the same when connecting to a server * if durable subscriptions or reliable messaging are required. * <p>A convenience method is provided to generate a random client id that * should satisfy this criteria - {@link #generateClientId()}. As the client identifier * is used by the server to identify a client when it reconnects, the client must use the * same identifier between connections if durable subscriptions or reliable * delivery of messages is required. * </p> * <p> * In Java SE, SSL can be configured in one of several ways, which the * client will use in the following order: * </p> * <ul> * <li><strong>Supplying an <code>SSLSocketFactory</code></strong> - applications can * use {@link MqttConnectOptions#setSocketFactory(SocketFactory)} to supply * a factory with the appropriate SSL settings.</li> * <li><strong>SSL Properties</strong> - applications can supply SSL settings as a * simple Java Properties using {@link MqttConnectOptions#setSSLProperties(Properties)}.</li> * <li><strong>Use JVM settings</strong> - There are a number of standard * Java system properties that can be used to configure key and trust stores.</li> * </ul> * <p/> * <p>In Java ME, the platform settings are used for SSL connections.</p> * <p/> * <p>An instance of the default persistence mechanism {@link MqttDefaultFilePersistence} * is used by the client. To specify a different persistence mechanism or to turn * off persistence, use the {@link #MqttClient(String, String, MqttClientPersistence)} * constructor. * * @param serverURI the address of the server to connect to, specified as a URI. Can be overridden using * {@link MqttConnectOptions#setServerURIs(String[])} * @param clientId a client identifier that is unique on the server being connected to * @throws IllegalArgumentException if the URI does not start with * "tcp://", "ssl://" or "local://". * @throws IllegalArgumentException if the clientId is null or is greater than 23 characters in length * @throws MqttException if any other problem was encountered */ public MqttClient(String serverURI, String clientId) throws MqttException { this(serverURI, clientId, new MqttDefaultFilePersistence()); }
/** * Create an MqttAsyncClient that is used to communicate with an MQTT server. * <p> * The address of a server can be specified on the constructor. Alternatively * a list containing one or more servers can be specified using the * {@link MqttConnectOptions#setServerURIs(String[]) setServerURIs} method * on MqttConnectOptions. * * <p>The <code>serverURI</code> parameter is typically used with the * the <code>clientId</code> parameter to form a key. The key * is used to store and reference messages while they are being delivered. * Hence the serverURI specified on the constructor must still be specified even if a list * of servers is specified on an MqttConnectOptions object. * The serverURI on the constructor must remain the same across * restarts of the client for delivery of messages to be maintained from a given * client to a given server or set of servers. * * <p>The address of the server to connect to is specified as a URI. Two types of * connection are supported <code>tcp://</code> for a TCP connection and * <code>ssl://</code> for a TCP connection secured by SSL/TLS. * For example: * <ul> * <li><code>tcp://localhost:1883</code></li> * <li><code>ssl://localhost:8883</code></li> * </ul> * If the port is not specified, it will * default to 1883 for <code>tcp://</code>" URIs, and 8883 for <code>ssl://</code> URIs. * </p> * * <p> * A client identifier <code>clientId</code> must be specified and be less that 65535 characters. * It must be unique across all clients connecting to the same * server. The clientId is used by the server to store data related to the client, * hence it is important that the clientId remain the same when connecting to a server * if durable subscriptions or reliable messaging are required. * <p>A convenience method is provided to generate a random client id that * should satisfy this criteria - {@link #generateClientId()}. As the client identifier * is used by the server to identify a client when it reconnects, the client must use the * same identifier between connections if durable subscriptions or reliable * delivery of messages is required. * </p> * <p> * In Java SE, SSL can be configured in one of several ways, which the * client will use in the following order: * </p> * <ul> * <li><strong>Supplying an <code>SSLSocketFactory</code></strong> - applications can * use {@link MqttConnectOptions#setSocketFactory(SocketFactory)} to supply * a factory with the appropriate SSL settings.</li> * <li><strong>SSL Properties</strong> - applications can supply SSL settings as a * simple Java Properties using {@link MqttConnectOptions#setSSLProperties(Properties)}.</li> * <li><strong>Use JVM settings</strong> - There are a number of standard * Java system properties that can be used to configure key and trust stores.</li> * </ul> * * <p>In Java ME, the platform settings are used for SSL connections.</p> * * <p>An instance of the default persistence mechanism {@link MqttDefaultFilePersistence} * is used by the client. To specify a different persistence mechanism or to turn * off persistence, use the {@link #MqttAsyncClient(String, String, MqttClientPersistence)} * constructor. * * @param serverURI the address of the server to connect to, specified as a URI. Can be overridden using * {@link MqttConnectOptions#setServerURIs(String[])} * @param clientId a client identifier that is unique on the server being connected to * @throws IllegalArgumentException if the URI does not start with * "tcp://", "ssl://" or "local://". * @throws IllegalArgumentException if the clientId is null or is greater than 65535 characters in length * @throws MqttException if any other problem was encountered */ public MqttAsyncClient(String serverURI, String clientId) throws MqttException { this(serverURI,clientId, new MqttDefaultFilePersistence()); }