Skip to content

Instantly share code, notes, and snippets.

@natashadsilva
Last active December 13, 2022 23:57
Show Gist options
  • Save natashadsilva/f363d2098b3f473f3041b03a078f6490 to your computer and use it in GitHub Desktop.
Save natashadsilva/f363d2098b3f473f3041b03a078f6490 to your computer and use it in GitHub Desktop.
Connect to MQTT with SSL enabled
# Properties file which configures the operation of the JDK logging facility.
#
# The configuration in this file is the suggesgted configuration
# for collecting trace for helping debug problems related to the
# Paho MQTT client. It configures trace to be continuosly collected
# in memory with minimal impact on performance.
#
# When the push trigger (by default a Severe level message) or a
# specific request is made to "push" the in memory trace then it
# is "pushed" to the configured target handler. By default
# this is the standard java.util.logging.FileHandler. The Paho Debug
# class can be used to push the memory trace to its target
#
# To enable trace either:
# - use this properties file as is and set the logging facility up
# to use it by configuring the util logging system property e.g.
#
# >java -Djava.util.logging.config.file=<location>\jsr47min.properties
#
# - This contents of this file can also be merged with another
# java.util.logging config file to ensure provide wider logging
# and trace including Paho trace
# Global logging properties.
# ------------------------------------------
# The set of handlers to be loaded upon startup.
# Comma-separated list of class names.
# - Root handlers are not enabled by default - just handlers on the Paho packages.
handlers=java.util.logging.MemoryHandler,java.util.logging.FileHandler, java.util.logging.ConsoleHandler
# Default global logging level.
# Loggers and Handlers may override this level
#.level=INFO
# Loggers
# ------------------------------------------
# A memoryhandler is attached to the paho packages
# and the level specified to collected all trace related
# to paho packages. This will override any root/global
# level handlers if set.
org.eclipse.paho.client.mqttv3.handlers=java.util.logging.MemoryHandler
org.eclipse.paho.client.mqttv3.level=ALL
# It is possible to set more granular trace on a per class basis e.g.
org.eclipse.paho.client.mqttv3.internal.wire.MqttConnect.level=ALL
org.eclipse.paho.client.mqttv3.MqttClient.level=ALL
org.eclipse.paho.client.mqttv3.internal.CommsReceiver.level=ALL
org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule=ALL
org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule=ALL
# Handlers
# -----------------------------------------
# Note: the target handler that is associated with the MemoryHandler is not a root handler
# and hence not returned when getting the handlers from root. It appears accessing
# target handler programatically is not possible as target is a private variable in
# class MemoryHandler
java.util.logging.MemoryHandler.level=ALL
java.util.logging.MemoryHandler.size=10000
java.util.logging.MemoryHandler.push=INFO
java.util.logging.MemoryHandler.target=java.util.logging.FileHandler
#java.util.logging.MemoryHandler.target=java.util.logging.ConsoleHandler
# --- FileHandler ---
# Override of global logging level
java.util.logging.FileHandler.level=ALL
# Naming style for the output file:
# (The output file is placed in the directory
# defined by the "user.home" System property.)
# See java.util.logging for more options
java.util.logging.FileHandler.pattern=%h/mqtt-streams-java-trace%u.log
# Limiting size of output file in bytes:
java.util.logging.FileHandler.limit=200000
# Number of output files to cycle through, by appending an
# integer to the base file name:
java.util.logging.FileHandler.count=3
# Style of output (Simple or XML):
java.util.logging.FileHandler.formatter=org.eclipse.paho.client.mqttv3.logging.SimpleLogFormatter
# --- ConsoleHandler ---
# Override of global logging level
#java.util.logging.ConsoleHandler.level=INFO
#java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
#java.util.logging.ConsoleHandler.formatter=org.eclipse.paho.client.mqttv3.logging.SimpleLogFormatter
package demo;
import java.util.Date;
import java.util.Properties;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MQTTRepro {
public static final String SSL_KEY_STORE_PASSWORD = "com.ibm.ssl.keyStorePassword"; //$NON-NLS-1$
public static final String SSL_KEY_STORE = "com.ibm.ssl.keyStore"; //$NON-NLS-1$
public static final String SSL_TRUST_STORE = "com.ibm.ssl.trustStore"; //$NON-NLS-1$
static final String SSK_TRUST_STORE_PASSWORD = "com.ibm.ssl.trustStorePassword"; //$NON-NLS-1$
public static final String SSL_PROTOCOL = "com.ibm.ssl.protocol"; //$NON-NLS-1$
public static final String DEFAULT_SSL_PROTOCOL = "TLSv1.2"; //$NON-NLS-1$
public static boolean messageReceived;
public static Properties setupSslProperties(String trustStore, String trustStorePw,String keyStore, String keyStorePw){
Properties sslProperties = new Properties();
if (trustStore != null || keyStore != null) {
if (trustStore != null) {
sslProperties.setProperty(SSL_TRUST_STORE,
trustStore);
}
if (keyStore != null) {
sslProperties.setProperty(SSL_KEY_STORE,
keyStore);
}
if (keyStorePw != null) {
sslProperties.setProperty(
SSL_KEY_STORE_PASSWORD, keyStorePw);
}
if (trustStorePw != null) {
sslProperties.setProperty(
SSK_TRUST_STORE_PASSWORD, trustStorePw);
}
sslProperties.setProperty(SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL);
}
return sslProperties;
}
public static void setMessageReceived() {
messageReceived = true;
}
public static String getMessage(){
return "Hello from MqttPublishSample" + new Date().toString();
}
public static void main(String[] args) {
//FOR SSL::: Import the server certificate to your JVM's truststore:
//.\keytool -importcert -keystore ..\lib\security\cacerts -storepass <pass. -file "mosquitto.org.crt" -alias "mosquito.org crt"
String topic = "<enter topic>";
String content = getMessage();
int qos = 2; //Set QOS
String broker = "tcp://test.mosquitto.org:1883"; //Change URI
//FOR SSL: String broker = "ssl://test.mosquitto.org:8883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
//Set username and password
String password = null;
String username = null;
////Uncomment this line if you get this exception
/**
* excep MqttException (0) - javax.net.ssl.SSLException: Received fatal alert: protocol_version
*/
//System.setProperty("com.ibm.jsse2.overrideDefaultTLS", "true");
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
String trustStore = null;//
String trustPass = null;//
String keyStore = null;
String keyStorePass = null;
connOpts.setSSLProperties(setupSslProperties(trustStore, trustPass, keyStore, keyStorePass));
if (username != null)
connOpts.setUserName(username);
if (password != null)
connOpts.setPassword(password.toCharArray());
connOpts.setCleanSession(true);
MqttCallback mqttCallback = new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage msg) throws Exception {
System.out.println("Received message :" + new String(msg.getPayload()));
setMessageReceived();
synchronized (this) {
notify();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
///System.out.print("Message delivery complete called, \n\tMessage: " );
// System.out.println(arg0);
}
@Override
public void connectionLost(Throwable arg0) {
System.err.println("Connection lost");
arg0.printStackTrace();
}
};
sampleClient.setCallback(mqttCallback);
String[] topicNames = new String[]{topic};
int[] topicQos = {qos};
System.out.println("Connecting to broker: "+broker);
sampleClient.connect(connOpts);
sampleClient.subscribe(topicNames, topicQos);
System.out.println("Connected");
System.out.println("Publishing message: "+content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println("Message published");
System.out.println("Waiting for message receipt");
if (!messageReceived){
synchronized (mqttCallback) {
mqttCallback.wait(40*300);
}
}
if (!messageReceived){
System.out.println("No message received after 120 seconds");
}
sampleClient.disconnect();
} 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();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment