diff --git a/common/src/main/java/org/apache/rocketmq/common/TopicConfig.java b/common/src/main/java/org/apache/rocketmq/common/TopicConfig.java index 18389b58191..c8a4af09d59 100644 --- a/common/src/main/java/org/apache/rocketmq/common/TopicConfig.java +++ b/common/src/main/java/org/apache/rocketmq/common/TopicConfig.java @@ -111,29 +111,38 @@ public String encode() { public boolean decode(final String in) { String[] strs = in.split(SEPARATOR); - if (strs.length >= 5) { - this.topicName = strs[0]; - - this.readQueueNums = Integer.parseInt(strs[1]); - - this.writeQueueNums = Integer.parseInt(strs[2]); - - this.perm = Integer.parseInt(strs[3]); + if (strs.length < 5) { + return false; + } - this.topicFilterType = TopicFilterType.valueOf(strs[4]); + int decodedReadQueueNums; + int decodedWriteQueueNums; + int decodedPerm; + TopicFilterType decodedFilterType; + try { + decodedReadQueueNums = Integer.parseInt(strs[1]); + decodedWriteQueueNums = Integer.parseInt(strs[2]); + decodedPerm = Integer.parseInt(strs[3]); + decodedFilterType = TopicFilterType.valueOf(strs[4]); + } catch (IllegalArgumentException e) { + return false; + } - if (strs.length >= 6) { - try { - this.attributes = JSON.parseObject(strs[5], ATTRIBUTES_TYPE_REFERENCE.getType()); - } catch (Exception e) { - // ignore exception when parse failed, cause map's key/value can have ' ' char. - } + this.topicName = strs[0]; + this.readQueueNums = decodedReadQueueNums; + this.writeQueueNums = decodedWriteQueueNums; + this.perm = decodedPerm; + this.topicFilterType = decodedFilterType; + + if (strs.length >= 6) { + try { + this.attributes = JSON.parseObject(strs[5], ATTRIBUTES_TYPE_REFERENCE.getType()); + } catch (Exception e) { + // ignore exception when parse failed, cause map's key/value can have ' ' char. } - - return true; } - return false; + return true; } public String getTopicName() { diff --git a/common/src/test/java/org/apache/rocketmq/common/TopicConfigTest.java b/common/src/test/java/org/apache/rocketmq/common/TopicConfigTest.java index 3df93a0bfb3..ca4c6736d89 100644 --- a/common/src/test/java/org/apache/rocketmq/common/TopicConfigTest.java +++ b/common/src/test/java/org/apache/rocketmq/common/TopicConfigTest.java @@ -75,4 +75,16 @@ public void testDecodeWhenCompatible() { assertThat(decodeTopicConfig).isEqualTo(topicConfig); } -} \ No newline at end of file + + @Test + public void testDecodeMalformedConfigDoesNotMutateState() { + TopicConfig topicConfig = new TopicConfig("original", 4, 4, perm); + + boolean decoded = topicConfig.decode("changed invalid 8 6 SINGLE_TAG"); + + assertThat(decoded).isFalse(); + assertThat(topicConfig.getTopicName()).isEqualTo("original"); + assertThat(topicConfig.getReadQueueNums()).isEqualTo(4); + assertThat(topicConfig.getWriteQueueNums()).isEqualTo(4); + } +}