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