From fd20e5a76cfc9ff866902eeac48c0e85a8ab7fd0 Mon Sep 17 00:00:00 2001 From: jhoneagle Date: Fri, 16 Aug 2019 15:36:04 +0300 Subject: [PATCH 1/3] add gitattributes --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes 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 From c7c58008e5f85b8138137db1ea404199760e8088 Mon Sep 17 00:00:00 2001 From: Jhoneagle Date: Sat, 17 Aug 2019 12:50:54 +0300 Subject: [PATCH 2/3] added checkstyle rules to project and improved code quality --- .gitignore | 1 + build.gradle | 14 + checkstyle.xml | 260 ++++++++++++++++++ ubimqtt/build.gradle | 5 + .../helsinki/ubimqtt/IUbiActionListener.java | 5 + .../helsinki/ubimqtt/IUbiMessageListener.java | 6 +- .../java/fi/helsinki/ubimqtt/JwsHelper.java | 71 ++--- .../fi/helsinki/ubimqtt/MessageValidator.java | 28 +- .../ubimqtt/PublicKeyChangeListener.java | 16 +- .../fi/helsinki/ubimqtt/ReplayDetector.java | 31 ++- .../fi/helsinki/ubimqtt/Subscription.java | 10 +- .../java/fi/helsinki/ubimqtt/UbiMqtt.java | 126 ++++----- .../fi/helsinki/ubimqtt/JwsHelperTest.java | 48 ++-- .../ubimqtt/MessageValidatorTest.java | 41 ++- .../java/fi/helsinki/ubimqtt/UbiMqttTest.java | 109 ++++---- 15 files changed, 529 insertions(+), 242 deletions(-) create mode 100644 checkstyle.xml diff --git a/.gitignore b/.gitignore index cdb6db1..e7e439f 100644 --- a/.gitignore +++ b/.gitignore @@ -191,3 +191,4 @@ gradle-app.setting /keystore/reservator_release.keystore app/release/ +*.pem \ 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/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 8ee37da..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 { - public void messageArrived(String topic, MqttMessage mqttMessage, String listenerId) throws Exception; + 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 c3676f8..ca02f26 100644 --- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java +++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java @@ -14,7 +14,6 @@ import org.apache.commons.lang3.RandomStringUtils; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.openssl.PEMException; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; @@ -28,34 +27,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 { - return verifySignatureCompact(jsonToCompact(json), publicKey); + 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("\\."); @@ -69,17 +79,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(); @@ -87,7 +101,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(); @@ -110,21 +124,19 @@ public static String signMessageToCompact( String message, String privateKey) th jwsObject.sign(signer); */ - String s = jwsObject.serialize(); - - return s; + 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); + System.out.println("header: " + header); + System.out.println("payload: " + payload); + System.out.println("signature: " + signature); JSONObject obj = new JSONObject(); @@ -145,21 +157,18 @@ 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"); - - JSONArray signaturesArray = (JSONArray)obj.get("signatures"); - JSONObject signatureObject = (JSONObject)signaturesArray.get(0); + String payload = (String) obj.get("payload"); - String header = ((JSONObject)signatureObject.get("protected")).toJSONString(); - String signature = (String)signatureObject.get("signature"); + 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 compact = Base64URL.encode(header)+"."+Base64URL.encode(payload)+"."+signature; - return compact; + return Base64URL.encode(header) + "." + Base64URL.encode(payload) + "." + signature; } } 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 5bfb1e2..a547246 100644 --- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/PublicKeyChangeListener.java +++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/PublicKeyChangeListener.java @@ -2,12 +2,15 @@ import org.eclipse.paho.client.mqttv3.MqttMessage; +/** + * Listener for updating public keys during use. + */ public class PublicKeyChangeListener implements IUbiMessageListener { - private String mainListenerId = null; - private IUbiActionListener originalCallback = null; - private UbiMqtt ubiMqtt = null; - private String mainTopic = null; - IUbiMessageListener mainListener = null; + private String mainListenerId; + private IUbiActionListener originalCallback; + private UbiMqtt ubiMqtt; + private String mainTopic; + private IUbiMessageListener mainListener; public PublicKeyChangeListener(UbiMqtt ubiMqtt, String mainTopic, IUbiMessageListener mainListener, IUbiActionListener originalCallback) { this.ubiMqtt = ubiMqtt; @@ -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 fade8b5..fb13798 100644 --- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/ReplayDetector.java +++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/ReplayDetector.java @@ -6,24 +6,24 @@ 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.buffer = new TreeMap<>(); this.bufferWindowInSeconds = bufferWindowInSeconds; //addEntry(System.currentTimeMillis(), ""); } private void addEntry(long timestamp, String messageId) { - - Map messages = null; + Map messages; if (!buffer.containsKey(timestamp)) { - messages = new HashMap(); + messages = new HashMap<>(); buffer.put(timestamp, messages); } else { messages = buffer.get(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 c7c7ecb..8e881d2 100644 --- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/Subscription.java +++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/Subscription.java @@ -3,20 +3,23 @@ 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; private ECPublicKey[] ecPublicKeys; - - public Subscription(String topic, IUbiMessageListener listener, String[] publicKeys) throws IOException { this.topic = topic; this.listener = listener; + 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; @@ -62,32 +54,27 @@ private ArrayList > getSubscriptionsForTopic(Stri 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 { next.getValue().getListener().messageArrived(topic, mqttMessage, next.getKey()); } } } }; - 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); @@ -97,8 +84,9 @@ 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 + ""; listenerCounter++; @@ -116,48 +104,38 @@ 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 */ - 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 */ @@ -176,10 +154,10 @@ 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) { try { this.client.disconnect(); @@ -191,14 +169,14 @@ 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 * @param retained publish the message as a retained Mqtt message if true * @param actionListener the callback to call upon success or error */ - public void publish(String topic, String message, int qos, boolean retained, IUbiActionListener actionListener) { try { this.client.publish(topic, message.getBytes(), qos, retained, null, actionListener); @@ -208,19 +186,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 @@ -228,7 +207,6 @@ public void publish(String topic, String message,IUbiActionListener actionListen * @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, int qos, boolean retained, String privateKey, IUbiActionListener actionListener) { try { this.client.publish(topic, this.signMessage(message, privateKey).getBytes(), qos, retained, null, actionListener); @@ -238,44 +216,45 @@ 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); } /** - * 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 */ - public void subscribe(String topic, IUbiMessageListener listener, IUbiActionListener actionListener) { addSubscription(actionListener, topic, null, listener); } /** - * 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 * @param actionListener the callback to be called upon successful subscription or error */ - public void subscribeSigned(String topic, String[] publicKeys, IUbiMessageListener listener, IUbiActionListener actionListener) { addSubscription(actionListener, topic, publicKeys, listener); } /** - * 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 @@ -286,7 +265,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() { @@ -299,6 +278,5 @@ public void onFailure(IMqttToken iMqttToken, Throwable throwable) { actionListener.onFailure(iMqttToken, throwable); } }); - } } diff --git a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java index c97228a..47ca755 100644 --- a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java +++ b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java @@ -1,7 +1,5 @@ package fi.helsinki.ubimqtt; -import com.nimbusds.jose.JOSEException; - import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -12,14 +10,17 @@ 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 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"; @@ -28,7 +29,7 @@ public void testJwsHelper_CanSign() { privateKey = new String(encoded, StandardCharsets.UTF_8); } catch (Exception e) { - assertEquals(null, e); + assertNull(e); } try { @@ -45,17 +46,17 @@ public void testJwsHelper_CanSign() { } catch (Exception e) { e.printStackTrace(); - assertEquals(null, e); + assertNull(e); } } - @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"; @@ -63,7 +64,7 @@ public void testJwsHelper_CanSignAndVerify() { byte[] encoded = Files.readAllBytes(Paths.get(path)); privateKey = new String(encoded, StandardCharsets.UTF_8); } catch (Exception e) { - assertEquals(null, e); + assertNull(e); } try { @@ -73,28 +74,24 @@ public void testJwsHelper_CanSignAndVerify() { byte[] encoded = Files.readAllBytes(Paths.get(path)); publicKey = 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 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); - assertEquals(true, isVerified); - + assertTrue(isVerified); } catch (Exception e) { e.printStackTrace(); - assertEquals(null, e); + assertNull(e); } } @@ -104,6 +101,7 @@ public void testJwsHelper_CanDetectFalseSignature() { String privateKey = ""; String publicKey = ""; + try { String home = System.getProperty("user.home"); String path = home + "/.private/ubimqtt-testing-key.pem"; @@ -111,7 +109,7 @@ public void testJwsHelper_CanDetectFalseSignature() { byte[] encoded = Files.readAllBytes(Paths.get(path)); privateKey = new String(encoded, StandardCharsets.UTF_8); } catch (Exception e) { - assertEquals(null, e); + assertNull(e); } try { @@ -121,32 +119,28 @@ public void testJwsHelper_CanDetectFalseSignature() { byte[] encoded = Files.readAllBytes(Paths.get(path)); publicKey = 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 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); - assertEquals(false, isVerified); - + assertFalse(isVerified); } catch (Exception e) { e.printStackTrace(); - assertEquals(null, e); + assertNull(e); } } - } 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 01f9b85..bb11a79 100644 --- a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/UbiMqttTest.java +++ b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/UbiMqttTest.java @@ -13,30 +13,29 @@ import java.util.concurrent.TimeoutException; 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 KEY_TOPIC = "publishers/javatestpublisher/publicKey"; private static final String JAVA_TEST_PUBLISHER = "javatestpublisher"; - ScheduledThreadPoolExecutor delayer = new ScheduledThreadPoolExecutor(5); + private ScheduledThreadPoolExecutor delayer = new ScheduledThreadPoolExecutor(5); - public void log(String s) { + 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); } - public 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; } @@ -61,6 +60,7 @@ public void onFailure(IMqttToken asyncActionToken, Throwable exception) { future.complete("failure"); } }); + try { assertEquals("success", future.get(5, TimeUnit.SECONDS)); @@ -78,15 +78,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); } } @@ -116,7 +117,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); } } @@ -141,11 +142,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<>(); @@ -158,6 +160,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) { @@ -171,15 +174,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() { @@ -195,16 +200,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<>(); @@ -222,13 +228,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 @@ -236,27 +242,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<>(); @@ -276,11 +281,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<>(); @@ -293,6 +299,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() { @@ -308,15 +315,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() { @@ -332,16 +341,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<>(); @@ -359,13 +369,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); } - } @@ -374,27 +384,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<>(); @@ -414,11 +423,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 @@ -438,11 +448,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<>(); @@ -455,6 +466,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) { @@ -468,15 +480,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() { @@ -492,16 +506,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<>(); @@ -519,12 +534,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); } - } } From cc3813da6ba0283b5e9ce178da74e1dcb6286298 Mon Sep 17 00:00:00 2001 From: jhoneagle Date: Sat, 17 Aug 2019 13:38:21 +0300 Subject: [PATCH 3/3] remove debug like system.out.rpints --- ubimqtt/.attach_pid7230 | 0 ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java | 4 ---- .../src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java | 7 ++----- 3 files changed, 2 insertions(+), 9 deletions(-) create mode 100644 ubimqtt/.attach_pid7230 diff --git a/ubimqtt/.attach_pid7230 b/ubimqtt/.attach_pid7230 new file mode 100644 index 0000000..e69de29 diff --git a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java index ca02f26..04ffcc6 100644 --- a/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java +++ b/ubimqtt/src/main/java/fi/helsinki/ubimqtt/JwsHelper.java @@ -134,10 +134,6 @@ public static String compactToJson(String compact) throws ParseException { 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(); diff --git a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java index 47ca755..b7fc332 100644 --- a/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java +++ b/ubimqtt/src/test/java/fi/helsinki/ubimqtt/JwsHelperTest.java @@ -33,14 +33,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);