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