Fix checkstyle warnings for config-netconf-connector
[controller.git] / opendaylight / netconf / config-netconf-connector / src / main / java / org / opendaylight / controller / netconf / confignetconfconnector / mapping / config / InstanceConfig.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
10
11 import com.google.common.base.Optional;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Maps;
14 import java.util.Date;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import javax.management.ObjectName;
19 import javax.management.openmbean.OpenType;
20 import org.opendaylight.controller.config.util.ConfigRegistryClient;
21 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
22 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
23 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
24 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
25 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
26 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
27 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
28 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
29 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
30 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
31 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.ObjectResolver;
32 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.AttributeWritingStrategy;
33 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
34 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
35 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
36 import org.opendaylight.controller.netconf.util.xml.XmlElement;
37 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.w3c.dom.Document;
41 import org.w3c.dom.Element;
42
43 public final class InstanceConfig {
44     private static final Logger LOG = LoggerFactory.getLogger(InstanceConfig.class);
45
46     private final Map<String, AttributeIfc> yangToAttrConfig;
47     private final String nullableDummyContainerName;
48     private final Map<String, AttributeIfc> jmxToAttrConfig;
49     private final ConfigRegistryClient configRegistryClient;
50
51     public InstanceConfig(ConfigRegistryClient configRegistryClient, Map<String, AttributeIfc> yangNamesToAttributes,
52                           String nullableDummyContainerName) {
53
54         this.yangToAttrConfig = yangNamesToAttributes;
55         this.nullableDummyContainerName = nullableDummyContainerName;
56         this.jmxToAttrConfig = reverseMap(yangNamesToAttributes);
57         this.configRegistryClient = configRegistryClient;
58     }
59
60     private Map<String, Object> getMappedConfiguration(ObjectName on) {
61
62         // TODO make field, mappingStrategies can be instantiated only once
63         Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> mappingStrategies = new ObjectMapper()
64                 .prepareMapping(jmxToAttrConfig);
65
66         Map<String, Object> toXml = Maps.newHashMap();
67
68         for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
69             // Skip children runtime beans as they are mapped by InstanceRuntime
70             if (configDefEntry.getValue() instanceof RuntimeBeanEntry){
71                 continue;
72             }
73             Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
74             try {
75                 AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
76                         .get(configDefEntry.getKey());
77                 Optional<?> a = attributeMappingStrategy.mapAttribute(value);
78                 if (!a.isPresent()){
79                     continue;
80                 }
81                 toXml.put(configDefEntry.getValue().getAttributeYangName(), a.get());
82             } catch (Exception e) {
83                 throw new IllegalStateException("Unable to map value " + value + " to attribute "
84                         + configDefEntry.getKey(), e);
85             }
86         }
87         return toXml;
88     }
89
90     public Element toXml(ObjectName on, String namespace, Document document, Element rootElement) {
91         Map<String, AttributeWritingStrategy> strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document);
92         Map<String, Object> mappedConfig = getMappedConfiguration(on);
93         Element parentElement;
94         if (nullableDummyContainerName != null) {
95             Element dummyElement = XmlUtil.createElement(document, nullableDummyContainerName, Optional.of(namespace));
96             rootElement.appendChild(dummyElement);
97             parentElement = dummyElement;
98         } else {
99             parentElement = rootElement;
100         }
101         for (Entry<String, ?> mappingEntry : mappedConfig.entrySet()) {
102             try {
103                 strats.get(mappingEntry.getKey()).writeElement(parentElement, namespace, mappingEntry.getValue());
104             } catch (Exception e) {
105                 throw new IllegalStateException("Unable to write value " + mappingEntry.getValue() + " for attribute "
106                         + mappingEntry.getValue(), e);
107             }
108         }
109         return rootElement;
110     }
111
112     private void resolveConfiguration(InstanceConfigElementResolved mappedConfig, ServiceRegistryWrapper depTracker) {
113
114         // TODO make field, resolvingStrategies can be instantiated only once
115         Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(
116                 depTracker).prepareResolving(yangToAttrConfig);
117
118         for (Entry<String, AttributeConfigElement> configDefEntry : mappedConfig.getConfiguration().entrySet()) {
119             AttributeConfigElement value = configDefEntry.getValue();
120             String attributeName = configDefEntry.getKey();
121             try {
122                 AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
123                         .get(attributeName);
124                 LOG.trace("Trying to set value {} of attribute {} with {}", value, attributeName, attributeResolvingStrategy);
125
126                 value.resolveValue(attributeResolvingStrategy, attributeName);
127                 value.setJmxName(
128                         yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
129             } catch (Exception e) {
130                 throw new IllegalStateException("Unable to resolve value " + value
131                         + " to attribute " + attributeName, e);
132             }
133         }
134     }
135
136     public InstanceConfigElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper services, String moduleNamespace,
137                                                  EditStrategyType defaultStrategy,
138                                                  Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) throws NetconfDocumentedException {
139         Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
140
141         Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
142         List<XmlElement> recognisedChildren = Lists.newArrayList();
143
144         XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
145         XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
146         List<XmlElement> typeAndNameElements = Lists.newArrayList(typeElement, nameElement);
147
148         // if dummy container was defined in yang, set moduleElement to its content
149         if (nullableDummyContainerName != null) {
150             int size = moduleElement.getChildElements().size();
151             int expectedChildNodes = 1 + typeAndNameElements.size();
152             if (size > expectedChildNodes) {
153                 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
154                         nameElement.getTextContent() + " - Expected " + expectedChildNodes +" child nodes, " +
155                         "one of them with name " + nullableDummyContainerName +
156                         ", got " + size + " elements.");
157             }
158             if (size == expectedChildNodes) {
159                 try {
160                     moduleElement = moduleElement.getOnlyChildElement(nullableDummyContainerName, moduleNamespace);
161                 } catch (NetconfDocumentedException e) {
162                     throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
163                             nameElement.getTextContent() + " - Expected child node with name " + nullableDummyContainerName +
164                             "." + e.getMessage());
165                 }
166             } // else 2 elements, no need to descend
167         }
168
169         for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
170             List<XmlElement> configNodes = getConfigNodes(moduleElement, moduleNamespace, readStratEntry.getKey(),
171                     recognisedChildren, typeAndNameElements);
172             AttributeConfigElement readElement = readStratEntry.getValue().readElement(configNodes);
173             retVal.put(readStratEntry.getKey(), readElement);
174         }
175
176         recognisedChildren.addAll(typeAndNameElements);
177         try {
178             moduleElement.checkUnrecognisedElements(recognisedChildren);
179         } catch (NetconfDocumentedException e) {
180             throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
181                     nameElement.getTextContent() + " - " +
182                     e.getMessage(), e.getErrorType(), e.getErrorTag(),e.getErrorSeverity(),e.getErrorInfo());
183         }
184         // TODO: add check for conflicts between global and local edit strategy
185         String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
186                 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
187
188         InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("") ? new InstanceConfigElementResolved(
189                 retVal, defaultStrategy) : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
190
191         resolveConfiguration(instanceConfigElementResolved, services);
192         return instanceConfigElementResolved;
193     }
194
195     private List<XmlElement> getConfigNodes(XmlElement moduleElement, String moduleNamespace, String name,
196             List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws NetconfDocumentedException {
197         List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
198         if (foundConfigNodes.isEmpty()) {
199             LOG.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
200             LOG.debug("Trying lookup of config nodes without specified namespace");
201             foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name,
202                     XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
203             // In case module type or name element is not present in config it
204             // would be matched with config type or name
205             // We need to remove config type and name from available module
206             // config elements
207             foundConfigNodes.removeAll(typeAndName);
208             LOG.debug("Found {} config nodes {} without specified namespace in {}", foundConfigNodes.size(), name,
209                     moduleElement);
210         } else {
211             List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
212                     XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
213             foundWithoutNamespaceNodes.removeAll(typeAndName);
214             if (!foundWithoutNamespaceNodes.isEmpty()){
215                 throw new NetconfDocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
216                         foundWithoutNamespaceNodes),
217                         NetconfDocumentedException.ErrorType.application,
218                         NetconfDocumentedException.ErrorTag.invalid_value,
219                         NetconfDocumentedException.ErrorSeverity.error);
220             }
221         }
222
223         recognisedChildren.addAll(foundConfigNodes);
224         return foundConfigNodes;
225     }
226
227     private static Map<String, AttributeIfc> reverseMap(Map<String, AttributeIfc> yangNameToAttr) {
228         Map<String, AttributeIfc> reversednameToAtr = Maps.newHashMap();
229
230         for (Entry<String, AttributeIfc> entry : yangNameToAttr.entrySet()) {
231             reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue());
232         }
233
234         return reversednameToAtr;
235     }
236
237 }