Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setSocketFactory()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttConnectOptions#setSocketFactory() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MqttService.java From PresencePublisher with MIT License | 6 votes |
public void sendMessages(List<Message> messages) throws MqttException { HyperLog.i(TAG, "Sending " + messages.size() + " messages to server"); boolean tls = sharedPreferences.getBoolean(USE_TLS, false); String clientCertAlias = sharedPreferences.getString(CLIENT_CERTIFICATE, null); String login = sharedPreferences.getString(USERNAME, ""); String password = securePreferences.getString(PASSWORD, ""); MqttClient mqttClient = new MqttClient(getMqttUrl(tls), Settings.Secure.ANDROID_ID, new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); options.setConnectionTimeout(5); if (!login.isEmpty() && !password.isEmpty()) { options.setUserName(login); options.setPassword(password.toCharArray()); } if (tls) { options.setSocketFactory(factory.getSslSocketFactory(clientCertAlias)); } mqttClient.connect(options); for (Message message : messages) { mqttClient.publish(message.getTopic(), message.getContent().getBytes(Charset.forName("UTF-8")), 1, false); } mqttClient.disconnect(5); mqttClient.close(true); HyperLog.i(TAG, "Sending messages was successful"); }
Example 2
Source File: AwsIotMqttConnection.java From aws-iot-device-sdk-java with Apache License 2.0 | 6 votes |
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) { MqttConnectOptions options = new MqttConnectOptions(); options.setSocketFactory(socketFactory); options.setCleanSession(client.isCleanSession()); options.setConnectionTimeout(client.getConnectionTimeout() / 1000); options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000); if(client.isClientEnableMetrics()) { options.setUserName(USERNAME_METRIC_STRING); } Set<String> serverUris = getServerUris(); if (serverUris != null && !serverUris.isEmpty()) { String[] uriArray = new String[serverUris.size()]; serverUris.toArray(uriArray); options.setServerURIs(uriArray); } if (client.getWillMessage() != null) { AWSIotMessage message = client.getWillMessage(); options.setWill(message.getTopic(), message.getPayload(), message.getQos().getValue(), false); } return options; }
Example 3
Source File: DeviceConfig.java From iot-java with Eclipse Public License 1.0 | 6 votes |
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException { MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT); if (getMqttPassword() != null) { connectOptions.setUserName(getMqttUsername()); connectOptions.setPassword(getMqttPassword().toCharArray()); } connectOptions.setCleanSession(this.options.mqtt.cleanStart); connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive); connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES); connectOptions.setAutomaticReconnect(true); if (!Arrays.asList(1883, 80).contains(options.mqtt.port)) { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); connectOptions.setSocketFactory(sslContext.getSocketFactory()); } return connectOptions; }
Example 4
Source File: ApplicationConfig.java From iot-java with Eclipse Public License 1.0 | 6 votes |
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException { MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT); connectOptions.setUserName(getMqttUsername()); connectOptions.setPassword(getMqttPassword().toCharArray()); connectOptions.setCleanSession(this.options.mqtt.cleanStart); connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive); connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES); connectOptions.setAutomaticReconnect(true); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); connectOptions.setSocketFactory(sslContext.getSocketFactory()); return connectOptions; }
Example 5
Source File: MqttServerSslTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
@Test public void connection(TestContext context) { this.async = context.async(); try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("ssl://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_TLS_PORT), "12345", persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setSocketFactory(this.getSocketFactory("/tls/client-truststore-root-ca.jks", null)); client.connect(options); client.publish(MQTT_TOPIC, MQTT_MESSAGE.getBytes(), 0, false); this.async.await(); client.disconnect(); context.assertTrue(true); } catch (MqttException e) { e.printStackTrace(); context.assertTrue(false); } catch (Exception e1) { e1.printStackTrace(); context.assertTrue(false); } }
Example 6
Source File: MqttClientFactory.java From enmasse with Apache License 2.0 | 5 votes |
private static <C> C create(ConnectionFactory<? extends C> factory, BiFunction<C, MqttConnectOptions, C> delegator, Endpoint endpoint, MqttConnectOptions options, String clientId) throws Exception { if (options.getSocketFactory() == null) { SSLContext sslContext = tryGetDefaultSSLContext(); sslContext.init(null, new X509TrustManager[] {new MyX509TrustManager()}, new SecureRandom()); SSLSocketFactory sslSocketFactory = new SNISettingSSLSocketFactory(sslContext.getSocketFactory(), endpoint.getHost()); options.setSocketFactory(sslSocketFactory); } else if (options.getSocketFactory() instanceof SSLSocketFactory) { options.setSocketFactory(new SNISettingSSLSocketFactory((SSLSocketFactory) options.getSocketFactory(), endpoint.getHost())); } if (!TestUtils.resolvable(endpoint)) { endpoint = new Endpoint("localhost", 443); } log.info("Using mqtt endpoint {}", endpoint); final String uriFormat = options.getSocketFactory() instanceof SSLSocketFactory ? TLS_SERVER_URI_TEMPLATE : SERVER_URI_TEMPLATE; String serverURI = String.format(uriFormat, endpoint.getHost(), endpoint.getPort()); return delegator.apply(factory.newInstance(serverURI, clientId, new MemoryPersistence()), options); }
Example 7
Source File: MqttClientCommon.java From datacollector with Apache License 2.0 | 5 votes |
private void configureSslContext(TlsConfigBean conf, MqttConnectOptions connOpts) { try { URI vURI = new URI(commonConf.brokerUrl); if (vURI.getScheme().equals("ssl")) { SSLContext sslContext = conf.getSslContext(); if (sslContext != null) { connOpts.setSocketFactory(sslContext.getSocketFactory()); } } } catch (URISyntaxException e) { throw new IllegalArgumentException(commonConf.brokerUrl); } }
Example 8
Source File: MqttListener.java From micro-integrator with Apache License 2.0 | 4 votes |
public void initAsyncClient() { mqttAsyncClient = confac.getMqttAsyncClient(this.name); MqttClientManager clientManager = MqttClientManager.getInstance(); String inboundIdentifier = clientManager .buildIdentifier(mqttAsyncClient.getClientId(), confac.getServerHost(), confac.getServerPort()); if (!clientManager.hasMqttCallback(inboundIdentifier)) { //registering callback for the first time connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(cleanSession); if (userName != null && password != null) { connectOptions.setUserName(userName); connectOptions.setPassword(password.toCharArray()); } if (socketFactory != null) { connectOptions.setSocketFactory(socketFactory); } mqttAsyncCallback = new MqttAsyncCallback(mqttAsyncClient, injectHandler, confac, connectOptions, mqttProperties); mqttAsyncCallback.setName(params.getName()); connectionConsumer = new MqttConnectionConsumer(connectOptions, mqttAsyncClient, confac, mqttProperties, name); mqttAsyncCallback.setMqttConnectionConsumer(connectionConsumer); mqttAsyncClient.setCallback(mqttAsyncCallback); //here we register the callback handler clientManager.registerMqttCallback(inboundIdentifier, mqttAsyncCallback); } else { //has previously registered callback we just update the reference //in other words has previous un-destroyed callback //this is a manually tenant loading case //should clear the previously set tenant loading flags for the inbound identifier clientManager.unRegisterInboundTenantLoadingFlag(inboundIdentifier); mqttAsyncCallback = clientManager.getMqttCallback(inboundIdentifier); mqttAsyncCallback.setName(params.getName()); connectOptions = mqttAsyncCallback.getMqttConnectionOptions(); connectionConsumer = mqttAsyncCallback.getMqttConnectionConsumer(); //but we need to update injectHandler due to recreation of synapse environment mqttAsyncCallback.updateInjectHandler(injectHandler); } }
Example 9
Source File: SparkplugRaspberryPiExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
/** * Establish an MQTT Session with Sparkplug defined Death Certificate. It may not be * Immediately intuitive that the Death Certificate is created prior to publishing the * Birth Certificate, but the Death Certificate is actually part of the MQTT Session * establishment. For complete details of the actual MQTT wire protocol refer to the * latest OASyS MQTT V3.1.1 standards at: * http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html * * @return true = MQTT Session Established */ public boolean establishMqttSession() { try { // // Setup the MQTT connection parameters using the Paho MQTT Client. // MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Autoreconnect enable options.setAutomaticReconnect(true); // MQTT session parameters Clean Start = true options.setCleanSession(true); // Session connection attempt timeout period in seconds options.setConnectionTimeout(10); // MQTT session parameter Keep Alive Period in Seconds options.setKeepAliveInterval(30); // MQTT Client Username options.setUserName(username); // MQTT Client Password options.setPassword(password.toCharArray()); // // Build up the Death Certificate MQTT Payload. Note that the Death // Certificate payload sequence number // is not tied to the normal message sequence numbers. // SparkplugBPayload payload = new SparkplugBPayloadBuilder(getNextSeqNum()) .setTimestamp(new Date()) .addMetric(new MetricBuilder("bdSeq", MetricDataType.Int64, bdSeq) .createMetric()) .createPayload(); byte[] bytes = new SparkplugBPayloadEncoder().getBytes(payload); // // Setup the Death Certificate Topic/Payload into the MQTT session // parameters // options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, bytes, 0, false); // // Create a new Paho MQTT Client // client = new MqttClient(serverUrl, clientId); // // Using the parameters set above, try to connect to the define MQTT // server now. // System.out.println("Trying to establish an MQTT Session to the MQTT Server @ :" + serverUrl); client.connect(options); System.out.println("MQTT Session Established"); client.setCallback(this); // // With a successful MQTT Session in place, now issue subscriptions // for the EoN Node and Device "Command" Topics of 'NCMD' and 'DCMD' // defined in Sparkplug // client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); } catch (Exception e) { System.out.println("Error Establishing an MQTT Session:"); e.printStackTrace(); return false; } return true; }
Example 10
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
public void run() { try { // Random generator and thread pool for outgoing published messages executor = Executors.newFixedThreadPool(1); // Build up DEATH payload - note DEATH payloads don't have a regular sequence number SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = addBdSeqNum(deathPayload); byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Connect to the MQTT Server options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(2000); client.setCallback(this); // short timeout on failure to connect client.connect(options); // Subscribe to control/command messages for both the edge of network node and the attached devices client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/#", 0); // Loop forever publishing data every PUBLISH_PERIOD while (true) { Thread.sleep(PUBLISH_PERIOD); if (client.isConnected()) { synchronized(seqLock) { System.out.println("Connected - publishing new data"); // Create the payload and add some metrics SparkplugBPayload payload = new SparkplugBPayload( new Date(), newMetrics(false), getSeqNum(), newUUID(), null); client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, new SparkplugBPayloadEncoder().getBytes(payload), 0, false); } } else { System.out.println("Not connected - not publishing data"); } } } catch(Exception e) { e.printStackTrace(); } }
Example 11
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
public void run() { try { // Random generator and thread pool for outgoing published messages executor = Executors.newFixedThreadPool(1); // Build up DEATH payload - note DEATH payloads don't have a regular sequence number SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = addBdSeqNum(deathPayload); byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Connect to the MQTT Server options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(30000); client.setCallback(this); // short timeout on failure to connect client.connect(options); // Subscribe to control/command messages for both the edge of network node and the attached devices client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); List<Metric> nodeMetrics = new ArrayList<Metric>(); List<Metric> deviceMetrics = new ArrayList<Metric>(); // Loop forever publishing data every PUBLISH_PERIOD while (true) { Thread.sleep(PUBLISH_PERIOD); synchronized(seqLock) { if (client.isConnected()) { System.out.println("Time: " + calendar.getTimeInMillis() + " Index: " + index); // Add a 'real time' metric nodeMetrics.add(new MetricBuilder("MyNodeMetric", Int32, index) .timestamp(calendar.getTime()) .createMetric()); // Add a 'real time' metric deviceMetrics.add(new MetricBuilder("MyDeviceMetric", Int32, index+50) .timestamp(calendar.getTime()) .createMetric()); // Publish, increment the calendar and index and reset calendar.add(Calendar.MILLISECOND, 1); if (index == 50) { index = 0; System.out.println("nodeMetrics: " + nodeMetrics.size()); System.out.println("deviceMetrics: " + deviceMetrics.size()); SparkplugBPayload nodePayload = new SparkplugBPayload( new Date(), nodeMetrics, getSeqNum(), null, null); client.publish(NAMESPACE + "/" + groupId + "/NDATA/" + edgeNode, new SparkplugBPayloadEncoder().getBytes(nodePayload), 0, false); SparkplugBPayload devicePayload = new SparkplugBPayload( new Date(), deviceMetrics, getSeqNum(), null, null); client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, new SparkplugBPayloadEncoder().getBytes(devicePayload), 0, false); nodeMetrics = new ArrayList<Metric>(); deviceMetrics = new ArrayList<Metric>(); } else { index++; } } else { System.out.println("Not connected - not publishing data"); } } } } catch(Exception e) { e.printStackTrace(); } }
Example 12
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
public void run() { try { // Random generator and thread pool for outgoing published messages executor = Executors.newFixedThreadPool(1); // Build up DEATH payload - note DEATH payloads don't have a regular sequence number SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = addBdSeqNum(deathPayload); byte[] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Connect to the MQTT Server options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(2000); client.setCallback(this); // short timeout on failure to connect client.connect(options); // Subscribe to control/command messages for both the edge of network node and the attached devices client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); // Loop forever publishing data every PUBLISH_PERIOD while (true) { Thread.sleep(PUBLISH_PERIOD); if (client.isConnected()) { synchronized (seqLock) { System.out.println("Connected - publishing new data"); // Create the payload and add some metrics SparkplugBPayload payload = new SparkplugBPayload(new Date(), newComplexTemplateInstance(), getSeqNum(), newUUID(), null); client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, new SparkplugBPayloadEncoder().getBytes(payload), 0, false); } } else { System.out.println("Not connected - not publishing data"); } } } catch (Exception e) { e.printStackTrace(); } }