Skip to content

Commit

Permalink
✨ 优化 topic 检验
Browse files Browse the repository at this point in the history
  • Loading branch information
li-xunhuan committed Aug 30, 2023
1 parent 730868b commit c5924d3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public static void validateTopicFilter(String topicFilter) throws IllegalArgumen
throw new IllegalArgumentException("Mqtt subscribe topicFilter illegal:" + topicFilter);
}
} else if (ch == MqttCodecUtil.TOPIC_WILDCARDS_ONE) {
// 校验: 单独 + 是允许的,判断 + 号前一位是否为 /
if (i > 0 && topicFilterChars[i - 1] != '/') {
// 校验: 单独 + 是允许的,判断 + 号前一位是否为 /,如果有后一位也必须为 /
if ((i > 0 && topicFilterChars[i - 1] != '/') || (i < topicFilterIdxEnd && topicFilterChars[i + 1] != '/')) {
throw new IllegalArgumentException("Mqtt subscribe topicFilter illegal:" + topicFilter);
}
}
Expand Down Expand Up @@ -110,8 +110,8 @@ public static boolean match(String topicFilter, String topicName) {
}
return true;
} else if (ch == MqttCodecUtil.TOPIC_WILDCARDS_ONE) {
// 校验: 单独 + 是允许的,判断 + 号前一位是否为 /
if (i > 0 && topicFilterChars[i - 1] != '/') {
// 校验: 单独 + 是允许的,判断 + 号前一位是否为 /,如果有后一位也必须为 /
if ((i > 0 && topicFilterChars[i - 1] != '/') || (i < topicFilterIdxEnd && topicFilterChars[i + 1] != '/')) {
throw new IllegalArgumentException("Mqtt subscribe topicFilter illegal:" + topicFilter);
}
// 如果 + 是最后一位,判断 topicName 中是否还存在层级 /
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,23 @@ void test2() {
Assertions.assertEquals(s3, s2);
}

@Test
void test3() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
TopicUtil.validateTopicFilter("/iot/test/+a");
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
TopicUtil.validateTopicFilter("/iot/test/a+");
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
TopicUtil.validateTopicFilter("/iot/test/+a/");
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
TopicUtil.validateTopicFilter("/iot/test/a+/");
});
Assertions.assertDoesNotThrow(() -> TopicUtil.validateTopicFilter("+"));
Assertions.assertDoesNotThrow(() -> TopicUtil.validateTopicFilter("/iot/test/+"));
Assertions.assertDoesNotThrow(() -> TopicUtil.validateTopicFilter("/iot/test/+/"));
}

}

0 comments on commit c5924d3

Please sign in to comment.