1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.yaml.snakeyaml.issues.issue60;
18
19 import java.util.Arrays;
20
21 import junit.framework.TestCase;
22
23 import org.yaml.snakeyaml.Util;
24 import org.yaml.snakeyaml.Yaml;
25 import org.yaml.snakeyaml.introspector.Property;
26 import org.yaml.snakeyaml.nodes.CollectionNode;
27 import org.yaml.snakeyaml.nodes.MappingNode;
28 import org.yaml.snakeyaml.nodes.Node;
29 import org.yaml.snakeyaml.nodes.NodeTuple;
30 import org.yaml.snakeyaml.nodes.SequenceNode;
31 import org.yaml.snakeyaml.nodes.Tag;
32 import org.yaml.snakeyaml.representer.Representer;
33
34 public class SkipBeanTest extends TestCase {
35
36 public void testSkipNull() {
37 Yaml yaml = new Yaml(new SkipNullRepresenter());
38 String output = yaml.dump(getBean());
39
40 assertEquals(Util.getLocalResource("issues/issue60-1.yaml"), output);
41 }
42
43 private class SkipNullRepresenter extends Representer {
44 @Override
45 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
46 Object propertyValue, Tag customTag) {
47 if (propertyValue == null) {
48 return null;
49 } else {
50 return super
51 .representJavaBeanProperty(javaBean, property, propertyValue, customTag);
52 }
53 }
54 }
55
56 public void testSkipEmptyCollections() {
57 Yaml yaml = new Yaml(new SkipEmptyRepresenter());
58 String output = yaml.dump(getBean());
59
60 assertEquals(Util.getLocalResource("issues/issue60-2.yaml"), output);
61 }
62
63 private class SkipEmptyRepresenter extends Representer {
64 @Override
65 protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
66 Object propertyValue, Tag customTag) {
67 NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue,
68 customTag);
69 Node valueNode = tuple.getValueNode();
70 if (Tag.NULL.equals(valueNode.getTag())) {
71 return null;
72 }
73 if (valueNode instanceof CollectionNode) {
74 if (Tag.SEQ.equals(valueNode.getTag())) {
75 SequenceNode seq = (SequenceNode) valueNode;
76 if (seq.getValue().isEmpty()) {
77 return null;
78 }
79 }
80 if (Tag.MAP.equals(valueNode.getTag())) {
81 MappingNode seq = (MappingNode) valueNode;
82 if (seq.getValue().isEmpty()) {
83 return null;
84 }
85 }
86 }
87 return tuple;
88 }
89 }
90
91 private SkipBean getBean() {
92 SkipBean bean = new SkipBean();
93 bean.setText("foo");
94 bean.setListDate(null);
95 bean.setListInt(Arrays.asList(new Integer[] { null, 1, 2, 3 }));
96 bean.setListStr(Arrays.asList(new String[] { "bar", null, "foo", null }));
97 return bean;
98 }
99 }