1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.yaml.snakeyaml.issues.issue139;
17
18 import java.util.List;
19 import java.util.Map;
20
21 import junit.framework.TestCase;
22
23 import org.yaml.snakeyaml.Yaml;
24 import org.yaml.snakeyaml.constructor.Constructor;
25 import org.yaml.snakeyaml.error.YAMLException;
26 import org.yaml.snakeyaml.nodes.MappingNode;
27 import org.yaml.snakeyaml.nodes.Node;
28 import org.yaml.snakeyaml.nodes.NodeTuple;
29
30 public class UniqueKeyTest extends TestCase {
31
32 public void testNotUnique() {
33 String data = "{key: 1, key: 2}";
34 Yaml yaml = new Yaml(new UniqueKeyConstructor());
35 try {
36 yaml.load(data);
37 fail("The same key must be rejected");
38 } catch (Exception e) {
39 assertEquals("The key is not unique key", e.getMessage());
40 }
41 }
42
43 private class UniqueKeyConstructor extends Constructor {
44
45 @Override
46 protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) {
47 List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
48 for (NodeTuple tuple : nodeValue) {
49 Node keyNode = tuple.getKeyNode();
50 Node valueNode = tuple.getValueNode();
51 Object key = constructObject(keyNode);
52 if (key != null) {
53 key.hashCode();
54 }
55 Object value = constructObject(valueNode);
56 Object old = mapping.put(key, value);
57 if (old != null) {
58 throw new YAMLException("The key is not unique " + key);
59 }
60 }
61 }
62 }
63
64 }