@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; }
@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(); } }
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); } } }