diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..06478d3
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+javadocs/* linguist-documentation
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index 71a771b..07fe1c5 100644
--- a/build.gradle
+++ b/build.gradle
@@ -21,6 +21,20 @@ allprojects {
jcenter()
}
+
+ task checkstyle(type: Checkstyle) {
+ showViolations = true
+ configFile file("../checkstyle.xml")
+
+ source 'src/main/java'
+ include '**/*.java'
+ exclude '**/gen/**'
+ exclude '**/R.java'
+ exclude '**/BuildConfig.java'
+
+ // empty classpath
+ classpath = files()
+ }
}
task clean(type: Delete) {
diff --git a/checkstyle.xml b/checkstyle.xml
new file mode 100644
index 0000000..405da4a
--- /dev/null
+++ b/checkstyle.xml
@@ -0,0 +1,260 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ubimqtt/.attach_pid7230 b/ubimqtt/.attach_pid7230
new file mode 100644
index 0000000..e69de29
diff --git a/ubimqtt/build.gradle b/ubimqtt/build.gradle
index 76fe777..7466689 100644
--- a/ubimqtt/build.gradle
+++ b/ubimqtt/build.gradle
@@ -2,6 +2,11 @@ apply plugin: 'java-library'
apply plugin: 'com.github.dcendents.android-maven'
group='com.github.ubikampus'
+apply plugin: 'checkstyle'
+
+assemble.dependsOn('lint')
+check.dependsOn('checkstyle')
+
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// https://mvnrepository.com/artifact/org.bitbucket.b_c/jose4j
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiActionListener.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiActionListener.java
index effc59c..5ef7759 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiActionListener.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiActionListener.java
@@ -2,5 +2,10 @@
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
+/**
+ * Interface to indicate if operation succeeded or not and give the error if it didn't.
+ *
+ * @see org.eclipse.paho.client.mqttv3.IMqttActionListener
+ */
public interface IUbiActionListener extends IMqttActionListener {
}
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiMessageListener.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiMessageListener.java
index defd622..86e2da3 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiMessageListener.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/IUbiMessageListener.java
@@ -2,6 +2,10 @@
import org.eclipse.paho.client.mqttv3.MqttMessage;
+/**
+ * Interface for implementing the actions that are wanted to be taken
+ * after valid messages arrives to the topic that subscription listens with this listener.
+ */
public interface IUbiMessageListener {
void messageArrived(String topic, MqttMessage mqttMessage, String listenerId) throws Exception;
}
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java
index 59b119d..0680532 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java
@@ -33,34 +33,45 @@
import java.security.KeyPair;
import java.security.interfaces.ECPublicKey;
+/**
+ * Static methods to handle signing, verifying, encrypting and decrypting messages using EC public and private keys.
+ * Using implementations of the algorithms provided by com.nimbusds.jose.
+ */
public class JwsHelper {
+ public static boolean verifySignature(String json, ECPublicKey publicKey)
+ throws java.text.ParseException, JOSEException, ParseException {
- public static boolean verifySignature(String json, ECPublicKey publicKey) throws java.text.ParseException, IOException, JOSEException, ParseException {
return verifySignatureCompact(jsonToCompact(json), publicKey);
}
- public static boolean verifySignature(String json, String publicKey) throws java.text.ParseException, IOException, JOSEException, ParseException {
+ public static boolean verifySignature(String json, String publicKey)
+ throws java.text.ParseException, IOException, JOSEException, ParseException {
+
return verifySignatureCompact(jsonToCompact(json), publicKey);
}
public static ECPublicKey createEcPublicKey(String publicKey) throws IOException {
+
PEMParser pemParser = new PEMParser(new StringReader(publicKey));
- SubjectPublicKeyInfo pemPublicKey = (SubjectPublicKeyInfo)pemParser.readObject();
+ SubjectPublicKeyInfo pemPublicKey = (SubjectPublicKeyInfo) pemParser.readObject();
// Convert to Java (JCA) format
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
- ECPublicKey ecPublicKey = (ECPublicKey)converter.getPublicKey(pemPublicKey);
+ ECPublicKey ecPublicKey = (ECPublicKey) converter.getPublicKey(pemPublicKey);
pemParser.close();
return ecPublicKey;
}
- public static boolean verifySignatureCompact(String compact, String publicKey) throws java.text.ParseException, IOException, JOSEException {
+ public static boolean verifySignatureCompact(String compact, String publicKey)
+ throws java.text.ParseException, IOException, JOSEException {
+
return verifySignatureCompact(compact, createEcPublicKey(publicKey));
}
- public static boolean verifySignatureCompact(String compact, ECPublicKey ecPublicKey) throws java.text.ParseException, IOException, JOSEException {
+ public static boolean verifySignatureCompact(String compact, ECPublicKey ecPublicKey)
+ throws java.text.ParseException, JOSEException {
String[] parts = compact.split("\\.");
@@ -74,17 +85,21 @@ public static boolean verifySignatureCompact(String compact, ECPublicKey ecPubli
return jwsObject.verify(verifier);
}
- public static String signMessage( String message, String privateKey) throws JOSEException, ParseException, IOException {
+ public static String signMessage(String message, String privateKey)
+ throws JOSEException, ParseException, IOException {
+
return compactToJson(signMessageToCompact(message, privateKey));
}
- public static String signMessageToCompact( String message, String privateKey) throws JOSEException, IOException {
+ public static String signMessageToCompact(String message, String privateKey)
+ throws JOSEException, IOException {
+
//ECKey jwk = (ECKey) ECKey.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
// Parse the EC key pair
//PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream("ec512-key-pair.pem")));
PEMParser pemParser = new PEMParser(new StringReader(privateKey));
- PEMKeyPair pemKeyPair = (PEMKeyPair)pemParser.readObject();
+ PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
// Convert to Java (JCA) format
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
@@ -92,7 +107,7 @@ public static String signMessageToCompact( String message, String privateKey) th
pemParser.close();
// Get private + public EC key
- ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
+ ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();
//ECPublicKey publicKey = (ECPublicKey)keyPair.getPublic();
@@ -118,17 +133,13 @@ public static String signMessageToCompact( String message, String privateKey) th
return jwsObject.serialize();
}
- public static String compactToJson(String compact) throws ParseException{
+ public static String compactToJson(String compact) throws ParseException {
String[] parts = compact.split("\\.");
String header = new Base64URL(parts[0]).decodeToString();
String payload = new Base64URL(parts[1]).decodeToString();
String signature = parts[2];
- System.out.println("header: " +header);
- System.out.println("payload: " +payload);
- System.out.println("signature: " +signature);
-
JSONObject obj = new JSONObject();
JSONObject signatureObject = new JSONObject();
@@ -148,20 +159,19 @@ public static String compactToJson(String compact) throws ParseException{
return obj.toJSONString();
}
+ public static String jsonToCompact(String json) throws ParseException {
+ JSONParser parser = new JSONParser();
+ JSONObject obj = (JSONObject) parser.parse(json);
- public static String jsonToCompact(String json) throws ParseException {
- JSONParser parser = new JSONParser();
- JSONObject obj = (JSONObject) parser.parse(json);
+ String payload = (String) obj.get("payload");
- String payload = (String)obj.get("payload");
+ JSONArray signaturesArray = (JSONArray) obj.get("signatures");
+ JSONObject signatureObject = (JSONObject) signaturesArray.get(0);
- JSONArray signaturesArray = (JSONArray)obj.get("signatures");
- JSONObject signatureObject = (JSONObject)signaturesArray.get(0);
+ String header = ((JSONObject) signatureObject.get("protected")).toJSONString();
+ String signature = (String) signatureObject.get("signature");
- String header = ((JSONObject)signatureObject.get("protected")).toJSONString();
- String signature = (String)signatureObject.get("signature");
-
- return Base64URL.encode(header)+"."+Base64URL.encode(payload)+"."+signature;
+ return Base64URL.encode(header) + "." + Base64URL.encode(payload) + "." + signature;
}
/**
@@ -214,7 +224,7 @@ public static String encryptMessage(String message, String publicKey) throws IOE
public static String decryptMessage(String message, String privateKey) throws JOSEException, IOException, java.text.ParseException {
// Parse the EC key pair
PEMParser pemParser = new PEMParser(new StringReader(privateKey));
- PEMKeyPair pemKeyPair = (PEMKeyPair)pemParser.readObject();
+ PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
// Convert to Java (JCA) format
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
@@ -222,7 +232,7 @@ public static String decryptMessage(String message, String privateKey) throws JO
pemParser.close();
// Get private EC key
- ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
+ ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();
// Decrypt the JWE with the EC private key
JWEObject jwe = JWEObject.parse(message);
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/MessageValidator.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/MessageValidator.java
index 56cec66..42e4dcf 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/MessageValidator.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/MessageValidator.java
@@ -8,38 +8,42 @@
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
-import java.io.IOException;
import java.security.interfaces.ECPublicKey;
+/**
+ * CLass to validate all the messages so that there is no problems in their syntax.
+ */
public class MessageValidator {
-
private ReplayDetector replayDetector;
public MessageValidator(int bufferWindowInSeconds) {
this.replayDetector = new ReplayDetector(bufferWindowInSeconds);
}
- public boolean validateMessage(String message, ECPublicKey ecPublicKey) throws ParseException, JOSEException, java.text.ParseException, IOException {
+ public boolean validateMessage(String message, ECPublicKey ecPublicKey)
+ throws ParseException, JOSEException, java.text.ParseException {
+
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(message);
- String payload = (String)obj.get("payload");
+ String payload = (String) obj.get("payload");
- JSONArray signaturesArray = (JSONArray)obj.get("signatures");
- JSONObject signatureObject = (JSONObject)signaturesArray.get(0);
- JSONObject headerObj = (JSONObject)signatureObject.get("protected");
+ JSONArray signaturesArray = (JSONArray) obj.get("signatures");
+ JSONObject signatureObject = (JSONObject) signaturesArray.get(0);
+ JSONObject headerObj = (JSONObject) signatureObject.get("protected");
- String signature = (String)signatureObject.get("signature");
+ String signature = (String) signatureObject.get("signature");
- String compact = Base64URL.encode(headerObj.toString())+"."+Base64URL.encode(payload)+"."+signature;
+ String compact = Base64URL.encode(headerObj.toString()) + "." + Base64URL.encode(payload) + "." + signature;
boolean isSignatureCorrect = JwsHelper.verifySignatureCompact(compact, ecPublicKey);
- if (!isSignatureCorrect)
+ if (!isSignatureCorrect) {
return false;
+ }
- long timestamp = (Long)headerObj.get("timestamp");
- String messageId = (String)headerObj.get("messageid");
+ long timestamp = (Long) headerObj.get("timestamp");
+ String messageId = (String) headerObj.get("messageid");
return replayDetector.isValid(timestamp, messageId);
}
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/PublicKeyChangeListener.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/PublicKeyChangeListener.java
index 98b3cf4..a547246 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/PublicKeyChangeListener.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/PublicKeyChangeListener.java
@@ -2,6 +2,9 @@
import org.eclipse.paho.client.mqttv3.MqttMessage;
+/**
+ * Listener for updating public keys during use.
+ */
public class PublicKeyChangeListener implements IUbiMessageListener {
private String mainListenerId;
private IUbiActionListener originalCallback;
@@ -22,8 +25,7 @@ public void messageArrived(String topic, MqttMessage message, String listenerId)
if (mainListenerId != null) {
System.out.println("PublicKeyChangeListener::onPublicKeyChanged() changing public key");
ubiMqtt.updatePublicKey(mainTopic, mainListenerId, message.toString());
- }
- else {
+ } else {
// This is the first time the public key arrives, subscribe to the main topic
String[] publicKeys = {message.toString()};
ubiMqtt.subscribeSigned(mainTopic, publicKeys, mainListener, originalCallback);
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/ReplayDetector.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/ReplayDetector.java
index 3034bc0..fb13798 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/ReplayDetector.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/ReplayDetector.java
@@ -6,20 +6,20 @@
import java.util.SortedMap;
import java.util.TreeMap;
+/**
+ * Detector for noticing if replay has occurred.
+ */
public class ReplayDetector {
-
private SortedMap> buffer;
- private int bufferWindowInSeconds = -1;
+ private int bufferWindowInSeconds;
public ReplayDetector(int bufferWindowInSeconds) {
-
this.buffer = new TreeMap<>();
this.bufferWindowInSeconds = bufferWindowInSeconds;
//addEntry(System.currentTimeMillis(), "");
}
private void addEntry(long timestamp, String messageId) {
-
Map messages;
if (!buffer.containsKey(timestamp)) {
@@ -34,30 +34,31 @@ private void addEntry(long timestamp, String messageId) {
public boolean isValid(long timestamp, String messageId) {
// Reject messages that are older than the bufferWindowInSeconds
-
- if (timestamp< System.currentTimeMillis() - (bufferWindowInSeconds*1000))
+ if (timestamp < System.currentTimeMillis() - (bufferWindowInSeconds * 1000)) {
return false;
+ }
// Reject message If there is an entry with exactly same timestamp and messageId
- if (buffer.containsKey(timestamp) && buffer.get(timestamp).containsKey(messageId))
+ if (buffer.containsKey(timestamp) && buffer.get(timestamp).containsKey(messageId)) {
return false;
+ }
// Remove entries that are older than bufferWindowInSeconds from buffer
-
Iterator iterator = buffer.keySet().iterator();
while (iterator.hasNext()) {
long key = iterator.next();
- if (key < System.currentTimeMillis() - (bufferWindowInSeconds*1000))
+
+ if (key < System.currentTimeMillis() - (bufferWindowInSeconds * 1000)) {
iterator.remove();
- else
+ } else {
break;
+ }
}
- // Message is accptable, add it to the buffer
+ // Message is acceptable, add it to the buffer
addEntry(timestamp, messageId);
return true;
}
-
}
diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/Subscription.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/Subscription.java
index 30e2880..43bc189 100644
--- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/Subscription.java
+++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/Subscription.java
@@ -3,6 +3,10 @@
import java.io.IOException;
import java.security.interfaces.ECPublicKey;
+/**
+ * Wrapper for the event when client subscribes to a topic
+ * and starts to listen all the messages in that topic.
+ */
public class Subscription {
private String topic;
private IUbiMessageListener listener;
@@ -17,7 +21,7 @@ public Subscription(String topic, IUbiMessageListener listener, String[] publicK
if (publicKeys != null) {
this.ecPublicKeys = new ECPublicKey[publicKeys.length];
- for (int i=0; i> subscriptions;
private Vector publicKeyChangeListeners;
- private ArrayList> getSubscriptionsForTopic(String topic) {
- ArrayList > ret = new ArrayList >();
-
- Iterator>> iter = subscriptions.entrySet().iterator();
-
- while (iter.hasNext()) {
- Map.Entry> entry = iter.next();
+ private ArrayList> getSubscriptionsForTopic(String topic) {
+ ArrayList> ret = new ArrayList<>();
+ for (Map.Entry> entry : subscriptions.entrySet()) {
if (MqttTopic.isMatched(entry.getKey(), topic)) {
- Iterator> subscriptionIterator = entry.getValue().entrySet().iterator();
- while (subscriptionIterator.hasNext()) {
- ret.add(subscriptionIterator.next());
- }
+ ret.addAll(entry.getValue().entrySet());
}
}
+
return ret;
}
private IMqttMessageListener messageListener = new IMqttMessageListener() {
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
-
ArrayList> subscriptionsForTopic = getSubscriptionsForTopic(topic);
- Iterator> iterator = subscriptionsForTopic.iterator();
-
- while (iterator.hasNext()) {
- Map.Entry next = iterator.next();
-
+ for (Map.Entry next : subscriptionsForTopic) {
if (next.getValue().getEcPublicKeys() != null) {
// This is a topic where signed messages are expected, try if the signature matches some of the public keys
ECPublicKey[] tempKeys = next.getValue().getEcPublicKeys();
- for (int i=0; i< tempKeys.length; i++) {
- if (messageValidator.validateMessage(mqttMessage.toString(), tempKeys[i])) {
+
+ for (ECPublicKey tempKey : tempKeys) {
+ if (messageValidator.validateMessage(mqttMessage.toString(), tempKey)) {
next.getValue().getListener().messageArrived(topic, mqttMessage, next.getKey());
break;
}
}
- }
- else {
+ } else {
if (next.getValue().getDecryptPrivateKey() != null) {
for (String privateKey : next.getValue().getDecryptPrivateKey()) {
try {
@@ -89,7 +77,7 @@ public void messageArrived(String topic, MqttMessage mqttMessage) throws Excepti
next.getValue().getListener().messageArrived(topic, mqttMessage, next.getKey());
break;
- } catch(RuntimeException ex) {
+ } catch (RuntimeException ex) {
ex.printStackTrace();
}
}
@@ -101,7 +89,7 @@ public void messageArrived(String topic, MqttMessage mqttMessage) throws Excepti
}
};
- protected void updatePublicKey(String topic, String listenerId, String publicKey) throws IOException {
+ void updatePublicKey(String topic, String listenerId, String publicKey) throws IOException {
if (subscriptions.containsKey(topic) && subscriptions.get(topic).containsKey(listenerId)) {
ECPublicKey[] tempKeys = new ECPublicKey[1];
tempKeys[0] = JwsHelper.createEcPublicKey(publicKey);
@@ -111,10 +99,11 @@ protected void updatePublicKey(String topic, String listenerId, String publicKey
private void addSubscription(IUbiActionListener actionListener, String topic, String[] publicKeys, IUbiMessageListener listener) {
try {
- if (!subscriptions.containsKey(topic))
+ if (!subscriptions.containsKey(topic)) {
subscriptions.put(topic, Collections.synchronizedMap(new HashMap<>()));
+ }
- String listenerId = listenerCounter + "";
+ String listenerId = Integer.toString(listenerCounter);
listenerCounter++;
subscriptions.get(topic).put(listenerId, new Subscription(topic, listener, publicKeys));
@@ -126,12 +115,15 @@ private void addSubscription(IUbiActionListener actionListener, String topic, St
}
}
- private void addSubscriptionEncrypted(IUbiActionListener actionListener, String topic, String[] publicKeys, String[] decryptPrivateKey, IUbiMessageListener listener) {
+ private void addSubscriptionEncrypted(IUbiActionListener actionListener, String topic, String[] publicKeys,
+ String[] decryptPrivateKey, IUbiMessageListener listener) {
+
try {
- if (!subscriptions.containsKey(topic))
+ if (!subscriptions.containsKey(topic)) {
subscriptions.put(topic, Collections.synchronizedMap(new HashMap<>()));
+ }
- String listenerId = listenerCounter + "";
+ String listenerId = Integer.toString(listenerCounter);
listenerCounter++;
subscriptions.get(topic).put(listenerId, new Subscription(topic, listener, publicKeys, decryptPrivateKey));
@@ -147,27 +139,18 @@ private String signMessage(String message, String privateKey) throws IOException
return JwsHelper.signMessage(message, privateKey);
}
-
/**
- * Constructs a Ubimqtt instance with default bufferWindowInSeconds but does not connect to a server
+ * Constructs a Ubimqtt instance with default bufferWindowInSeconds but does not connect to a server.
+ *
* @param serverAddress the Mqtt server to use
*/
public UbiMqtt(String serverAddress) {
- this.clientId = UUID.randomUUID().toString();
- this.messageValidator = new MessageValidator(DEFAULT_BUFFER_WINDOW_IN_SECONDS);
-
- this.subscriptions = Collections.synchronizedMap(new HashMap>());
- this.publicKeyChangeListeners = new Vector();
-
- if (serverAddress.startsWith("tcp://"))
- this.serverAddress = serverAddress;
- else
- this.serverAddress = "tcp://" + serverAddress;
-
+ this(serverAddress, DEFAULT_BUFFER_WINDOW_IN_SECONDS);
}
/**
- * Constructs a Ubimqtt instance but does not connect to a server
+ * Constructs a Ubimqtt instance but does not connect to a server.
+ *
* @param serverAddress the Mqtt server to use
* @param bufferWindowInSeconds the maximum acceptable age for signed messages, older signed messages will be discarded
*/
@@ -175,18 +158,19 @@ public UbiMqtt(String serverAddress, int bufferWindowInSeconds) {
this.clientId = UUID.randomUUID().toString();
this.messageValidator = new MessageValidator(bufferWindowInSeconds);
- this.subscriptions = Collections.synchronizedMap(new HashMap>());
- this.publicKeyChangeListeners = new Vector();
+ this.subscriptions = Collections.synchronizedMap(new HashMap<>());
+ this.publicKeyChangeListeners = new Vector<>();
- if (serverAddress.startsWith("tcp://"))
+ if (serverAddress.startsWith("tcp://")) {
this.serverAddress = serverAddress;
- else
+ } else {
this.serverAddress = "tcp://" + serverAddress;
-
+ }
}
/**
- * Connecs to the Mqtt server the address of which was given as a constructor parameter
+ * Connecs to the Mqtt server the address of which was given as a constructor parameter.
+ *
* @param actionListener the listener to call upon connection or error
*/
public void connect(IUbiActionListener actionListener) {
@@ -204,7 +188,8 @@ public void connect(IUbiActionListener actionListener) {
}
/**
- * Disconnects from the Mqtt server
+ * Disconnects from the Mqtt server.
+ *
* @param actionListener the callback to call upon successful disconnection or error
*/
public void disconnect(IUbiActionListener actionListener) {
@@ -218,7 +203,8 @@ public void disconnect(IUbiActionListener actionListener) {
}
/**
- * Publishes a message on the connected Mqtt server
+ * Publishes a message on the connected Mqtt server.
+ *
* @param topic the Mqtt topic to publish to
* @param message the message to publish
* @param qos the Mqtt qos to use
@@ -234,18 +220,20 @@ public void publish(String topic, String message, int qos, boolean retained, IUb
}
/**
- * Publishes a message on the connected Mqtt server with default qos=1 and retained = false
+ * Publishes a message on the connected Mqtt server with default qos = 1 and retained = false.
+ *
* @param topic the Mqtt topic to publish to
* @param message the message to publish
* @param actionListener the callback to call upon success or error
*/
- public void publish(String topic, String message,IUbiActionListener actionListener) {
- publish(topic, message, 1,false, actionListener);
+ public void publish(String topic, String message, IUbiActionListener actionListener) {
+ publish(topic, message, 1, false, actionListener);
}
/**
- * Publishes a signed message on the connected Mqtt server
+ * Publishes a signed message on the connected Mqtt server.
+ *
* @param topic the Mqtt topic to publish to
* @param message the message to publish
* @param qos the Mqtt qos to use
@@ -262,14 +250,15 @@ public void publishSigned(String topic, String message, int qos, boolean retaine
}
/**
- * Publishes a signed message on the connected Mqtt server with default qos=1 and retained = false
+ * Publishes a signed message on the connected Mqtt server with default qos = 1 and retained = false.
+ *
* @param topic the Mqtt topic to publish to
* @param message the message to publish
* @param privateKey the private key in .pem format to sign the message with
* @param actionListener the callback to call upon success or error
*/
public void publishSigned(String topic, String message, String privateKey, IUbiActionListener actionListener) {
- publishSigned(topic, message, 1, false, privateKey,actionListener);
+ publishSigned(topic, message, 1, false, privateKey, actionListener);
}
/**
@@ -283,7 +272,9 @@ public void publishSigned(String topic, String message, String privateKey, IUbiA
* @param encryptPublicKey public key for the encryption
* @param actionListener the callback to call upon success or error
*/
- public void publishEncrypted(String topic, String message, int qos, boolean retained, String encryptPublicKey, IUbiActionListener actionListener) {
+ public void publishEncrypted(String topic, String message, int qos, boolean retained,
+ String encryptPublicKey, IUbiActionListener actionListener) {
+
try {
this.client.publish(topic, this.encryptMessage(message, encryptPublicKey).getBytes(), qos, retained, null, actionListener);
} catch (Exception e) {
@@ -292,7 +283,7 @@ public void publishEncrypted(String topic, String message, int qos, boolean reta
}
/**
- * Publishes a message on the connected Mqtt server with default qos=1 and retained = false.
+ * Publishes a message on the connected Mqtt server with default qos = 1 and retained = false.
* Encrypting all the messages which are going to be published.
*
* @param topic the Mqtt topic to publish to
@@ -301,7 +292,7 @@ public void publishEncrypted(String topic, String message, int qos, boolean reta
* @param actionListener the callback to call upon success or error
*/
public void publishEncrypted(String topic, String message, String encryptPublicKey, IUbiActionListener actionListener) {
- publishEncrypted(topic, message, 1,false, encryptPublicKey, actionListener);
+ publishEncrypted(topic, message, 1, false, encryptPublicKey, actionListener);
}
private String encryptMessage(String message, String publicKey) throws IOException, JOSEException {
@@ -309,7 +300,8 @@ private String encryptMessage(String message, String publicKey) throws IOExcepti
}
/**
- * Subscribes to a Mqtt topic on the connected Mqtt server
+ * Subscribes to a Mqtt topic on the connected Mqtt server.
+ *
* @param topic the Mqtt topic to subscribe to
* @param listener the listener function to call whenever a message matching the topic arrives
* @param actionListener the listener to be called upon successful subscription or error
@@ -331,7 +323,8 @@ public void subscribeEncrypted(String topic, String[] decryptPrivateKey, IUbiMes
}
/**
- * Subscribes to messages signed by particular keypairs on a Mqtt topic on the connected Mqtt server
+ * Subscribes to messages signed by particular keypairs on a Mqtt topic on the connected Mqtt server.
+ *
* @param topic the Mqtt topic to subscribe to
* @param publicKeys the public keys the messages are checked against
* @param listener the listener function to call whenever a message matching the topic and signed with one of the publicKeys arrives
@@ -342,9 +335,10 @@ public void subscribeSigned(String topic, String[] publicKeys, IUbiMessageListen
}
/**
- * Subscribes to messages on a Mqtt topic on the connected Mqtt server signed by a known publiser The public key of the publiser
+ * Subscribes to messages on a Mqtt topic on the connected Mqtt server signed by a known publiser The public key of the publisher
* is used for recognizing the messages originating from the publisher. The public key of the publisher is fetched from the Mqtt
- * topic publishers/publishername/publicKey and kept up-to-date with the help of a regular Mqtt subscription
+ * topic publishers/publishername/publicKey and kept up-to-date with the help of a regular Mqtt subscription.
+ *
* @param topic the Mqtt topic to subscribe to
* @param publisherName the name of the known publisher
* @param listener the listener to call whenever a message matching the topic and signed with the publicKey arrives
@@ -354,7 +348,7 @@ public void subscribeFromPublisher(String topic, String publisherName, IUbiMessa
PublicKeyChangeListener publicKeyChangeListener = new PublicKeyChangeListener(this, topic, listener, actionListener);
publicKeyChangeListeners.add(publicKeyChangeListener);
- //subscribe to the public key of the publisher
+ // Subscribe to the public key of the publisher
String publicKeyTopic = PUBLISHERS_PREFIX + publisherName + "/publicKey";
this.subscribe(publicKeyTopic, publicKeyChangeListener, new IUbiActionListener() {
diff --git a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java
index 332c77e..1d1bee5 100644
--- a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java
+++ b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java
@@ -12,6 +12,7 @@
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
+
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@@ -28,12 +29,12 @@
import static org.junit.Assert.*;
public class JwsHelperTest {
-
@Test
public void testJwsHelper_CanSign() {
java.security.Security.addProvider(com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton.getInstance());
String privateKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
@@ -46,14 +47,11 @@ public void testJwsHelper_CanSign() {
}
try {
- String compactResult = JwsHelper.signMessageToCompact("Hello world", privateKey);
- System.out.println(compactResult);
+ String msg = "Hello world";
+ String compactResult = JwsHelper.signMessageToCompact(msg, privateKey);
String jsonResult = JwsHelper.compactToJson(compactResult);
- System.out.println(jsonResult);
-
String newCompactResult = JwsHelper.jsonToCompact(jsonResult);
- System.out.println(newCompactResult);
assertEquals(compactResult, newCompactResult);
@@ -63,13 +61,13 @@ public void testJwsHelper_CanSign() {
}
}
-
@Test
public void testJwsHelper_CanSignAndVerify() {
java.security.Security.addProvider(com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton.getInstance());
String privateKey = "";
String publicKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
@@ -91,21 +89,17 @@ public void testJwsHelper_CanSignAndVerify() {
}
try {
- String compactResult = JwsHelper.signMessageToCompact("Hello world", privateKey);
- System.out.println(compactResult);
+ String msg = "Hello world";
+ String compactResult = JwsHelper.signMessageToCompact(msg, privateKey);
String jsonResult = JwsHelper.compactToJson(compactResult);
- System.out.println(jsonResult);
-
String newCompactResult = JwsHelper.jsonToCompact(jsonResult);
- System.out.println(newCompactResult);
assertEquals(compactResult, newCompactResult);
boolean isVerified = JwsHelper.verifySignatureCompact(newCompactResult, publicKey);
assertTrue(isVerified);
-
} catch (Exception e) {
e.printStackTrace();
assertNull(e);
@@ -118,6 +112,7 @@ public void testJwsHelper_CanDetectFalseSignature() {
String privateKey = "";
String publicKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
@@ -139,24 +134,21 @@ public void testJwsHelper_CanDetectFalseSignature() {
}
try {
- String compactResult = JwsHelper.signMessageToCompact("Hello world", privateKey);
- System.out.println(compactResult);
+ String msg = "Hello world";
+ String compactResult = JwsHelper.signMessageToCompact(msg, privateKey);
String jsonResult = JwsHelper.compactToJson(compactResult);
- System.out.println(jsonResult);
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(jsonResult);
JSONArray signaturesArray = (JSONArray) obj.get("signatures");
- JSONObject signatureObject = (JSONObject)signaturesArray.get(0);
+ JSONObject signatureObject = (JSONObject) signaturesArray.get(0);
signatureObject.put("signature","falsesignature");
-
boolean isVerified = JwsHelper.verifySignature(obj.toJSONString(), publicKey);
assertFalse(isVerified);
-
} catch (Exception e) {
e.printStackTrace();
assertNull(e);
@@ -169,6 +161,7 @@ public void testJwsHelper_canEncryptMessage() {
String privateKey = "";
String publicKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
@@ -222,6 +215,7 @@ public void testJwsHelper_canDecryptMessage() {
String privateKey = "";
String publicKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
diff --git a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/MessageValidatorTest.java b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/MessageValidatorTest.java
index 122a2a5..03e4c3c 100644
--- a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/MessageValidatorTest.java
+++ b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/MessageValidatorTest.java
@@ -7,9 +7,11 @@
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
public class MessageValidatorTest {
-
private String signMessage(String message) {
java.security.Security.addProvider(com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton.getInstance());
@@ -22,26 +24,19 @@ private String signMessage(String message) {
byte[] encoded = Files.readAllBytes(Paths.get(path));
privateKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
try {
- String compactResult = JwsHelper.signMessageToCompact("Hello world", privateKey);
- System.out.println(compactResult);
-
+ String compactResult = JwsHelper.signMessageToCompact(message, privateKey);
jsonResult = JwsHelper.compactToJson(compactResult);
- System.out.println(jsonResult);
-
String newCompactResult = JwsHelper.jsonToCompact(jsonResult);
- System.out.println(newCompactResult);
assertEquals(compactResult, newCompactResult);
-
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
return jsonResult;
}
@@ -49,7 +44,7 @@ private String signMessage(String message) {
@Test
public void testMessageValidator_CanDetectReplayedMessage() {
try {
- String signedMessage = this.signMessage("Testjee");
+ String signedMessage = this.signMessage("TestWuu");
MessageValidator messageValidator = new MessageValidator(60);
@@ -62,27 +57,27 @@ public void testMessageValidator_CanDetectReplayedMessage() {
byte[] encoded = Files.readAllBytes(Paths.get(path));
publicKey = new String(encoded, StandardCharsets.UTF_8);
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
- System.out.println("Trying to validate message");
+ // Trying to validate message.
boolean firstResult = messageValidator.validateMessage(signedMessage, JwsHelper.createEcPublicKey(publicKey));
- assertEquals(true, firstResult);
+ assertTrue(firstResult);
boolean secondResult = messageValidator.validateMessage(signedMessage, JwsHelper.createEcPublicKey(publicKey));
- assertEquals(false, secondResult);
+ assertFalse(secondResult);
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
}
@Test
public void testMessageValidator_CanDetectTooOldMessage() {
try {
- String signedMessage = this.signMessage("Testjee");
+ String signedMessage = this.signMessage("TestAAA");
MessageValidator messageValidator = new MessageValidator(1);
@@ -95,19 +90,17 @@ public void testMessageValidator_CanDetectTooOldMessage() {
byte[] encoded = Files.readAllBytes(Paths.get(path));
publicKey = new String(encoded, StandardCharsets.UTF_8);
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
- System.out.println("Trying to validate a message that is one second too old, sleeping 2 seconds");
-
+ // Trying to validate a message that is one second too old, sleeping 2 seconds.
Thread.sleep(5000);
boolean firstResult = messageValidator.validateMessage(signedMessage, JwsHelper.createEcPublicKey(publicKey));
- assertEquals(false, firstResult);
-
+ assertFalse(firstResult);
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
}
}
diff --git a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/UbiMqttTest.java b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/UbiMqttTest.java
index bb9eb47..ed5cfb5 100644
--- a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/UbiMqttTest.java
+++ b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/UbiMqttTest.java
@@ -15,12 +15,12 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-// Make sure that a MQTT server answers at localhost:1883 before running these tests
-// If you have access to Ubikampus VMs, you can forward the Ubikampus MQTT server
-// port to localhost with the command "ssh -L 1883:10.120.0.4:1883 ubi@iot.ubikampus.net"
-
+/**
+ * Make sure that a MQTT server answers at localhost:1883 before running these tests
+ * If you have access to Ubikampus VMs, you can forward the Ubikampus MQTT server
+ * port to localhost with the command "ssh -L 1883:10.120.0.4:1883 ubi@iot.ubikampus.net"
+ */
public class UbiMqttTest {
-
private static final String TOPIC = "test/javatesttopic";
private static final String SIGNED_TOPIC = "test/javasignedtesttopic";
private static final String ENCRYPTED_TOPIC = "test/javaencryptedtesttopic";
@@ -32,13 +32,12 @@ public class UbiMqttTest {
private void log(String s) {
StackTraceElement l = new Exception().getStackTrace()[0];
- System.out.println(
- l.getClassName() + "/" + l.getMethodName() + ":" + l.getLineNumber() + ": " + s);
+ System.out.println(l.getClassName() + "/" + l.getMethodName() + ":" + l.getLineNumber() + ": " + s);
}
- private CompletableFuture timeoutAfter(long timeout, TimeUnit unit) {
+ private CompletableFuture timeoutAfter() {
CompletableFuture result = new CompletableFuture();
- delayer.schedule(() -> result.completeExceptionally(new TimeoutException()), timeout, unit);
+ delayer.schedule(() -> result.completeExceptionally(new TimeoutException()), (long) 10, TimeUnit.SECONDS);
return result;
}
@@ -63,6 +62,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
future.complete("failure");
}
});
+
try {
assertEquals("success", future.get(5, TimeUnit.SECONDS));
@@ -80,15 +80,16 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
disconnectFuture.complete("failure");
}
});
+
try {
assertEquals("success", disconnectFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
}
@@ -118,7 +119,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
assertEquals("failure", future.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
}
@@ -143,11 +144,12 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
future.complete("failure");
}
});
+
try {
assertEquals("success", future.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture subscribeFuture = new CompletableFuture<>();
@@ -160,6 +162,7 @@ public void messageArrived(String s, MqttMessage mqttMessage, String subscriptio
messageFuture.complete(mqttMessage.toString());
}
};
+
ubiMqtt.subscribe("test/javatesttopic", messageListener, new IUbiActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
@@ -173,15 +176,17 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
subscribeFuture.complete("failure");
}
});
+
try {
assertEquals("success", subscribeFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
try {
- messageFuture.acceptEither(timeoutAfter(10, TimeUnit.SECONDS), message -> assertEquals("Hello from Java!", message))
+ messageFuture
+ .acceptEither(timeoutAfter(), message -> assertEquals("Hello from Java!", message))
.thenAccept(message -> {
CompletableFuture disconnectFuture = new CompletableFuture<>();
ubiMqtt.disconnect(new IUbiActionListener() {
@@ -197,16 +202,17 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
disconnectFuture.complete("failure");
}
});
+
try {
assertEquals("success", disconnectFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
});
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture publishFuture = new CompletableFuture<>();
@@ -224,13 +230,13 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
publishFuture.complete("failure");
}
});
+
try {
assertEquals("success", publishFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
-
}
@Test
@@ -238,27 +244,26 @@ public void testUbiMqtt_CanPublishAndSubscribeSigned() {
log("testUbiMqtt_CanPublishAndSubscribeSigned()");
String privateKey = "";
+ String publicKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
byte[] encoded = Files.readAllBytes(Paths.get(path));
privateKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
- String publicKey = "";
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key-public.pem";
byte[] encoded = Files.readAllBytes(Paths.get(path));
publicKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture future = new CompletableFuture<>();
@@ -278,11 +283,12 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
future.complete("failure");
}
});
+
try {
assertEquals("success", future.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture subscribeFuture = new CompletableFuture<>();
@@ -295,6 +301,7 @@ public void messageArrived(String s, MqttMessage mqttMessage, String subscriptio
messageFuture.complete(mqttMessage.toString());
}
};
+
String[] publicKeys = {publicKey};
ubiMqtt.subscribeSigned(SIGNED_TOPIC, publicKeys, messageListener, new IUbiActionListener() {
@@ -310,15 +317,17 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
subscribeFuture.complete("failure");
}
});
+
try {
assertEquals("success", subscribeFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
try {
- messageFuture.acceptEither(timeoutAfter(10, TimeUnit.SECONDS), message -> assertEquals("Hello from Java!", message))
+ messageFuture
+ .acceptEither(timeoutAfter(), message -> assertEquals("Hello from Java!", message))
.thenAccept(message -> {
CompletableFuture disconnectFuture = new CompletableFuture<>();
ubiMqtt.disconnect(new IUbiActionListener() {
@@ -334,16 +343,17 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
disconnectFuture.complete("failure");
}
});
+
try {
assertEquals("success", disconnectFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
});
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture publishFuture = new CompletableFuture<>();
@@ -361,39 +371,38 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
publishFuture.complete("failure");
}
});
+
try {
assertEquals("success", publishFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
-
}
@Test
public void testUbiMqtt_CanPublishAndSubscribeEncrypted() {
log("testUbiMqtt_CanPublishAndSubscribeEncrypted()");
+ String publicKey = "";
String privateKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
byte[] encoded = Files.readAllBytes(Paths.get(path));
privateKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
assertNull(e);
}
- String publicKey = "";
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key-public.pem";
byte[] encoded = Files.readAllBytes(Paths.get(path));
publicKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
assertNull(e);
}
@@ -414,6 +423,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
future.complete("failure");
}
});
+
try {
assertEquals("success", future.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
@@ -446,6 +456,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
subscribeFuture.complete("failure");
}
});
+
try {
assertEquals("success", subscribeFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
@@ -454,7 +465,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
try {
- messageFuture.acceptEither(timeoutAfter(10, TimeUnit.SECONDS), message -> assertEquals("Hello from Java!", message))
+ messageFuture.acceptEither(timeoutAfter(), message -> assertEquals("Hello from Java!", message))
.thenAccept(message -> {
CompletableFuture disconnectFuture = new CompletableFuture<>();
ubiMqtt.disconnect(new IUbiActionListener() {
@@ -470,6 +481,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
disconnectFuture.complete("failure");
}
});
+
try {
assertEquals("success", disconnectFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
@@ -497,6 +509,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
publishFuture.complete("failure");
}
});
+
try {
assertEquals("success", publishFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
@@ -510,27 +523,26 @@ public void testUbiMqtt_CanSubscribeFromKnownPublisher() {
log("testUbiMqtt_CanSubscribeFromKnownPublisher()");
String privateKey = "";
+ String publicKey = "";
+
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key.pem";
byte[] encoded = Files.readAllBytes(Paths.get(path));
privateKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
- String publicKey = "";
try {
String home = System.getProperty("user.home");
String path = home + "/.private/ubimqtt-testing-key-public.pem";
byte[] encoded = Files.readAllBytes(Paths.get(path));
publicKey = new String(encoded, StandardCharsets.UTF_8);
-
} catch (Exception e) {
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture future = new CompletableFuture<>();
@@ -550,11 +562,12 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
future.complete("failure");
}
});
+
try {
assertEquals("success", future.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
// Publish the the a public key for our "known" publisher
@@ -574,11 +587,12 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
publishKeyFuture.complete("failure");
}
});
+
try {
assertEquals("success", publishKeyFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture subscribeFuture = new CompletableFuture<>();
@@ -591,6 +605,7 @@ public void messageArrived(String s, MqttMessage mqttMessage, String subscriptio
messageFuture.complete(mqttMessage.toString());
}
};
+
ubiMqtt.subscribeFromPublisher("test/javatesttopic", JAVA_TEST_PUBLISHER, messageListener, new IUbiActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
@@ -604,15 +619,17 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
subscribeFuture.complete("failure");
}
});
+
try {
assertEquals("success", subscribeFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
try {
- messageFuture.acceptEither(timeoutAfter(10, TimeUnit.SECONDS), message -> assertEquals("Hello from Java!", message))
+ messageFuture
+ .acceptEither(timeoutAfter(), message -> assertEquals("Hello from Java!", message))
.thenAccept(message -> {
CompletableFuture disconnectFuture = new CompletableFuture<>();
ubiMqtt.disconnect(new IUbiActionListener() {
@@ -628,16 +645,17 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
disconnectFuture.complete("failure");
}
});
+
try {
assertEquals("success", disconnectFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
});
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
CompletableFuture publishFuture = new CompletableFuture<>();
@@ -655,12 +673,12 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
publishFuture.complete("failure");
}
});
+
try {
assertEquals("success", publishFuture.get(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
- assertEquals(null, e);
+ assertNull(e);
}
-
}
}