Fixed checkStyle and ErrorProne warns

This commit is contained in:
andsel
2018-04-26 22:23:06 +02:00
parent 1a6dd8a259
commit 033a428184
81 changed files with 680 additions and 424 deletions
+4 -4
View File
@@ -169,19 +169,19 @@ public final class Utils {
return 3;
if (2097152 <= len && len <= 268435455)
return 4;
throw new IllegalArgumentException("value shoul be in the range [0..268435455]");
throw new IllegalArgumentException("value should be in the range [0..268435455]");
}
static byte encodeFlags(MqttMessage message) {
byte flags = 0;
if (message.fixedHeader().isDup()) {
flags |= 0x08;
flags |= (byte) 0x08;
}
if (message.fixedHeader().isRetain()) {
flags |= 0x01;
flags |= (byte) 0x01;
}
flags |= (message.fixedHeader().qosLevel().value() & 0x03) << 1;
flags |= (byte) ((message.fixedHeader().qosLevel().value() & 0x03) << 1);
return flags;
}
@@ -1,3 +1,19 @@
/*
* Copyright (c) 2012-2017 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.moquette.persistence;
import io.moquette.spi.*;
@@ -9,11 +25,14 @@ import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static io.moquette.spi.impl.subscriptions.Topic.asTopic;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
import static io.netty.handler.codec.mqtt.MqttQoS.EXACTLY_ONCE;
import static java.nio.charset.StandardCharsets.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -28,9 +47,9 @@ public abstract class MessageStoreTCK {
protected SessionsRepository sessionsRepository;
@Test
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() {
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() throws UnsupportedEncodingException {
final ClientSession session = sessionsRepository.createNewSession(TEST_CLIENT, true);
StoredMessage publishToStore = new StoredMessage("Hello".getBytes(), EXACTLY_ONCE, "/topic");
StoredMessage publishToStore = new StoredMessage("Hello".getBytes(UTF_8), EXACTLY_ONCE, "/topic");
publishToStore.setClientID(TEST_CLIENT);
publishToStore.setRetained(true);
messagesStore.storeRetained(new Topic("/topic"), publishToStore);
@@ -50,8 +69,8 @@ public abstract class MessageStoreTCK {
}
@Test
public void testStoreRetained() {
StoredMessage msgStored = new StoredMessage("Hello".getBytes(), MqttQoS.AT_LEAST_ONCE, "/topic");
public void testStoreRetained() throws UnsupportedEncodingException {
StoredMessage msgStored = new StoredMessage("Hello".getBytes(UTF_8), MqttQoS.AT_LEAST_ONCE, "/topic");
msgStored.setClientID(TEST_CLIENT);
messagesStore.storeRetained(asTopic("/topic"), msgStored);
@@ -68,7 +87,7 @@ public abstract class MessageStoreTCK {
final ByteBuf payload = msgRetrieved.getPayload();
byte[] content = new byte[payload.readableBytes()];
payload.readBytes(content);
assertEquals("Hello", new String(content));
assertEquals("Hello", new String(content, UTF_8));
}
@Test
@@ -26,7 +26,7 @@ import java.util.concurrent.*;
*/
public class MessageCollector implements MqttCallback {
private final class ReceivedMessage {
private static final class ReceivedMessage {
private final MqttMessage message;
private final String topic;
@@ -27,6 +27,8 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;
public class ServerIntegrationFuseTest {
@@ -98,6 +100,6 @@ public class ServerIntegrationFuseTest {
Message msg = m_subscriber.receive(500, TimeUnit.MILLISECONDS);
assertNotNull("We should get notified with 'Will' message", msg);
msg.ack();
assertEquals(willTestamentMsg, new String(msg.getPayload()));
assertEquals(willTestamentMsg, new String(msg.getPayload(), UTF_8));
}
}
@@ -35,6 +35,7 @@ import java.sql.SQLException;
import java.util.Properties;
import static io.moquette.BrokerConstants.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
public class ServerIntegrationHazelcastHandlerInterceptorTest {
@@ -122,7 +123,7 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest {
LOG.info("*** checkPublishPassThroughCluster_Qos0 ***");
m_listener.subscribe("/topic", 1);
m_publisher.publish("/topic", "Hello world MQTT QoS0".getBytes(), 0, false);
m_publisher.publish("/topic", "Hello world MQTT QoS0".getBytes(UTF_8), 0, false);
MqttMessage messageQos0 = m_messagesCollector.waitMessage(1);
assertEquals("Hello world MQTT QoS0", messageQos0.toString());
assertEquals(0, messageQos0.getQos());
@@ -133,7 +134,7 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest {
LOG.info("*** checkPublishPassThroughCluster_Qos1 ***");
m_listener.subscribe("/topic", 1);
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(), 1, false);
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(UTF_8), 1, false);
MqttMessage messageQos1 = m_messagesCollector.waitMessage(1);
assertEquals("Hello world MQTT QoS1", messageQos1.toString());
assertEquals(1, messageQos1.getQos());
@@ -144,7 +145,7 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest {
LOG.info("*** checkPublishPassThroughCluster_Qos2 ***");
m_listener.subscribe("/topic", 2);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 2, false);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(UTF_8), 2, false);
MqttMessage messageQos2 = m_messagesCollector.waitMessage(1);
assertEquals("Hello world MQTT QoS2", messageQos2.toString());
assertEquals(2, messageQos2.getQos());
@@ -26,6 +26,8 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;
public class ServerIntegrationPahoTest {
@@ -83,7 +85,6 @@ public class ServerIntegrationPahoTest {
m_server.stopServer();
}
@Ignore("This test hasn't any meaning using in memory storage service")
@Test
public void testCleanSession_maintainClientSubscriptions_withServerRestart() throws Exception {
@@ -100,12 +101,11 @@ public class ServerIntegrationPahoTest {
// reconnect and publish
m_client.connect(options);
m_client.publish("/topic", "Test my payload".getBytes(), 0, false);
m_client.publish("/topic", "Test my payload".getBytes(UTF_8), 0, false);
assertEquals("/topic", m_messagesCollector.getTopic());
}
/**
* subscriber A connect and subscribe on "a/b" QoS 1 subscriber B connect and subscribe on "a/+"
* BUT with QoS 2 publisher connects and send a message "hello" on "a/b" subscriber A must
@@ -133,15 +133,15 @@ public class ServerIntegrationPahoTest {
subscriberB.subscribe("a/+", 2);
m_client.connect();
m_client.publish("a/b", "Hello world MQTT!!".getBytes(), 2, false);
m_client.publish("a/b", "Hello world MQTT!!".getBytes(UTF_8), 2, false);
MqttMessage messageOnA = cbSubscriberA.waitMessage(1);
assertEquals("Hello world MQTT!!", new String(messageOnA.getPayload()));
assertEquals("Hello world MQTT!!", new String(messageOnA.getPayload(), UTF_8));
assertEquals(1, messageOnA.getQos());
subscriberA.disconnect();
MqttMessage messageOnB = cbSubscriberB.waitMessage(1);
assertEquals("Hello world MQTT!!", new String(messageOnB.getPayload()));
assertEquals("Hello world MQTT!!", new String(messageOnB.getPayload(), UTF_8));
assertEquals(2, messageOnB.getQos());
subscriberB.disconnect();
}
@@ -180,15 +180,15 @@ public class ServerIntegrationPahoTest {
tmpDir + File.separator + "clientForPublish");
MqttClient clientForPublish = new MqttClient("tcp://localhost:1883", "clientForPublish", dsSubscriberPUB);
clientForPublish.connect();
clientForPublish.publish("topic", "Hello".getBytes(), 2, true);
clientForPublish.publish("topic", "Hello".getBytes(UTF_8), 2, true);
// verify clientForSubscribe1 doesn't receive a notification but clientForSubscribe2 yes
LOG.info("Before waiting to receive 1 sec from " + clientForSubscribe1.getClientId());
LOG.info("Before waiting to receive 1 sec from {}", clientForSubscribe1.getClientId());
assertFalse(clientForSubscribe1.isConnected());
assertTrue(clientForSubscribe2.isConnected());
LOG.info("Waiting to receive 1 sec from " + clientForSubscribe2.getClientId());
LOG.info("Waiting to receive 1 sec from {}", clientForSubscribe2.getClientId());
MqttMessage messageOnB = cbSubscriber2.waitMessage(1);
assertEquals("Hello", new String(messageOnB.getPayload()));
assertEquals("Hello", new String(messageOnB.getPayload(), UTF_8));
}
// @Test
@@ -32,6 +32,8 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
public class ServerIntegrationQoSValidationTest {
@@ -92,7 +94,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS0ReceiveQoS0publishes ***");
m_subscriber.subscribe("/topic", 0);
m_publisher.publish("/topic", "Hello world MQTT QoS0".getBytes(), 0, false);
m_publisher.publish("/topic", "Hello world MQTT QoS0".getBytes(UTF_8), 0, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS0", message.toString());
assertEquals(0, message.getQos());
@@ -103,7 +105,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS0ReceiveQoS1publishes_downgrade ***");
m_subscriber.subscribe("/topic", 0);
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(), 1, false);
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(UTF_8), 1, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS1", message.toString());
assertEquals(0, message.getQos());
@@ -114,7 +116,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS0ReceiveQoS2publishes_downgrade ***");
m_subscriber.subscribe("/topic", 0);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 2, false);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(UTF_8), 2, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS2", message.toString());
assertEquals(0, message.getQos());
@@ -125,7 +127,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS1ReceiveQoS0publishes ***");
m_subscriber.subscribe("/topic", 1);
m_publisher.publish("/topic", "Hello world MQTT QoS0".getBytes(), 0, false);
m_publisher.publish("/topic", "Hello world MQTT QoS0".getBytes(UTF_8), 0, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS0", message.toString());
assertEquals(0, message.getQos());
@@ -136,7 +138,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS1ReceiveQoS1publishes ***");
m_subscriber.subscribe("/topic", 1);
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(), 1, false);
m_publisher.publish("/topic", "Hello world MQTT QoS1".getBytes(UTF_8), 1, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS1", message.toString());
assertEquals(1, message.getQos());
@@ -147,7 +149,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS1ReceiveQoS2publishes_downgrade ***");
m_subscriber.subscribe("/topic", 1);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 2, false);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(UTF_8), 2, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS2", message.toString());
assertEquals(1, message.getQos());
@@ -158,7 +160,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS2ReceiveQoS0publishes ***");
m_subscriber.subscribe("/topic", 2);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 0, false);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(UTF_8), 0, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS2", message.toString());
assertEquals(0, message.getQos());
@@ -169,7 +171,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS2ReceiveQoS1publishes ***");
m_subscriber.subscribe("/topic", 2);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 1, false);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(UTF_8), 1, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS2", message.toString());
assertEquals(1, message.getQos());
@@ -180,7 +182,7 @@ public class ServerIntegrationQoSValidationTest {
LOG.info("*** checkSubscriberQoS2ReceiveQoS2publishes ***");
m_subscriber.subscribe("/topic", 2);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(), 2, false);
m_publisher.publish("/topic", "Hello world MQTT QoS2".getBytes(UTF_8), 2, false);
MqttMessage message = m_callback.waitMessage(1);
assertEquals("Hello world MQTT QoS2", message.toString());
assertEquals(2, message.getQos());
@@ -27,6 +27,8 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -100,11 +102,11 @@ public class ServerIntegrationRestartTest {
// should be just one registration so a publisher receive one notification
m_publisher.connect(CLEAN_SESSION_OPT);
m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(), 1, false);
m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(UTF_8), 1, false);
// read the messages
MqttMessage msg = m_messageCollector.waitMessage(1);
assertEquals("Hello world MQTT!!", new String(msg.getPayload()));
assertEquals("Hello world MQTT!!", new String(msg.getPayload(), UTF_8));
// no more messages on the same topic will be received
assertNull(m_messageCollector.waitMessage(1));
}
@@ -121,7 +123,7 @@ public class ServerIntegrationRestartTest {
m_server.startServer(IntegrationUtils.prepareTestProperties());
m_publisher.connect();
m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(), 0, false);
m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(UTF_8), 0, false);
}
@Test
@@ -147,7 +149,7 @@ public class ServerIntegrationRestartTest {
// publisher publishes on /topic
m_publisher = new MqttClient("tcp://localhost:1883", "Publisher", s_pubDataStore);
m_publisher.connect();
m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(), 1, false);
m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(UTF_8), 1, false);
// Expected
// the subscriber doesn't get notified (it's fully unsubscribed)
@@ -163,9 +165,9 @@ public class ServerIntegrationRestartTest {
client.setCallback(collector);
client.connect();
client.subscribe(topic, 1);
client.publish(topic, "Hello world MQTT!!".getBytes(), 0, false);
client.publish(topic, "Hello world MQTT!!".getBytes(UTF_8), 0, false);
MqttMessage msg = collector.waitMessage(1);
assertEquals("Hello world MQTT!!", new String(msg.getPayload()));
assertEquals("Hello world MQTT!!", new String(msg.getPayload(), UTF_8));
return client;
}
}
@@ -16,6 +16,7 @@
package io.moquette.server;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import java.io.File;
import java.io.IOException;
@@ -150,7 +151,7 @@ public class ServerIntegrationSSLTest {
MqttConnectOptions secondClientOptions = new MqttConnectOptions();
secondClientOptions.setSocketFactory(ssf);
secondClient.connect(secondClientOptions);
secondClient.publish("/topic", new MqttMessage("message".getBytes()));
secondClient.publish("/topic", new MqttMessage("message".getBytes(UTF_8)));
secondClient.disconnect();
m_client.disconnect();
@@ -65,6 +65,7 @@ public class ServerIntegrationWebSocketTest {
m_server.stopServer();
}
@SuppressWarnings("FutureReturnValueIgnored")
@Test
public void checkPlainConnect() throws Exception {
LOG.info("*** checkPlainConnect ***");
@@ -33,6 +33,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;
public class ServerLowlevelMessagesIntegrationTests {
@@ -121,7 +122,7 @@ public class ServerLowlevelMessagesIntegrationTests {
assertNotNull("the will message should be fired after keep alive!", msg);
// the will message hasn't to be received before the elapsing of Keep Alive timeout
assertTrue(System.currentTimeMillis() - connectTime > 3000);
assertEquals(willTestamentMsg, new String(msg.getPayload(), StandardCharsets.UTF_8));
assertEquals(willTestamentMsg, new String(msg.getPayload(), UTF_8));
});
m_willSubscriber.disconnect();
@@ -153,7 +154,7 @@ public class ServerLowlevelMessagesIntegrationTests {
// Verify will testament is published
org.eclipse.paho.client.mqttv3.MqttMessage receivedTestament = m_messageCollector.waitMessage(1);
assertEquals(willTestamentMsg, new String(receivedTestament.getPayload()));
assertEquals(willTestamentMsg, new String(receivedTestament.getPayload(), UTF_8));
m_willSubscriber.disconnect();
}
@@ -64,15 +64,16 @@ public class ClientSessionTest {
subscriptionsDirectory.add(oldSubscription);
// Subscribe on /topic again that overrides the previous subscription.
Subscription overrindingSubscription = new Subscription(sessionClean.clientID, new Topic("/topic"), EXACTLY_ONCE);
sessionClean.subscribe(overrindingSubscription);
subscriptionsDirectory.add(overrindingSubscription);
Subscription overridingSubscription = new Subscription(sessionClean.clientID, new Topic("/topic"),
EXACTLY_ONCE);
sessionClean.subscribe(overridingSubscription);
subscriptionsDirectory.add(overridingSubscription);
// Verify
List<Subscription> subscriptions = subscriptionsDirectory.matches(new Topic("/topic"));
assertEquals("Only one subscription must match /topic", 1, subscriptions.size());
Subscription sub = subscriptions.get(0);
assertEquals("Matching subscription MUST have higher QoS",
overrindingSubscription.getRequestedQos(), sub.getRequestedQos());
overridingSubscription.getRequestedQos(), sub.getRequestedQos());
}
}
@@ -23,7 +23,6 @@ import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.security.PermitAllAuthorizator;
import io.moquette.spi.impl.subscriptions.*;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.mqtt.*;
@@ -33,6 +32,7 @@ import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.CONNECTION_ACCEP
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_LEAST_ONCE;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -104,11 +104,10 @@ abstract class AbstractProtocolProcessorCommonUtils {
final String clientId = NettyUtils.clientID(channel);
Subscription expectedSubscription = new Subscription(clientId, new Topic(topic), desiredQos);
verifySubscriptionExists(channel, m_sessionStore, expectedSubscription);
verifySubscriptionExists(m_sessionStore, expectedSubscription);
}
protected static void verifySubscriptionExists(Channel channel, ISessionsStore sessionsStore, Subscription expectedSubscription) {
final String clientId = NettyUtils.clientID(channel);
protected static void verifySubscriptionExists(ISessionsStore sessionsStore, Subscription expectedSubscription) {
final Subscription subscription = sessionsStore.subscriptionStore().reload(expectedSubscription);
assertEquals(expectedSubscription, subscription);
}
@@ -166,7 +165,7 @@ abstract class AbstractProtocolProcessorCommonUtils {
.topicName(topic)
.retained(retained)
.qos(qos)
.payload(Unpooled.copiedBuffer(HELLO_WORLD_MQTT.getBytes())).build();
.payload(Unpooled.copiedBuffer(HELLO_WORLD_MQTT.getBytes(UTF_8))).build();
this.m_processor.internalPublish(publish, "INTRPUBL");
}
@@ -180,7 +179,7 @@ abstract class AbstractProtocolProcessorCommonUtils {
.topicName(topic)
.retained(retained)
.qos(qos)
.payload(Unpooled.copiedBuffer(HELLO_WORLD_MQTT.getBytes())).build();
.payload(Unpooled.copiedBuffer(HELLO_WORLD_MQTT.getBytes(UTF_8))).build();
this.m_processor.processPublish(m_channel, publish);
}
@@ -188,33 +187,37 @@ abstract class AbstractProtocolProcessorCommonUtils {
publishToAs(this.m_channel, clientId, topic, qos, messageId, retained);
}
protected void publishToAs(EmbeddedChannel channel, String clientId, String topic, MqttQoS qos, int messageId, boolean retained) {
protected void publishToAs(EmbeddedChannel channel, String clientId, String topic, MqttQoS qos, int messageId,
boolean retained) {
publishToAs(channel, clientId, topic, HELLO_WORLD_MQTT, qos, messageId, retained);
}
protected void publishToAs(EmbeddedChannel channel, String clientId, String topic, String payload, MqttQoS qos, int messageId, boolean retained) {
protected void publishToAs(EmbeddedChannel channel, String clientId, String topic, String payload, MqttQoS qos,
int messageId, boolean retained) {
NettyUtils.userName(channel, clientId);
MqttPublishMessage publish = MqttMessageBuilders.publish()
.topicName(topic)
.retained(retained)
.messageId(messageId)
.qos(qos)
.payload(Unpooled.copiedBuffer(payload.getBytes())).build();
.payload(Unpooled.copiedBuffer(payload.getBytes(UTF_8))).build();
this.m_processor.processPublish(channel, publish);
}
protected void publishQoS2ToAs(EmbeddedChannel channel, String clientId, String topic, int messageId, boolean retained) {
protected void publishQoS2ToAs(EmbeddedChannel channel, String clientId, String topic, int messageId,
boolean retained) {
publishQoS2ToAs(channel, clientId, topic, HELLO_WORLD_MQTT, messageId, retained);
}
protected void publishQoS2ToAs(EmbeddedChannel channel, String clientId, String topic, String payload, int messageId, boolean retained) {
protected void publishQoS2ToAs(EmbeddedChannel channel, String clientId, String topic, String payload,
int messageId, boolean retained) {
NettyUtils.userName(channel, clientId);
MqttPublishMessage publish = MqttMessageBuilders.publish()
.topicName(topic)
.retained(retained)
.messageId(messageId)
.qos(MqttQoS.EXACTLY_ONCE)
.payload(Unpooled.copiedBuffer(payload.getBytes())).build();
.payload(Unpooled.copiedBuffer(payload.getBytes(UTF_8))).build();
this.m_processor.processPublish(channel, publish);
verifyPubrecIsReceived(channel, messageId);
@@ -236,7 +239,6 @@ abstract class AbstractProtocolProcessorCommonUtils {
assertEquals(messageId, Utils.messageId(pubComp));
}
protected void connect() {
connectAsClient(FAKE_CLIENT_ID);
}
@@ -307,7 +309,7 @@ abstract class AbstractProtocolProcessorCommonUtils {
protected void verifyPublishIsReceived(EmbeddedChannel channel) {
final MqttPublishMessage publishReceived = channel.readOutbound();
String payloadMessage = new String(publishReceived.payload().array());
String payloadMessage = new String(publishReceived.payload().array(), UTF_8);
assertEquals("Sent and received payload must be identical", HELLO_WORLD_MQTT, payloadMessage);
}
@@ -321,7 +323,7 @@ abstract class AbstractProtocolProcessorCommonUtils {
protected void verifyPublishIsReceived(EmbeddedChannel channel, String expectedPayload, MqttQoS expectedQoS) {
final MqttPublishMessage publishReceived = channel.readOutbound();
String payloadMessage = new String(publishReceived.payload().array());
String payloadMessage = new String(publishReceived.payload().array(), UTF_8);
assertEquals("Sent and received payload must be identical", expectedPayload, payloadMessage);
assertEquals("Expected QoS don't match", expectedQoS, publishReceived.fixedHeader().qosLevel());
}
@@ -30,6 +30,7 @@ import org.junit.Test;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.mock;
@@ -126,7 +127,7 @@ public class BrokerInterceptorTest {
public void testNotifyTopicPublished() throws Exception {
interceptor.notifyTopicPublished(
MqttMessageBuilders.publish().qos(MqttQoS.AT_MOST_ONCE)
.payload(Unpooled.copiedBuffer("Hello".getBytes())).build(),
.payload(Unpooled.copiedBuffer("Hello".getBytes(UTF_8))).build(),
"cli1234",
"cli1234");
interval();
@@ -20,6 +20,8 @@ import java.util.Map;
import java.util.Set;
import io.moquette.spi.security.IAuthenticator;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Test utility to implements authenticator instance.
*/
@@ -33,6 +35,7 @@ class MockAuthenticator implements IAuthenticator {
m_userPwds = userPwds;
}
@Override
public boolean checkValid(String clientId, String username, byte[] password) {
if (!m_clientIds.contains(clientId)) {
return false;
@@ -43,7 +46,7 @@ class MockAuthenticator implements IAuthenticator {
if (password == null) {
return false;
}
return m_userPwds.get(username).equals(new String(password));
return m_userPwds.get(username).equals(new String(password, UTF_8));
}
}
@@ -42,6 +42,7 @@ import static io.moquette.spi.impl.NettyChannelAssertions.assertConnAckAccepted;
import static io.moquette.spi.impl.ProtocolProcessor.lowerQosToTheSubscriptionDesired;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_LEAST_ONCE;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@@ -61,7 +62,6 @@ public class ProtocolProcessorTest extends AbstractProtocolProcessorCommonUtils
static final List<InterceptHandler> EMPTY_OBSERVERS = Collections.emptyList();
static final BrokerInterceptor NO_OBSERVERS_INTERCEPTOR = new BrokerInterceptor(EMPTY_OBSERVERS);
@Before
public void setUp() throws InterruptedException {
initializeProcessorAndSubsystems();
@@ -143,7 +143,7 @@ public class ProtocolProcessorTest extends AbstractProtocolProcessorCommonUtils
// Exercise
MqttPublishMessage msg = MqttMessageBuilders.publish().topicName(FAKE_TOPIC).qos(AT_MOST_ONCE)
.retained(false).payload(Unpooled.copiedBuffer("Hello".getBytes())).build();
.retained(false).payload(Unpooled.copiedBuffer("Hello".getBytes(UTF_8))).build();
NettyUtils.userName(m_channel, "FakeCLI");
m_processor.processPublish(m_channel, msg);
@@ -269,7 +269,7 @@ public class ProtocolProcessorTest extends AbstractProtocolProcessorCommonUtils
List<Subscription> emptySubs = Collections.emptyList();
when(subs.matches(any(Topic.class))).thenReturn(emptySubs);
StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(), MqttQoS.EXACTLY_ONCE, "/topic");
StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(UTF_8), MqttQoS.EXACTLY_ONCE, "/topic");
retainedMessage.setRetained(true);
retainedMessage.setClientID(FAKE_PUBLISHER_ID);
m_messagesStore.storeRetained(new Topic("/topic"), retainedMessage);
@@ -69,7 +69,8 @@ public class ProtocolProcessor_CONNECT_Test {
subscriptions.init(sessionsRepository);
m_processor = new ProtocolProcessor();
m_processor.init(subscriptions, m_messagesStore, m_sessionStore, m_mockAuthenticator, true,
new PermitAllAuthorizator(), NO_OBSERVERS_INTERCEPTOR, new SessionsRepository(this.m_sessionStore, null));
new PermitAllAuthorizator(), NO_OBSERVERS_INTERCEPTOR,
new SessionsRepository(this.m_sessionStore, null));
}
@Test
@@ -286,7 +287,7 @@ public class ProtocolProcessor_CONNECT_Test {
FAKE_CLIENT_ID,
new Topic(ProtocolProcessorTest.FAKE_TOPIC),
MqttQoS.AT_MOST_ONCE);
verifySubscriptionExists(m_session, m_sessionStore, expectedSubscription);
verifySubscriptionExists(m_sessionStore, expectedSubscription);
assertEqualsSubAck(m_session.readOutbound());
// disconnect
@@ -300,7 +301,7 @@ public class ProtocolProcessor_CONNECT_Test {
assertTrue("Connection is accepted and therefore should remain open.", m_session.isOpen());
// verify that the first subscription is still preserved
verifySubscriptionExists(m_session, m_sessionStore, expectedSubscription);
verifySubscriptionExists(m_sessionStore, expectedSubscription);
}
@Test
@@ -201,7 +201,8 @@ public class ProtocolProcessor_VariousUseCases_Test extends AbstractProtocolProc
}
@Test
public void avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1() throws InterruptedException {
public void avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1()
throws InterruptedException {
connect();
subscribe("/topic", AT_LEAST_ONCE);
disconnect();
@@ -221,7 +222,6 @@ public class ProtocolProcessor_VariousUseCases_Test extends AbstractProtocolProc
verifyPublishIsReceived("Hello MQTT 2", AT_LEAST_ONCE);
}
@Test
public void testConnectSubPub_cycle_getTimeout_on_second_disconnect_issue142() throws InterruptedException {
connect();
@@ -24,6 +24,8 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -70,7 +72,7 @@ public class DBAuthenticatorTest {
JDBC_H2_MEM_TEST,
"SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
SHA_256);
assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes()));
assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes(UTF_8)));
}
@Test
@@ -80,7 +82,7 @@ public class DBAuthenticatorTest {
JDBC_H2_MEM_TEST,
"SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
SHA_256);
assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes()));
assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes(UTF_8)));
}
@Test
@@ -90,7 +92,7 @@ public class DBAuthenticatorTest {
JDBC_H2_MEM_TEST,
"SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
SHA_256);
assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes()));
assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes(UTF_8)));
}
@After
@@ -18,6 +18,8 @@ package io.moquette.spi.impl.security;
import io.moquette.spi.security.IAuthenticator;
import org.junit.Test;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -29,7 +31,7 @@ public class FileAuthenticatorTest {
String file = getClass().getResource("/password_file.conf").getPath();
IAuthenticator auth = new FileAuthenticator(null, file);
assertTrue(auth.checkValid(null, "testuser", "passwd".getBytes()));
assertTrue(auth.checkValid(null, "testuser", "passwd".getBytes(UTF_8)));
}
@Test
@@ -37,14 +39,14 @@ public class FileAuthenticatorTest {
String file = getClass().getResource("/password_file.conf").getPath();
IAuthenticator auth = new FileAuthenticator(null, file);
assertFalse(auth.checkValid(null, "testuser2", "passwd".getBytes()));
assertFalse(auth.checkValid(null, "testuser2", "passwd".getBytes(UTF_8)));
}
@Test
public void loadPasswordFile_verifyDirectoryRef() {
IAuthenticator auth = new FileAuthenticator("", "");
assertFalse(auth.checkValid(null, "testuser2", "passwd".getBytes()));
assertFalse(auth.checkValid(null, "testuser2", "passwd".getBytes(UTF_8)));
}
}
@@ -83,10 +83,11 @@ public class CTrieSubscriptionDirectoryMatchingTest {
sut.add(financeAnySub);
// Verify
assertThat(sut.recursiveMatch(asTopic("finance/stock"), sut.root)).containsExactlyInAnyOrder(financeAnySub, anySub);
assertThat(sut.recursiveMatch(asTopic("finance/stock/ibm"), sut.root)).containsExactlyInAnyOrder(financeAnySub, anySub);
System.out.println(sut.dumpTree());
assertThat(sut.recursiveMatch(asTopic("finance/stock"), sut.root))
.containsExactlyInAnyOrder(financeAnySub, anySub);
assertThat(sut.recursiveMatch(asTopic("finance/stock/ibm"), sut.root))
.containsExactlyInAnyOrder(financeAnySub, anySub);
// System.out.println(sut.dumpTree());
}
@Test
@@ -144,8 +144,8 @@ public class CTrieSubscriptionDirectoryTest {
@Test
public void givenTreeWithSomeNodeWhenRemoveMultipleTimes() {
sut.add(clientSubOnTopic("TempSensor1", "test"));
// make sure no TNode exceptions
// make sure no TNode exceptions
sut.removeSubscription(asTopic("test"), "TempSensor1");
sut.removeSubscription(asTopic("test"), "TempSensor1");
sut.removeSubscription(asTopic("test"), "TempSensor1");
@@ -192,35 +192,30 @@ public class CTrieSubscriptionDirectoryTest {
sut.add(clientSubOnTopic("TempSensor1", "/temp/2"));
//Exercise
sut.removeSubscription(asTopic("/temp"), "TempSensor1");
final Set<Subscription> matchingSubs1 = sut.recursiveMatch(asTopic("/temp/1"), sut.root);
final Set<Subscription> matchingSubs2 = sut.recursiveMatch(asTopic("/temp/2"), sut.root);
//Verify
// not clear to me, but I believe /temp unsubscribe should not unsub you from downstream /temp/1 or /temp/2
final Subscription expectedMatchingsub1 = new Subscription("TempSensor1", asTopic("/temp/1"));
assertThat(matchingSubs1).contains(expectedMatchingsub1);
final Subscription expectedMatchingsub2 = new Subscription("TempSensor1", asTopic("/temp/2"));
assertThat(matchingSubs2).contains(expectedMatchingsub2);
}
@Test
public void givenTreeWithDeepNodeWhenRemoveContainedSubscriptionThenNodeIsUpdated() {
sut.add(clientSubOnTopic("TempSensor1", "/bah/bin/bash"));
sut.removeSubscription(asTopic("/bah/bin/bash"),"TempSensor1");
sut.removeSubscription(asTopic("/bah/bin/bash"), "TempSensor1");
//Verify
final Optional<CNode> matchedNode = sut.lookup(asTopic("/bah/bin/bash"));
assertFalse("Node on path /temp can't be present", matchedNode.isPresent());
}
@Test
public void testMatchSubscriptionNoWildcards() {
sut.add(clientSubOnTopic("TempSensor1", "/temp"));
@@ -237,7 +232,7 @@ public class CTrieSubscriptionDirectoryTest {
public void testRemovalInnerTopicOffRootSameClient() {
sut.add(clientSubOnTopic("TempSensor1", "temp"));
sut.add(clientSubOnTopic("TempSensor1", "temp/1"));
//Exercise
final Set<Subscription> matchingSubs1 = sut.recursiveMatch(asTopic("temp"), sut.root);
final Set<Subscription> matchingSubs2 = sut.recursiveMatch(asTopic("temp/1"), sut.root);
@@ -249,7 +244,7 @@ public class CTrieSubscriptionDirectoryTest {
assertThat(matchingSubs1).contains(expectedMatchingsub1);
assertThat(matchingSubs2).contains(expectedMatchingsub2);
sut.removeSubscription(asTopic("temp"),"TempSensor1");
sut.removeSubscription(asTopic("temp"), "TempSensor1");
//Exercise
final Set<Subscription> matchingSubs3 = sut.recursiveMatch(asTopic("temp"), sut.root);
@@ -275,7 +270,7 @@ public class CTrieSubscriptionDirectoryTest {
assertThat(matchingSubs1).contains(expectedMatchingsub1);
assertThat(matchingSubs2).contains(expectedMatchingsub2);
sut.removeSubscription(asTopic("temp"),"TempSensor1");
sut.removeSubscription(asTopic("temp"), "TempSensor1");
//Exercise
final Set<Subscription> matchingSubs3 = sut.recursiveMatch(asTopic("temp"), sut.root);
@@ -301,7 +296,7 @@ public class CTrieSubscriptionDirectoryTest {
assertThat(matchingSubs1).contains(expectedMatchingsub1);
assertThat(matchingSubs2).contains(expectedMatchingsub2);
sut.removeSubscription(asTopic("temp/1"),"TempSensor2");
sut.removeSubscription(asTopic("temp/1"), "TempSensor2");
//Exercise
final Set<Subscription> matchingSubs3 = sut.recursiveMatch(asTopic("temp"), sut.root);
@@ -311,5 +306,3 @@ public class CTrieSubscriptionDirectoryTest {
assertThat(matchingSubs4).doesNotContain(expectedMatchingsub2);
}
}
@@ -122,7 +122,6 @@ public class TopicTest {
assertEquals(Topic.asTopic("a/b"), Topic.asTopic("/a/b").exceptHeadToken());
}
public static TopicAssert assertThat(Topic topic) {
return new TopicAssert(topic);
}
@@ -25,9 +25,13 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.netty.channel.ChannelFutureListener.CLOSE_ON_FAILURE;
import static io.netty.channel.ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE;
/**
* Class used just to send and receive MQTT messages without any protocol login in action, just use
* the encoder/decoder part.
@@ -52,6 +56,7 @@ public class Client {
this(host, BrokerConstants.PORT);
}
@SuppressWarnings("FutureReturnValueIgnored")
public Client(String host, int port) {
handler.setClient(this);
workerGroup = new NioEventLoopGroup();
@@ -157,7 +162,7 @@ public class Client {
}
public void sendMessage(MqttMessage msg) {
m_channel.writeAndFlush(msg);
m_channel.writeAndFlush(msg).addListener(FIRE_EXCEPTION_ON_FAILURE);
}
public MqttMessage lastReceivedMessage() {
@@ -179,9 +184,10 @@ public class Client {
return m_connectionLost;
}
@SuppressWarnings("FutureReturnValueIgnored")
public void close() throws InterruptedException {
// Wait until the connection is closed.
m_channel.closeFuture().sync();
m_channel.closeFuture().sync().addListener(CLOSE_ON_FAILURE);
if (workerGroup == null) {
throw new IllegalStateException("Invoked close on an Acceptor that wasn't initialized");
}
@@ -24,6 +24,8 @@ import io.netty.handler.codec.mqtt.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.netty.channel.ChannelFutureListener.CLOSE_ON_FAILURE;
@ChannelHandler.Sharable
class ClientNettyMQTTHandler extends ChannelInboundHandlerAdapter {
@@ -38,9 +40,9 @@ class ClientNettyMQTTHandler extends ChannelInboundHandlerAdapter {
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
public void channelInactive(ChannelHandlerContext ctx) {
m_client.setConnectionLost(true);
ctx.close(/* false */);
ctx.close().addListener(CLOSE_ON_FAILURE);
}
void setClient(Client client) {
@@ -32,6 +32,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static io.netty.channel.ChannelFutureListener.CLOSE_ON_FAILURE;
/**
* This class is used to have a fluent interface to interact with a server. Inspired by
* org.kaazing.robot
@@ -55,10 +57,9 @@ public final class RawClient {
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// m_client.setConnectionLost(true);
public void channelInactive(ChannelHandlerContext ctx) {
disconnectLatch.countDown();
ctx.close(/* false */);
ctx.close().addListener(CLOSE_ON_FAILURE);
}
}
@@ -72,6 +73,7 @@ public final class RawClient {
private CountDownLatch disconnectLatch;
private final Semaphore readableBytesSem;
@SuppressWarnings("FutureReturnValueIgnored")
private RawClient(String host, int port) {
handler = new RawMessageHandler();
heapBuffer = Unpooled.buffer(128);
@@ -120,14 +122,14 @@ public final class RawClient {
for (int b : bytes) {
buff.writeByte((byte) b);
}
m_channel.write(buff);
m_channel.write(buff).addListener(CLOSE_ON_FAILURE);
return this;
}
public RawClient writeWithSize(String str) {
ByteBuf buff = Unpooled.buffer(str.length() + 2);
buff.writeBytes(Utils.encodeString(str));
m_channel.write(buff);
m_channel.write(buff).addListener(CLOSE_ON_FAILURE);
return this;
}
@@ -145,7 +147,7 @@ public final class RawClient {
throw new IllegalStateException(ex);
}
out.writeBytes(raw);
m_channel.write(out);
m_channel.write(out).addListener(CLOSE_ON_FAILURE);
return this;
}