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 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 void start() throws MqttException { MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(brokerUser); options.setPassword(brokerPass.toCharArray()); client.connect(options); // PrintOutCallback printOutCallback = new PrintOutCallback(); DatabaseCallback databaseCallback = new DatabaseCallback( databaseIP, databasePort, dataBaseUser, dataBasePass, defultDataBase, client); client.setCallback(databaseCallback); subscribeToTopics(); }
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); } }
public static MqttConnectOptions getOpts() { Properties pro = getOptsPro(); if (null != pro) { String uName = pro.getProperty("u", null); String pwd = pro.getProperty("p", null); String cid = pro.getProperty("c", null); if (!isEmpty(uName) && !isEmpty(pwd) && !isEmpty(cid)) { MqttConnectOptions opts = new MqttConnectOptions(); opts.setKeepAliveInterval(200); opts.setUserName(uName); opts.setPassword(pwd.toCharArray()); return opts; } } return null; }
/** * 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); } }
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); }
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 static void main(String[] args) { MqttClient client = null; MemoryPersistence persistence = new MemoryPersistence(); try { client = new MqttClient("tcp://mqtt.phelicks.net:1883", "PointOfNoReturnService", persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("cab"); options.setPassword("sjuttongubbar".toCharArray()); client.connect(options); } catch (MqttException e) { e.printStackTrace(); } PointOfNoReturnCallback pointOfNoReturnCallback = new PointOfNoReturnCallback(client); client.setCallback(pointOfNoReturnCallback); try { client.subscribe("telemetry/snapshot"); client.subscribe("set/config"); } catch (MqttException e) { e.printStackTrace(); } }
public void startListener() throws MqttException { if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null && this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) { String username = this.mqttBrokerConnectionConfiguration.getBrokerUsername(); String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl(); String scopes = this.mqttBrokerConnectionConfiguration.getBrokerScopes(); // getJWT Client Parameters. if (dcrUrlString != null && !dcrUrlString.isEmpty()) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); try { URL dcrUrl = new URL(dcrUrlString); HttpClient httpClient = MQTTUtil.getHttpClient(dcrUrl.getProtocol()); HttpPost postMethod = new HttpPost(dcrUrlString); RegistrationProfile registrationProfile = new RegistrationProfile(); registrationProfile.setCallbackUrl(MQTTEventAdapterConstants.EMPTY_STRING); registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE); registrationProfile.setOwner(username); registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE); registrationProfile.setApplicationType(MQTTEventAdapterConstants.APPLICATION_TYPE); registrationProfile.setClientName(username + "_" + tenantId); String jsonString = registrationProfile.toJSON(); StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); postMethod.setEntity(requestEntity); HttpResponse httpResponse = httpClient.execute(postMethod); if (httpResponse != null) { String response = MQTTUtil.getResponseString(httpResponse); try { if (response != null) { JSONParser jsonParser = new JSONParser(); JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID); String clientSecret = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_SECRET); JWTClientManagerService jwtClientManagerService = MQTTUtil.getJWTClientManagerService(); AccessTokenInfo accessTokenInfo = jwtClientManagerService .getJWTClient() .getAccessToken(clientId, clientSecret, username, scopes); connectionOptions.setUserName(accessTokenInfo.getAccessToken()); } } catch (ParseException e) { String msg = "error occurred while parsing client credential payload"; log.error(msg, e); } catch (JWTClientException e) { String msg = "error occurred while parsing the response from JWT Client"; log.error(msg, e); } } } catch (MalformedURLException e) { log.error("Invalid dcrUrl : " + dcrUrlString); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) { log.error("Failed to create an https connection.", e); } finally { PrivilegedCarbonContext.endTenantFlow(); } } } mqttClient.connect(connectionOptions); mqttClient.subscribe(topic); }
/** * 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); } } }