Topic { public static Topic parse(String topic) { List<Level> levels = new ArrayList<>(); Set<String> labels = new HashSet<>(); for (String level : topic.split("/")) { if (level.contains("#") || level.contains("+")) { throw new TopicSyntaxException(format( "Wildcard levels are not allowed in MQTT topics. Found `%s` in `%s`", level, topic)); } else if (level.startsWith("{") && level.endsWith("}")) { String label = level.substring(1, level.length() - 1); if (!LABEL_PATTERN.matcher(label).matches()) { throw new TopicSyntaxException(format( "Invalid topic label name `%s` found in `%s`", label, topic)); } else if (labels.contains(label)) { throw new TopicSyntaxException(format("Duplicate topic label `%s` found in `%s`", label, topic)); } labels.add(label); levels.add(new Level(label, true)); } else if (level.contains("{") || level.contains("}")) { throw new TopicSyntaxException(format( "Topic labels must span an entire level. Found `%s` in `%s`", level, topic)); } else { levels.add(new Level(level, false)); } } return new Topic(topic, levels); } private  Topic(String topic, List<Level> levels); static Topic parse(String topic); List<Level> getLevels(); List<Level> getLabels(); boolean hasLabel(String label); boolean conflictsWith(Topic other); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode();  }
@Test public void requiresThatLabelsSpanWholeLevel() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/{baz}bam")); }
@Test public void requiresThatLabelsContainOneCharacter() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/{}")); }
@Test public void requiresThatLabelsContainValidCharacters() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/{nope nope}")); }
@Test public void doesNotAllowDuplicateLabels() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/{nope}/{nope}")); }
@Test public void doesNotSupportSingleLevelWildCards() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/+/nope")); }
@Test public void doesNotSupportMultiLevelWildCards() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/nope/#")); }
@Test public void detectsLabelSyntaxError() { assertThrows(TopicSyntaxException.class, () -> Topic.parse("foo/bar/nope/}")); }
@Test public void topicEquality() { Topic topic1 = Topic.parse("foo/bar"); Topic topic2 = Topic.parse("foo/{bar}"); assertThat(topic1, equalTo(topic1)); assertThat(topic1, not(equalTo(topic2))); assertThat(topic1, not(equalTo(null))); }