private void doConnect() { L.info( "Connecting to MQTT broker " + mqttc.getServerURI() + " with CLIENTID=" + mqttc.getClientId() + " and TOPIC PREFIX=" + topicPrefix); MqttConnectOptions copts = new MqttConnectOptions(); copts.setWill(topicPrefix + "connected", "0".getBytes(), 1, true); copts.setCleanSession(true); copts.setUserName("emonpi"); copts.setPassword("emonpimqtt2016".toCharArray()); try { mqttc.connect(copts); sendConnectionState(); L.info("Successfully connected to broker, subscribing to " + topicPrefix + "(set|get)/#"); try { mqttc.subscribe(topicPrefix + "set/#", 1); mqttc.subscribe(topicPrefix + "get/#", 1); shouldBeConnected = true; } catch (MqttException mqe) { L.log(Level.WARNING, "Error subscribing to topic hierarchy, check your configuration", mqe); throw mqe; } } catch (MqttException mqe) { L.log( Level.WARNING, "Error while connecting to MQTT broker, will retry: " + mqe.getMessage(), mqe); queueConnect(); // Attempt reconnect } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mapView.addLayer( new ArcGISTiledMapServiceLayer( "http://cache1.arcgisonline.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer")); layer = new GraphicsLayer(); mapView.addLayer(layer); mapView.getLocationDisplayManager().start(); mapView.getLocationDisplayManager().setLocationListener(this); try { client = new MqttAndroidClient( this, "tcp://broker.mqttdashboard.com:1883", "Likaci/MqttMap/" + id); client.setCallback(this); MqttConnectOptions options = new MqttConnectOptions(); options.setKeepAliveInterval(10); options.setConnectionTimeout(1000); options.setCleanSession(false); client.connect(options, null, this); } catch (Exception e) { e.printStackTrace(); } }
@Override public MqttConnectOptions getConnectionOptions() { MqttConnectOptions options = new MqttConnectOptions(); if (this.cleanSession != null) { options.setCleanSession(this.cleanSession); } if (this.connectionTimeout != null) { options.setConnectionTimeout(this.connectionTimeout); } if (this.keepAliveInterval != null) { options.setKeepAliveInterval(this.keepAliveInterval); } if (this.password != null) { options.setPassword(this.password.toCharArray()); } if (this.socketFactory != null) { options.setSocketFactory(this.socketFactory); } if (this.sslProperties != null) { options.setSSLProperties(this.sslProperties); } if (this.userName != null) { options.setUserName(this.userName); } if (this.will != null) { options.setWill( this.will.getTopic(), this.will.getPayload(), this.will.getQos(), this.will.isRetained()); } if (this.serverURIs != null) { options.setServerURIs(this.serverURIs); } return options; }
public static void main(String[] args) { // The quality of service for the sent message. int qualityOfService = 1; // Memory persistence for client message deliver. Store it in a file in case // lose connections to the broker. MqttClientPersistence persistence = new MqttDefaultFilePersistence(); try { Properties credentials = new Properties(); credentials.load(new FileInputStream(new File("/Users/keith/mqtt.properties"))); MqttClient client = new MqttClient( "ssl://smartspaces.io:8883", "/mqtt/publisher/credentialed/ssl", persistence); client.setCallback( new MqttCallback() { @Override public void connectionLost(Throwable cause) { System.out.println("Lost connection"); cause.printStackTrace(); } @Override public void deliveryComplete(IMqttDeliveryToken token) { System.out.println("Got delivery token " + token.getResponse()); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // Not needed since not subscribing. } }); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(credentials.getProperty("mqtt.username")); options.setPassword(credentials.getProperty("mqtt.password").toCharArray()); options.setSocketFactory(configureSSLSocketFactory(credentials)); System.out.println("Connecting to broker: " + client.getServerURI()); client.connect(options); System.out.println("Connected"); byte[] content = "Hello, world!".getBytes(); MqttMessage message = new MqttMessage(content); message.setQos(qualityOfService); client.publish("/greeting", message); System.out.println("Message published"); client.disconnect(); System.out.println("Disconnected"); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { String topic = "/group/1ffb66a0-304e-11e5-a2cb-0800200c9a66/send_data"; String contentStr = "Message from KC"; int qos = 2; String broker = "tcp://isplanet.dyndns-office.com:1883"; String clientId = "JavaSample"; MemoryPersistence persistence = new MemoryPersistence(); Content content = new Content(); content.setDevID("80:C1:6E:F3:E7:6B"); content.setDevName("KC"); content.setGroupID("1ffb66a0-304e-11e5-a2cb-0800200c9a66"); content.setSendTimestamp(String.valueOf(System.currentTimeMillis())); Shot shot = new Shot(); shot.setMessage("Test"); shot.setImageUrl("http://ab.unayung.cc/uploads/photo/file/000/000/030/LN07_005.jpg"); shot.setPosition(new GeoPoint(25.042299, 121.507695)); content.setShot(shot); contentStr = JsonDataFactory.getJson(content); // System.exit(0); try { MqttClient sampleClient = new MqttClient(broker, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); System.out.println("Connecting to broker: " + broker); sampleClient.connect(connOpts); System.out.println("Connected"); System.out.println("Publishing message: " + contentStr); MqttMessage message = new MqttMessage(contentStr.getBytes()); message.setQos(qos); sampleClient.publish(topic, message); System.out.println("Message published"); sampleClient.disconnect(); System.out.println("Disconnected"); System.exit(0); } catch (MqttException me) { System.out.println("reason " + me.getReasonCode()); System.out.println("msg " + me.getMessage()); System.out.println("loc " + me.getLocalizedMessage()); System.out.println("cause " + me.getCause()); System.out.println("excep " + me); me.printStackTrace(); } }
private void initMQTT() { getLogger().info("Init MQTT"); try { MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); this.mqttClient = new MqttClient("tcp://elab.kr:1883", String.valueOf(this.getServiceId()), persistence); this.mqttClient.setCallback(this.mqttCallback); this.mqttClient.connect(connOpts); } catch (MqttException e) { getLogger().fatal("Not Connected MQTT broker", e); } }
public MQTTAdaptorListener( MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String topic, String mqttClientId, InputEventAdaptorListener inputEventAdaptorListener, int tenantId) { this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.mqttClientId = mqttClientId; this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); this.keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); this.topic = topic; this.eventAdaptorListener = inputEventAdaptorListener; this.tenantId = tenantId; // SORTING 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); connectionOptions.setKeepAliveInterval(keepAlive); if (this.mqttBrokerConnectionConfiguration.getBrokerPassword() != null) { connectionOptions.setPassword( this.mqttBrokerConnectionConfiguration.getBrokerPassword().toCharArray()); } if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null) { connectionOptions.setUserName(this.mqttBrokerConnectionConfiguration.getBrokerUsername()); } // Construct an MQTT blocking mode client mqttClient = new MqttClient( this.mqttBrokerConnectionConfiguration.getBrokerUrl(), this.mqttClientId, dataStore); // Set this wrapper as the callback handler mqttClient.setCallback(this); } catch (MqttException e) { log.error("Exception occurred while subscribing to MQTT broker" + e); throw new InputEventAdaptorEventProcessingException(e); } catch (Throwable e) { log.error("Exception occurred while subscribing to MQTT broker" + e); throw new InputEventAdaptorEventProcessingException(e); } }
private void createClient() { Log.d(TAG, "Creating client"); client = new MqttAndroidClient(context, serverURI, clientId); client.setCallback(this); client.setTraceCallback(this); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); try { client.connect(options); } catch (MqttException e) { e.printStackTrace(); } // MqttMessage message = new MqttMessage(); // message.setQos(qos); // message.setPayload(new String("Bjorn").getBytes()); // client.publish("message); }
/** * 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); } }
public MQTTAdapterPublisher( MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String topic, String mqttClientId) { this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.mqttClientId = mqttClientId; this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); this.keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); this.topic = topic; // SORTING messages until the server fetches them String temp_directory = System.getProperty(MQTTEventAdapterConstants.ADAPTER_TEMP_DIRECTORY_NAME); 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); connectionOptions.setKeepAliveInterval(keepAlive); if (this.mqttBrokerConnectionConfiguration.getBrokerPassword() != null) { connectionOptions.setPassword( this.mqttBrokerConnectionConfiguration.getBrokerPassword().toCharArray()); } if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null) { connectionOptions.setUserName(this.mqttBrokerConnectionConfiguration.getBrokerUsername()); } // Construct an MQTT blocking mode client mqttClient = new MqttClient( this.mqttBrokerConnectionConfiguration.getBrokerUrl(), this.mqttClientId, dataStore); mqttClient.connect(connectionOptions); } catch (MqttException e) { log.error( "Error occurred when constructing MQTT client for broker url : " + mqttBrokerConnectionConfiguration.getBrokerUrl()); handleException(e); } }
void connectAndSub() { String methodName = Utility.getMethodName(); try { mqttClient = clientFactory.createMqttClient(serverURI, ClientId); mqttV3Receiver = new MqttV3Receiver(mqttClient, LoggingUtilities.getPrintStream()); mqttV3Receiver.setReportConnectionLoss(false); mqttClient.setCallback(mqttV3Receiver); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setCleanSession(false); mqttConnectOptions.setWill("WillTopic", "payload".getBytes(), 2, true); log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + ClientId); mqttClient.connect(mqttConnectOptions); log.info("Subscribing to..." + FirstSubTopicString); mqttClient.subscribe(FirstSubTopicString, 2); } catch (Exception exception) { log.log(Level.SEVERE, "caugh exception:" + exception); setState(FirstClientState.ERROR); Assert.fail("Failed ConnectAndSub exception=" + exception); } }
public void initializeAndConnect(Context ctx, int qos, InitCallback callback) { connectCallback = callback; context = ctx; qualityOfService = qos; deviceId = "ad" + Secure.getString(ctx.getContentResolver(), Secure.ANDROID_ID); opts = new MqttConnectOptions(); opts.setCleanSession(true); User curUser = ClearBlade.getCurrentUser(); if (curUser.getAuthToken() == null) { Log.i(DEBUG_TAG, "Auth token is null, cannot start messaging service"); return; } else { Log.i(DEBUG_TAG, "Received Authenticated user details"); opts.setUserName(curUser.getAuthToken()); opts.setPassword(Util.getSystemKey().toCharArray()); } connect(ctx, callback); }
public void doDemo() { try { client = new MqttClient("tcp://115.28.225.5:1883", "pahomqttpublish1"); client.connect(); MqttMessage message = new MqttMessage(); message.setPayload("A single message".getBytes()); client.publish("pahodemo", message); client.disconnect(); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); // client = new MqttClient("tcp://115.28.225.5:1883", "pahomqtt2"); // client.setCallback(new MqttCallback() { // // public void messageArrived(String topic, MqttMessage msg) throws Exception { // System.out.println("get topic : " + topic + " , msg: " + msg); // } // // public void deliveryComplete(IMqttDeliveryToken arg0) { // // TODO Auto-generated method stub // // } // // public void connectionLost(Throwable arg0) { // // TODO Auto-generated method stub // // } // }); // client.connect(options); // client.subscribe(new String[]{"pahodemo"}); // Thread.sleep(3000); // client.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
private MqttConnectOptions getConnectOptions( String userName, String password, Boolean clearSession, Integer connectionTimeout, String lwtTopic, String lwtMessage, Integer lwtQos, Boolean lwtRetained) { MqttConnectOptions connectOpts = new MqttConnectOptions(); if (!StringUtility.isNullOrEmpty(userName)) { connectOpts.setUserName(userName); if (!StringUtility.isNullOrEmpty(password)) { connectOpts.setPassword(password.toCharArray()); } } if (clearSession != null) { connectOpts.setCleanSession(clearSession); } if (connectionTimeout != null) { connectOpts.setConnectionTimeout(connectionTimeout); } if (!StringUtility.isNullOrEmpty(lwtTopic) && !StringUtility.isNullOrEmpty(lwtMessage)) { connectOpts.setWill( lwtTopic, lwtMessage.getBytes(), NumberUtility.nvl(lwtQos, 1), BooleanUtility.nvl(lwtRetained, false)); } return connectOpts; }
public boolean connect(Properties props) { brokerUrl = props.getProperty("brokerurl", null); if (brokerUrl == null) { throw new RuntimeException("Could not find parameter brokerur"); } Random rnd = new Random(); clientId = props.getProperty( "clientid", System.getenv("mqtt.clientid") != null ? System.getenv("mqtt.clientid") : "mqtt.loadgen." + rnd.nextInt(100000)); if (clientId == null || clientId.length() == 0) { try { clientId = NetworkInterface.getNetworkInterfaces().hasMoreElements() ? NetworkInterface.getNetworkInterfaces() .nextElement() .getInetAddresses() .nextElement() .getHostName() : "noop"; } catch (Exception ex) { LOG.log(Level.SEVERE, "Could not retrieve hostname", ex); } } // 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 File tmpDir = createTempDir(); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir.getAbsolutePath()); LOG.log( Level.INFO, "Using directory {0} for temporary message storage", tmpDir.getAbsolutePath()); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(Boolean.parseBoolean(props.getProperty("cleansession", "true"))); conOpt.setConnectionTimeout(Integer.parseInt(props.getProperty("connectiontimeout", "100"))); conOpt.setKeepAliveInterval(Integer.parseInt(props.getProperty("keepaliveinterval", "100"))); conOpt.setSocketFactory( SslUtil.getSocketFactory( props.getProperty("cafile"), props.getProperty("cert"), props.getProperty("privkey"), props.getProperty("password", "dummy"))); // Construct an MQTT blocking mode client client = new MqttClient(this.brokerUrl, clientId, dataStore); // Wait max 10sec for a blocking call client.setTimeToWait(10000); // Set this wrapper as the callback handler client.setCallback(this); // Connect to the MQTT server LOG.log( Level.INFO, "Connecting to {0} with client ID {1}", new Object[] {brokerUrl, client.getClientId()}); client.connect(conOpt); LOG.info("Connected"); connected = true; return connected; } catch (MqttException e) { LOG.log(Level.WARNING, "Unable to set up client: " + e.toString(), e); } catch (Exception ex) { LOG.log(Level.SEVERE, "Could not create connection: " + ex.getLocalizedMessage(), ex); } return false; }
/** * Process data from the connect action * * @param data the {@link Bundle} returned by the {@link NewConnection} Acitivty */ private void connectAction(Bundle data) { MqttConnectOptions conOpt = new MqttConnectOptions(); /* * Mutal Auth connections could do something like this * * * SSLContext context = SSLContext.getDefault(); * context.init({new CustomX509KeyManager()},null,null); //where CustomX509KeyManager proxies calls to keychain api * SSLSocketFactory factory = context.getSSLSocketFactory(); * * MqttConnectOptions options = new MqttConnectOptions(); * options.setSocketFactory(factory); * * client.connect(options); * */ // public Properties getSSLSettings() { // final Properties properties = new Properties(); // properties.setProperty("com.ibm.ssl.keyStore", // "C:/BKSKeystore/mqttclientkeystore.keystore"); // properties.setProperty("com.ibm.ssl.keyStoreType", "BKS"); // properties.setProperty("com.ibm.ssl.keyStorePassword", "passphrase"); // properties.setProperty("com.ibm.ssl.trustStore", // "C:/BKSKeystore/mqttclienttrust.keystore"); // properties.setProperty("com.ibm.ssl.trustStoreType", "BKS"); // properties.setProperty("com.ibm.ssl.trustStorePassword", "passphrase "); // // return properties; // } try { SSLContext context; KeyStore ts = KeyStore.getInstance("BKS"); ts.load(getResources().openRawResource(R.raw.test), "123456".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(ts); TrustManager[] tm = tmf.getTrustManagers(); context = SSLContext.getInstance("TLS"); context.init(null, tm, null); // SocketFactory factory= SSLSocketFactory.getDefault(); // Socket socket =factory.createSocket("localhost", 10000); SocketFactory factory = context.getSocketFactory(); conOpt.setSocketFactory(factory); } catch (Exception e) { // TODO: handle exception } // The basic client information String server = (String) data.get(ActivityConstants.server); String clientId = (String) data.get(ActivityConstants.clientId); int port = Integer.parseInt((String) data.get(ActivityConstants.port)); boolean cleanSession = (Boolean) data.get(ActivityConstants.cleanSession); boolean ssl = (Boolean) data.get(ActivityConstants.ssl); String uri = null; if (ssl) { Log.e("SSLConnection", "Doing an SSL Connect"); uri = "ssl://"; } else { uri = "tcp://"; } uri = uri + server + ":" + port; MqttClientAndroidService client; client = Connections.getInstance(this).createClient(this, uri, clientId); // create a client handle String clientHandle = uri + clientId; // last will message String message = (String) data.get(ActivityConstants.message); String topic = (String) data.get(ActivityConstants.topic); Integer qos = (Integer) data.get(ActivityConstants.qos); Boolean retained = (Boolean) data.get(ActivityConstants.retained); // connection options String username = (String) data.get(ActivityConstants.username); String password = (String) data.get(ActivityConstants.password); int timeout = (Integer) data.get(ActivityConstants.timeout); int keepalive = (Integer) data.get(ActivityConstants.keepalive); Connection connection = new Connection(clientHandle, clientId, server, port, this, client, ssl); arrayAdapter.add(connection); connection.registerChangeListener(changeListener); // connect client String[] actionArgs = new String[1]; actionArgs[0] = clientId; connection.changeConnectionStatus(ConnectionStatus.CONNECTING); conOpt.setCleanSession(cleanSession); conOpt.setConnectionTimeout(timeout); conOpt.setKeepAliveInterval(keepalive); if (!username.equals(ActivityConstants.empty)) { conOpt.setUserName(username); } if (!password.equals(ActivityConstants.empty)) { conOpt.setPassword(password.toCharArray()); } final ActionListener callback = new ActionListener(this, ActionListener.Action.CONNECT, clientHandle, actionArgs); boolean doConnect = true; if ((!message.equals(ActivityConstants.empty)) || (!topic.equals(ActivityConstants.empty))) { // need to make a message since last will is set try { conOpt.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue()); } catch (Exception e) { doConnect = false; callback.onFailure(null, e); } } client.setCallback(new MqttCallbackHandler(this, clientHandle)); connection.addConnectionOptions(conOpt); Connections.getInstance(this).addConnection(connection); if (doConnect) { try { client.connect(conOpt, null, callback); } catch (MqttException e) { Log.e(this.getClass().getCanonicalName(), "MqttException Occured", e); } } }
public MQTTAdapterListener( MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String topic, String mqttClientId, InputEventAdapterListener inputEventAdapterListener, int tenantId) { if (mqttClientId == null || mqttClientId.trim().isEmpty()) { mqttClientId = MqttClient.generateClientId(); } this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); int keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); this.topic = topic; this.eventAdapterListener = inputEventAdapterListener; this.tenantId = tenantId; // SORTING messages until the server fetches them String temp_directory = System.getProperty("java.io.tmpdir"); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(temp_directory); try { connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); connectionOptions.setKeepAliveInterval(keepAlive); // Construct an MQTT blocking mode client mqttClient = new MqttClient( this.mqttBrokerConnectionConfiguration.getBrokerUrl(), mqttClientId, dataStore); // Set this wrapper as the callback handler mqttClient.setCallback(this); String contentValidatorClassName = this.mqttBrokerConnectionConfiguration.getContentValidatorClassName(); if (contentValidatorClassName != null && contentValidatorClassName.equals(MQTTEventAdapterConstants.DEFAULT)) { contentValidator = new DefaultContentValidator(); } else if (contentValidatorClassName != null && !contentValidatorClassName.isEmpty()) { try { Class<? extends ContentValidator> contentValidatorClass = Class.forName(contentValidatorClassName).asSubclass(ContentValidator.class); contentValidator = contentValidatorClass.newInstance(); } catch (ClassNotFoundException e) { throw new MQTTContentInitializationException( "Unable to find the class validator: " + contentValidatorClassName, e); } catch (InstantiationException e) { throw new MQTTContentInitializationException( "Unable to create an instance of :" + contentValidatorClassName, e); } catch (IllegalAccessException e) { throw new MQTTContentInitializationException("Access of the instance in not allowed.", e); } } String contentTransformerClassName = this.mqttBrokerConnectionConfiguration.getContentTransformerClassName(); if (contentTransformerClassName != null && contentTransformerClassName.equals(MQTTEventAdapterConstants.DEFAULT)) { contentTransformer = new DefaultContentTransformer(); } else if (contentTransformerClassName != null && !contentTransformerClassName.isEmpty()) { try { Class<? extends ContentTransformer> contentTransformerClass = Class.forName(contentTransformerClassName).asSubclass(ContentTransformer.class); contentTransformer = contentTransformerClass.newInstance(); } catch (ClassNotFoundException e) { throw new MQTTContentInitializationException( "Unable to find the class transfoer: " + contentTransformerClassName, e); } catch (InstantiationException e) { throw new MQTTContentInitializationException( "Unable to create an instance of :" + contentTransformerClassName, e); } catch (IllegalAccessException e) { throw new MQTTContentInitializationException("Access of the instance in not allowed.", e); } } } catch (MqttException e) { log.error( "Exception occurred while subscribing to MQTT broker at " + mqttBrokerConnectionConfiguration.getBrokerUrl()); throw new InputEventAdapterRuntimeException(e); } }
/** * Test that a client actively doing work can be taken over * * @throws Exception */ @Test public void testLiveTakeOver() throws Exception { String methodName = Utility.getMethodName(); LoggingUtilities.banner(log, cclass, methodName); log.entering(className, methodName); IMqttClient mqttClient = null; try { FirstClient firstClient = new FirstClient(); Thread firstClientThread = new Thread(firstClient); log.info("Starting the firstClient thread"); firstClientThread.start(); log.info("firstClientThread Started"); firstClient.waitForState(FirstClientState.READY); log.fine("telling the 1st client to go and let it publish for 2 seconds"); // Tell the first client to go and let it publish for a couple of seconds firstClient.setState(FirstClientState.RUNNING); Thread.sleep(2000); log.fine("Client has been run for 2 seconds, now taking over connection"); // Now lets take over the connection // Create a second MQTT client connection with the same clientid. The // server should spot this and kick the first client connection off. // To do this from the same box the 2nd client needs to use either // a different form of persistent store or a different locaiton for // the store to the first client. // MqttClientPersistence persist = new MemoryPersistence(); mqttClient = clientFactory.createMqttClient(serverURI, ClientId, null); MqttV3Receiver mqttV3Receiver = new MqttV3Receiver(mqttClient, LoggingUtilities.getPrintStream()); mqttClient.setCallback(mqttV3Receiver); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setCleanSession(false); mqttConnectOptions.setWill("WillTopic", "payload".getBytes(), 2, true); log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + ClientId); mqttClient.connect(mqttConnectOptions); // We should have taken over the first Client's subscription...we may have some // of his publishes arrive. // NOTE: as a different persistence is used for the second client any inflight // publications from the client will not be recovered / restarted. This will // leave debris on the server. log.fine( "We should have taken over the first Client's subscription...we may have some of his publishes arrive."); // Ignore his publishes that arrive... ReceivedMessage oldMsg; do { oldMsg = mqttV3Receiver.receiveNext(1000); } while (oldMsg != null); log.fine("Now check we have grabbed his subscription by publishing.."); // Now check we have grabbed his subscription by publishing.. byte[] payload = ("Message payload from second client " + getClass().getName() + "." + methodName) .getBytes(); MqttTopic mqttTopic = mqttClient.getTopic(FirstSubTopicString); log.info("Publishing to..." + FirstSubTopicString); mqttTopic.publish(payload, 1, false); log.info("Publish sent, checking for receipt..."); boolean ok = mqttV3Receiver.validateReceipt(FirstSubTopicString, 1, payload); if (!ok) { throw new Exception("Receive failed"); } } catch (Exception exception) { log.throwing(className, methodName, exception); throw exception; } finally { try { mqttClient.disconnect(); log.info("Disconnecting..."); mqttClient.close(); log.info("Close..."); } catch (Exception exception) { log.throwing(className, methodName, exception); throw exception; } } log.exiting(className, methodName); }