678ba007240ef858b552794ad4b6aac9ef12029a
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.sdc.tosca.services;
21
22 import java.util.AbstractMap;
23 import java.util.Map;
24 import java.util.Set;
25 import org.yaml.snakeyaml.constructor.Constructor;
26 import org.yaml.snakeyaml.nodes.MappingNode;
27 import org.yaml.snakeyaml.parser.ParserException;
28
29 public class StrictMapAppenderConstructor extends Constructor {
30
31     /**
32      * Instantiates a new Strict map appender constructor.
33      *
34      * @param theRoot the the root
35      */
36     public StrictMapAppenderConstructor(Class<?> theRoot) {
37         super(theRoot);
38     }
39
40     @Override
41     protected Map<Object, Object> createDefaultMap(int initSize) {
42         final Map<Object, Object> delegate = super.createDefaultMap(initSize);
43         return new AbstractMap<>() {
44             @Override
45             public Object put(Object key, Object value) {
46                 if (delegate.containsKey(key)) {
47                     throw new IllegalStateException("duplicate key: " + key);
48                 }
49                 return delegate.put(key, value);
50             }
51
52             @Override
53             public Set<Entry<Object, Object>> entrySet() {
54                 return delegate.entrySet();
55             }
56         };
57     }
58
59     @Override
60     protected Map<Object, Object> constructMapping(MappingNode node) {
61         try {
62             return super.constructMapping(node);
63         } catch (IllegalStateException exception) {
64             throw new ParserException("while parsing MappingNode", node.getStartMark(), exception.getMessage(), node.getEndMark());
65         }
66     }
67 }