67 lines
1.8 KiB
Java
67 lines
1.8 KiB
Java
import java.nio.charset.StandardCharsets;
|
|
|
|
final class MqttTools {
|
|
private MqttTools() {}
|
|
|
|
static boolean isValidTopic(String topic) {
|
|
return hasValidLength(topic)
|
|
&& !topic.contains("+")
|
|
&& !topic.contains("#");
|
|
}
|
|
|
|
static boolean isValidFilter(String filter) {
|
|
if (!hasValidLength(filter))
|
|
return false;
|
|
|
|
var levels = filter.split("/", -1);
|
|
|
|
for (var index = 0; index < levels.length; index++) {
|
|
var level = levels[index];
|
|
|
|
if (level.contains("#")
|
|
&& !(level.equals("#") && index == levels.length - 1))
|
|
return false;
|
|
|
|
if (level.contains("+") && !level.equals("+"))
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
static boolean isTopicMatchingFilter(String topic, String filter) {
|
|
if (!isValidTopic(topic) || !isValidFilter(filter))
|
|
return false;
|
|
|
|
if (topic.startsWith("$") && !filter.startsWith("$"))
|
|
return false;
|
|
|
|
var topicLevels = topic.split("/", -1);
|
|
var filterLevels = filter.split("/", -1);
|
|
var topicIndex = 0;
|
|
|
|
for (var filterLevel : filterLevels) {
|
|
if (filterLevel.equals("#"))
|
|
return true;
|
|
|
|
if (topicIndex == topicLevels.length)
|
|
return false;
|
|
|
|
if (!filterLevel.equals("+")
|
|
&& !filterLevel.equals(topicLevels[topicIndex]))
|
|
return false;
|
|
|
|
topicIndex++;
|
|
}
|
|
|
|
return topicIndex == topicLevels.length;
|
|
}
|
|
|
|
private static boolean hasValidLength(String value) {
|
|
if (value == null || value.isEmpty() || value.contains("\u0000"))
|
|
return false;
|
|
|
|
return value.getBytes(StandardCharsets.UTF_8).length <= 65_535;
|
|
}
|
|
}
|