View Javadoc

1   /**
2    * Copyright (c) 2008-2012, http://www.snakeyaml.org
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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();// check circular dependencies
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  }