Minor, just code layout

This commit is contained in:
andsel
2017-03-20 21:58:18 +01:00
parent 22b1fa2b0e
commit c659a54158
@@ -19,7 +19,6 @@ package io.moquette.spi.impl;
import io.moquette.interception.InterceptHandler;
import io.moquette.interception.messages.InterceptAcknowledgedMessage;
import io.moquette.server.ConnectionDescriptor;
import io.moquette.server.ConnectionDescriptor.ConnectionState;
import io.moquette.server.ConnectionDescriptorStore;
import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.*;
@@ -50,6 +49,7 @@ import static io.moquette.spi.impl.Utils.readBytesAndRewind;
import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.*;
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
import static io.netty.handler.codec.mqtt.MqttQoS.*;
import static io.moquette.server.ConnectionDescriptor.ConnectionState.*;
/**
* Class responsible to handle the logic of MQTT protocol it's the director of the protocol
@@ -160,47 +160,22 @@ public class ProtocolProcessor {
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
BrokerInterceptor interceptor) {
init(
subscriptions,
storageService,
sessionsStore,
authenticator,
allowAnonymous,
false,
authorizator,
interceptor,
null);
init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, false, authorizator,
interceptor, null);
}
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor) {
init(
subscriptions,
storageService,
sessionsStore,
authenticator,
allowAnonymous,
allowZeroByteClientId,
authorizator,
interceptor,
null);
init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, allowZeroByteClientId,
authorizator, interceptor, null);
}
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
init(
new ConnectionDescriptorStore(sessionsStore),
subscriptions,
storageService,
sessionsStore,
authenticator,
allowAnonymous,
allowZeroByteClientId,
authorizator,
interceptor,
serverPort);
init(new ConnectionDescriptorStore(sessionsStore), subscriptions, storageService, sessionsStore, authenticator,
allowAnonymous, allowZeroByteClientId, authorizator, interceptor, serverPort);
}
/**
@@ -243,36 +218,16 @@ public class ProtocolProcessor {
LOG.info("Initializing messages publisher...");
final PersistentQueueMessageSender messageSender = new PersistentQueueMessageSender(this.connectionDescriptors);
this.messagesPublisher = new MessagesPublisher(
connectionDescriptors,
sessionsStore,
m_messagesStore,
this.messagesPublisher = new MessagesPublisher(connectionDescriptors, sessionsStore, m_messagesStore,
messageSender);
LOG.info("Initializing QoS publish handlers...");
this.qos0PublishHandler = new Qos0PublishHandler(
m_authorizator,
subscriptions,
m_messagesStore,
m_interceptor,
this.messagesPublisher);
this.qos1PublishHandler = new Qos1PublishHandler(
m_authorizator,
subscriptions,
m_messagesStore,
m_interceptor,
this.connectionDescriptors,
m_server_port,
this.messagesPublisher);
this.qos2PublishHandler = new Qos2PublishHandler(
m_authorizator,
subscriptions,
m_messagesStore,
m_interceptor,
this.connectionDescriptors,
m_sessionsStore,
m_server_port,
this.qos0PublishHandler = new Qos0PublishHandler(m_authorizator, subscriptions, m_messagesStore, m_interceptor,
this.messagesPublisher);
this.qos1PublishHandler = new Qos1PublishHandler(m_authorizator, subscriptions, m_messagesStore, m_interceptor,
this.connectionDescriptors, m_server_port, this.messagesPublisher);
this.qos2PublishHandler = new Qos2PublishHandler(m_authorizator, subscriptions, m_messagesStore, m_interceptor,
this.connectionDescriptors, m_sessionsStore, m_server_port, this.messagesPublisher);
LOG.info("Initializing internal republisher...");
this.internalRepublisher = new InternalRepublisher(messageSender);
@@ -287,7 +242,7 @@ public class ProtocolProcessor {
&& msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) {
MqttConnAckMessage badProto = connAck(CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION);
LOG.error("The MQTT protocol version is not valid. CId = {}", clientId);
LOG.error("MQTT protocol version is not valid. CId={}", clientId);
channel.writeAndFlush(badProto);
channel.close();
return;
@@ -305,9 +260,7 @@ public class ProtocolProcessor {
// Generating client id.
clientId = UUID.randomUUID().toString().replace("-", "");
LOG.info(
"The client has connected with a server generated identifier. CId = {}, username = {}",
clientId,
LOG.info("Client has connected with a server generated identifier. CId={}, username={}", clientId,
payload.userName());
}
@@ -316,9 +269,7 @@ public class ProtocolProcessor {
return;
}
ConnectionDescriptor descriptor = new ConnectionDescriptor(
clientId,
channel,
ConnectionDescriptor descriptor = new ConnectionDescriptor(clientId, channel,
msg.variableHeader().isCleanSession());
ConnectionDescriptor existing = this.connectionDescriptors.addConnection(descriptor);
if (existing != null) {
@@ -328,9 +279,7 @@ public class ProtocolProcessor {
}
initializeKeepAliveTimeout(channel, msg, clientId);
storeWillMessage(msg, clientId);
if (!sendAck(descriptor, msg, clientId)) {
channel.close();
return;
@@ -348,8 +297,7 @@ public class ProtocolProcessor {
channel.close();
return;
}
final boolean success = descriptor
.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED);
final boolean success = descriptor.assignState(MESSAGES_REPUBLISHED, ESTABLISHED);
if (!success) {
channel.close();
}
@@ -366,12 +314,8 @@ public class ProtocolProcessor {
}
private MqttConnAckMessage connAck(MqttConnectReturnCode returnCode, boolean sessionPresent) {
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
MqttMessageType.CONNACK,
false,
MqttQoS.AT_MOST_ONCE,
false,
0);
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE,
false, 0);
MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(returnCode, sessionPresent);
return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader);
}
@@ -383,26 +327,19 @@ public class ProtocolProcessor {
if (msg.variableHeader().hasPassword()) {
pwd = msg.payload().password().getBytes();
} else if (!this.allowAnonymous) {
LOG.error(
"The client didn't supply any password and MQTT anonymous mode is disabled. CId = {}.",
clientId);
LOG.error("Client didn't supply any password and MQTT anonymous mode is disabled CId={}", clientId);
failedCredentials(channel);
return false;
}
if (!m_authenticator.checkValid(clientId, msg.payload().userName(), pwd)) {
LOG.error(
"The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.",
clientId,
msg.payload().userName(),
pwd);
LOG.error("Authenticator has rejected the MQTT credentials CId={}, username={}, password={}",
clientId, msg.payload().userName(), pwd);
failedCredentials(channel);
return false;
}
NettyUtils.userName(channel, msg.payload().userName());
} else if (!this.allowAnonymous) {
LOG.error(
"The client didn't supply any credentials and MQTT anonymous mode is disabled. CId = {}.",
clientId);
LOG.error("Client didn't supply any credentials and MQTT anonymous mode is disabled. CId={}", clientId);
failedCredentials(channel);
return false;
}
@@ -411,7 +348,7 @@ public class ProtocolProcessor {
private boolean sendAck(ConnectionDescriptor descriptor, MqttConnectMessage msg, final String clientId) {
LOG.info("Sending connect ACK. CId={}.", clientId);
final boolean success = descriptor.assignState(ConnectionState.DISCONNECTED, ConnectionState.SENDACK);
final boolean success = descriptor.assignState(DISCONNECTED, SENDACK);
if (!success) {
return false;
}
@@ -446,32 +383,20 @@ public class ProtocolProcessor {
int idleTime = Math.round(keepAlive * 1.5f);
setIdleTime(channel.pipeline(), idleTime);
LOG.info(
"The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.",
clientId,
keepAlive,
msg.variableHeader().isCleanSession(),
idleTime);
LOG.debug("The connection has been configured CId={}, keepAlive={}, cleanSession={}, idleTime={}",
clientId, keepAlive, msg.variableHeader().isCleanSession(), idleTime);
}
private void storeWillMessage(MqttConnectMessage msg, final String clientId) {
// Handle will flag
if (msg.variableHeader().isWillFlag()) {
MqttQoS willQos = MqttQoS.valueOf(msg.variableHeader().willQos());
LOG.info(
"Configuring MQTT last will and testament. "
+ "CId = {}, willQos = {}, willTopic = {}, willRetain = {}.",
clientId,
willQos,
msg.payload().willTopic(),
msg.variableHeader().isWillRetain());
LOG.info("Configuring MQTT last will and testament CId={}, willQos={}, willTopic={}, willRetain={}",
clientId, willQos, msg.payload().willTopic(), msg.variableHeader().isWillRetain());
byte[] willPayload = msg.payload().willMessage().getBytes();
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(willPayload.length).put(willPayload).flip();
// save the will testament in the clientID store
WillMessage will = new WillMessage(
msg.payload().willTopic(),
bb,
msg.variableHeader().isWillRetain(),
WillMessage will = new WillMessage(msg.payload().willTopic(), bb, msg.variableHeader().isWillRetain(),
willQos);
m_willStore.put(clientId, will);
LOG.info("MQTT last will and testament has been configured. CId={}.", clientId);
@@ -480,7 +405,7 @@ public class ProtocolProcessor {
private ClientSession createOrLoadClientSession(ConnectionDescriptor descriptor, MqttConnectMessage msg,
String clientId) {
final boolean success = descriptor.assignState(ConnectionState.SENDACK, ConnectionState.SESSION_CREATED);
final boolean success = descriptor.assignState(SENDACK, SESSION_CREATED);
if (!success) {
return null;
}
@@ -498,8 +423,7 @@ public class ProtocolProcessor {
}
private boolean republish(ConnectionDescriptor descriptor, MqttConnectMessage msg, ClientSession clientSession) {
final boolean success = descriptor
.assignState(ConnectionState.SESSION_CREATED, ConnectionState.MESSAGES_REPUBLISHED);
final boolean success = descriptor.assignState(SESSION_CREATED, MESSAGES_REPUBLISHED);
if (!success) {
return false;
}
@@ -558,19 +482,15 @@ public class ProtocolProcessor {
ByteBuf payload = msg.payload();
byte[] payloadContent = readBytesAndRewind(payload);
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(
payloadContent,
msg.fixedHeader().qosLevel(),
msg.variableHeader().topicName());
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(payloadContent,
msg.fixedHeader().qosLevel(), msg.variableHeader().topicName());
stored.setRetained(msg.fixedHeader().isRetain());
stored.setMessageID(msg.variableHeader().messageId());
return stored;
}
private static IMessagesStore.StoredMessage asStoredMessage(WillMessage will) {
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(
will.getPayload().array(),
will.getQos(),
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(will.getPayload().array(), will.getQos(),
will.getTopic());
pub.setRetained(will.isRetained());
return pub;
@@ -579,12 +499,8 @@ public class ProtocolProcessor {
public void processPublish(Channel channel, MqttPublishMessage msg) {
final MqttQoS qos = msg.fixedHeader().qosLevel();
final String clientId = NettyUtils.clientID(channel);
LOG.info(
"Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.",
clientId,
msg.variableHeader().topicName(),
msg.variableHeader().messageId(),
qos);
LOG.info("Processing PUBLISH message. CId={}, topic={}, messageId={}, qos={}", clientId,
msg.variableHeader().topicName(), msg.variableHeader().messageId(), qos);
switch (qos) {
case AT_MOST_ONCE:
this.qos0PublishHandler.receivedPublishQos0(channel, msg);
@@ -765,8 +681,7 @@ public class ProtocolProcessor {
}
private boolean removeSubscriptions(ConnectionDescriptor descriptor, String clientID) {
final boolean success = descriptor
.assignState(ConnectionState.ESTABLISHED, ConnectionState.SUBSCRIPTIONS_REMOVED);
final boolean success = descriptor.assignState(ESTABLISHED, SUBSCRIPTIONS_REMOVED);
if (!success) {
return false;
}
@@ -780,8 +695,7 @@ public class ProtocolProcessor {
}
private boolean dropStoredMessages(ConnectionDescriptor descriptor, String clientID) {
final boolean success = descriptor
.assignState(ConnectionState.SUBSCRIPTIONS_REMOVED, ConnectionState.MESSAGES_DROPPED);
final boolean success = descriptor.assignState(SUBSCRIPTIONS_REMOVED, MESSAGES_DROPPED);
if (!success) {
return false;
}
@@ -795,8 +709,7 @@ public class ProtocolProcessor {
}
private boolean cleanWillMessageAndNotifyInterceptor(ConnectionDescriptor descriptor, String clientID) {
final boolean success = descriptor
.assignState(ConnectionState.MESSAGES_DROPPED, ConnectionState.INTERCEPTORS_NOTIFIED);
final boolean success = descriptor.assignState(MESSAGES_DROPPED, INTERCEPTORS_NOTIFIED);
if (!success) {
return false;
}
@@ -846,10 +759,7 @@ public class ProtocolProcessor {
if (!validTopic) {
// close the connection, not valid topicFilter is a protocol violation
channel.close();
LOG.error(
"The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.",
clientID,
topics,
LOG.error( "Topic filter is not valid. CId={}, topics={}, badTopicFilter={}", clientID, topics,
topic);
return;
}
@@ -879,22 +789,16 @@ public class ProtocolProcessor {
SubscriptionState currentStatus = this.subscriptionInCourse
.putIfAbsent(executionKey, SubscriptionState.VERIFIED);
if (currentStatus != null) {
LOG.warn(
"The client sent another SUBSCRIBE message while this one was being processed. "
+ "CId = {}, messageId = {}.",
clientID,
messageID);
LOG.warn("Client sent another SUBSCRIBE message while this one was being processed " +
"CId={}, messageId={}", clientID, messageID);
return;
}
String username = NettyUtils.userName(channel);
List<MqttTopicSubscription> ackTopics = doVerify(clientID, username, msg);
MqttSubAckMessage ackMessage = doAckMessageFromValidateFilters(ackTopics, messageID);
if (!this.subscriptionInCourse.replace(executionKey, SubscriptionState.VERIFIED, SubscriptionState.STORED)) {
LOG.warn(
"The client sent another SUBSCRIBE message while the topic filters were being verified. "
+ "CId = {}, messageId = {}.",
clientID,
messageID);
LOG.warn("Client sent another SUBSCRIBE message while the topic filters were being verified " +
"CId={}, messageId={}", clientID, messageID);
return;
}
@@ -903,7 +807,6 @@ public class ProtocolProcessor {
List<Subscription> newSubscriptions = doStoreSubscription(ackTopics, clientID);
// save session, persist subscriptions from session
for (Subscription subscription : newSubscriptions) {
subscriptions.add(subscription.asClientTopicCouple());
}
@@ -958,32 +861,19 @@ public class ProtocolProcessor {
Topic topic = new Topic(req.topicName());
if (!m_authorizator.canRead(topic, username, clientSession.clientID)) {
// send SUBACK with 0x80, the user hasn't credentials to read the topic
LOG.error(
"The client does not have read permissions on the topic. "
+ "CId = {}, username = {}, messageId = {}, topic = {}.",
clientID,
username,
messageId,
topic);
LOG.error("Client does not have read permissions on the topic " +
"CId={}, username={}, messageId={}, topic={}",
clientID, username, messageId, topic);
ackTopics.add(new MqttTopicSubscription(topic.toString(), FAILURE));
} else {
MqttQoS qos;
if (topic.isValid()) {
LOG.info(
"The client will be subscribed to the topic. "
+ "CId = {}, username = {}, messageId = {}, topic = {}.",
clientID,
username,
messageId,
topic);
LOG.info("Client will be subscribed to the topic " +
"CId={}, username={}, messageId={}, topic={}", clientID, username, messageId, topic);
qos = req.qualityOfService();
} else {
LOG.error(
"The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.",
clientID,
username,
messageId,
topic);
LOG.error("Topic filter is not valid CId={}, username={}, messageId={}, topic={}",
clientID, username, messageId, topic);
qos = FAILURE;
}
ackTopics.add(new MqttTopicSubscription(topic.toString(), qos));
@@ -1007,9 +897,7 @@ public class ProtocolProcessor {
}
private void publishRetainedMessagesInSession(final Subscription newSubscription, String username) {
LOG.info(
"Retrieving retained messages. CId = {}, topics = {}.",
newSubscription.getClientId(),
LOG.info("Retrieving retained messages CId={}, topics={}", newSubscription.getClientId(),
newSubscription.getTopicFilter());
// scans retained messages to be published to the new subscription
@@ -1023,11 +911,8 @@ public class ProtocolProcessor {
});
if (!messages.isEmpty()) {
LOG.info(
"Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter(),
messages.size());
LOG.info("Publishing retained messages CId={}, topics={}, messagesNo={}",
newSubscription.getClientId(), newSubscription.getTopicFilter(), messages.size());
}
ClientSession targetSession = m_sessionsStore.sessionForClient(newSubscription.getClientId());
this.internalRepublisher.publishRetained(targetSession, messages);
@@ -1047,12 +932,8 @@ public class ProtocolProcessor {
} else {
// recreate a publish from stored publish in queue
boolean retained = m_messagesStore.getMessageByGuid(msg.getGuid()) != null;
MqttPublishMessage pubMsg = createPublishForQos(
msg.getTopic(),
msg.getQos(),
msg.getMessage(),
retained,
0);
MqttPublishMessage pubMsg = createPublishForQos( msg.getTopic(), msg.getQos(), msg.getMessage(),
retained, 0);
channel.write(pubMsg);
}
}