1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.yaml.snakeyaml.issues.issue97;
18
19 import java.util.Collection;
20 import java.util.Set;
21 import java.util.SortedSet;
22 import java.util.TreeSet;
23
24 import junit.framework.Assert;
25 import junit.framework.TestCase;
26
27 import org.yaml.snakeyaml.Yaml;
28 import org.yaml.snakeyaml.constructor.Constructor;
29 import org.yaml.snakeyaml.error.YAMLException;
30 import org.yaml.snakeyaml.introspector.BeanAccess;
31 import org.yaml.snakeyaml.nodes.Node;
32 import org.yaml.snakeyaml.nodes.NodeId;
33 import org.yaml.snakeyaml.nodes.SequenceNode;
34
35 public class YamlSortedSetTest extends TestCase {
36 public void testYaml() {
37 String serialized = "!!org.yaml.snakeyaml.issues.issue97.Blog\n" + "posts:\n"
38 + " - text: Dummy\n" + " title: Test\n" + " - text: Creative\n"
39 + " title: Highly\n";
40
41 Yaml yaml2 = constructYamlParser();
42 Blog rehydrated = (Blog) yaml2.load(serialized);
43 checkTestBlog(rehydrated);
44 }
45
46 protected Yaml constructYamlParser() {
47 Yaml yaml = new Yaml(new SetContructor());
48 yaml.setBeanAccess(BeanAccess.FIELD);
49 return yaml;
50 }
51
52 protected void checkTestBlog(Blog blog) {
53 Set<Post> posts = blog.getPosts();
54 Assert.assertEquals("Blog contains 2 posts", 2, posts.size());
55 }
56
57 private class SetContructor extends Constructor {
58 public SetContructor() {
59 yamlClassConstructors.put(NodeId.sequence, new ConstructSetFromSequence());
60 }
61
62 private class ConstructSetFromSequence extends ConstructSequence {
63 @Override
64 public Object construct(Node node) {
65 if (SortedSet.class.isAssignableFrom(node.getType())) {
66 if (node.isTwoStepsConstruction()) {
67 throw new YAMLException("Set cannot be recursive.");
68 } else {
69 Collection<Object> result = new TreeSet<Object>();
70 SetContructor.this.constructSequenceStep2((SequenceNode) node, result);
71 return result;
72 }
73 } else {
74 return super.construct(node);
75 }
76 }
77 }
78 }
79 }