1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.yaml.snakeyaml.representer;
17
18 import junit.framework.TestCase;
19
20 import org.yaml.snakeyaml.Yaml;
21 import org.yaml.snakeyaml.constructor.AbstractConstruct;
22 import org.yaml.snakeyaml.constructor.Constructor;
23 import org.yaml.snakeyaml.nodes.Node;
24 import org.yaml.snakeyaml.nodes.ScalarNode;
25 import org.yaml.snakeyaml.nodes.Tag;
26
27 public class RepresentTest extends TestCase {
28
29 public void testCustomRepresenter() {
30 Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter());
31 CustomBean etalon = new CustomBean("A", 1);
32 String output = yaml.dump(etalon);
33 assertEquals("!!Dice 'Ad1'\n", output);
34 CustomBean bean = (CustomBean) yaml.load(output);
35 assertEquals("A", bean.getPrefix());
36 assertEquals(1, bean.getSuffix());
37 assertEquals(etalon, bean);
38 }
39
40 class CustomBean {
41 private String prefix;
42 private int suffix;
43
44 public CustomBean(String prefix, int suffix) {
45 this.prefix = prefix;
46 this.suffix = suffix;
47 }
48
49 public String getPrefix() {
50 return prefix;
51 }
52
53 public int getSuffix() {
54 return suffix;
55 }
56
57 @Override
58 public boolean equals(Object obj) {
59 CustomBean bean = (CustomBean) obj;
60 return prefix.equals(bean.getPrefix()) && suffix == bean.getSuffix();
61 }
62 }
63
64 class MyRepresenter extends Representer {
65 public MyRepresenter() {
66 this.representers.put(CustomBean.class, new RepresentDice());
67 }
68
69 private class RepresentDice implements Represent {
70 public Node representData(Object data) {
71 CustomBean coin = (CustomBean) data;
72 String value = coin.getPrefix() + "d" + coin.getSuffix();
73 return representScalar(new Tag("!!Dice"), value);
74 }
75 }
76 }
77
78 class MyConstructor extends Constructor {
79 public MyConstructor() {
80 this.yamlConstructors.put(new Tag(Tag.PREFIX + "Dice"), new ConstructDice());
81 }
82
83 private class ConstructDice extends AbstractConstruct {
84 public Object construct(Node node) {
85 String val = (String) constructScalar((ScalarNode) node);
86 return new CustomBean(val.substring(0, 1), new Integer(val.substring(2)));
87 }
88 }
89 }
90 }