Merge "Bug 451 - Fix netconf exception handling"
[controller.git] / opendaylight / netconf / config-netconf-connector / src / main / java / org / opendaylight / controller / netconf / confignetconfconnector / mapping / config / Services.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 java.util.List;
12 import java.util.Map;
13 import java.util.Map.Entry;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
16
17 import javax.management.ObjectName;
18
19 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
20 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
21 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
22 import org.opendaylight.controller.netconf.util.xml.XmlElement;
23 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
24 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.w3c.dom.Document;
28 import org.w3c.dom.Element;
29
30 import com.google.common.base.Optional;
31 import com.google.common.base.Preconditions;
32 import com.google.common.collect.Maps;
33
34 public final class Services {
35
36     private static final Logger logger = LoggerFactory.getLogger(Services.class);
37
38     private static final String PROVIDER_KEY = "provider";
39     private static final String NAME_KEY = "name";
40     public static final String TYPE_KEY = "type";
41     public static final String SERVICE_KEY = "service";
42
43     private final Map<String /*Namespace*/, Map<String/* ServiceName */, Map<String/* refName */, ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = Maps
44             .newHashMap();
45
46     /**
47      *
48      */
49     public Map<String, Map<String, Map<String, ServiceInstance>>> getNamespaceToServiceNameToRefNameToInstance() {
50         return namespaceToServiceNameToRefNameToInstance;
51     }
52
53     private static Services resolveServices(Map<String, Map<String, Map<String, String>>> mappedServices) {
54         Services tracker = new Services();
55
56         for (Entry<String, Map<String, Map<String, String>>> namespaceEntry : mappedServices.entrySet()) {
57             String namespace = namespaceEntry.getKey();
58
59             for (Entry<String, Map<String, String>> serviceEntry : namespaceEntry.getValue().entrySet()) {
60
61                 String serviceName = serviceEntry.getKey();
62                 for (Entry<String, String> refEntry : serviceEntry.getValue().entrySet()) {
63
64                     Map<String, Map<String, ServiceInstance>> namespaceToServices = tracker.namespaceToServiceNameToRefNameToInstance.get(namespace);
65                     if (namespaceToServices == null) {
66                         namespaceToServices = Maps.newHashMap();
67                         tracker.namespaceToServiceNameToRefNameToInstance.put(namespace, namespaceToServices);
68                     }
69
70                     Map<String, ServiceInstance> refNameToInstance = namespaceToServices
71                             .get(serviceName);
72                     if (refNameToInstance == null) {
73                         refNameToInstance = Maps.newHashMap();
74                         namespaceToServices.put(serviceName, refNameToInstance);
75                     }
76
77                     String refName = refEntry.getKey();
78
79                     ServiceInstance serviceInstance = ServiceInstance.fromString(refEntry.getValue());
80                     refNameToInstance.put(refName, serviceInstance);
81
82                 }
83             }
84         }
85         return tracker;
86     }
87
88     // TODO support edit strategies on services
89
90     public static Services fromXml(XmlElement xml) throws NetconfDocumentedException {
91         Map<String, Map<String, Map<String, String>>> retVal = Maps.newHashMap();
92
93         List<XmlElement> services = xml.getChildElements(SERVICE_KEY);
94         xml.checkUnrecognisedElements(services);
95
96         for (XmlElement service : services) {
97
98             XmlElement typeElement = service.getOnlyChildElement(TYPE_KEY);
99             Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
100
101             Preconditions.checkState(prefixNamespace.getKey()!=null && prefixNamespace.getKey().equals("") == false, "Type attribute was not prefixed");
102
103             Map<String, Map<String, String>> namespaceToServices = retVal.get(prefixNamespace.getValue());
104             if(namespaceToServices == null) {
105                 namespaceToServices = Maps.newHashMap();
106                 retVal.put(prefixNamespace.getValue(), namespaceToServices);
107             }
108
109             String serviceName =  ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
110
111             Map<String, String> innerMap = Maps.newHashMap();
112             namespaceToServices.put(serviceName, innerMap);
113
114             List<XmlElement> instances = service.getChildElements(XmlNetconfConstants.INSTANCE_KEY);
115             service.checkUnrecognisedElements(instances, typeElement);
116
117             for (XmlElement instance : instances) {
118                 XmlElement nameElement = instance.getOnlyChildElement(NAME_KEY);
119                 String refName = nameElement.getTextContent();
120
121                 XmlElement providerElement = instance.getOnlyChildElement(PROVIDER_KEY);
122                 String providerName = providerElement.getTextContent();
123
124                 instance.checkUnrecognisedElements(nameElement, providerElement);
125
126                 innerMap.put(refName, providerName);
127             }
128         }
129
130         return resolveServices(retVal);
131     }
132
133     public static Element toXml(ServiceRegistryWrapper serviceRegistryWrapper, Document document) {
134         Element root = XmlUtil.createElement(document, XmlNetconfConstants.SERVICES_KEY, Optional.of(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
135
136         Map<String, Map<String, Map<String, String>>> mappedServices = serviceRegistryWrapper.getMappedServices();
137         for (String namespace : mappedServices.keySet()) {
138
139             for (Entry<String, Map<String, String>> serviceEntry : mappedServices.get(namespace).entrySet()) {
140                 Element serviceElement = XmlUtil.createElement(document, SERVICE_KEY, Optional.<String>absent());
141                 root.appendChild(serviceElement);
142
143                 Element typeElement = XmlUtil.createPrefixedTextElement(document, XmlUtil.createPrefixedValue(XmlNetconfConstants.PREFIX, TYPE_KEY), XmlNetconfConstants.PREFIX,
144                         serviceEntry.getKey(), Optional.of(namespace));
145                 serviceElement.appendChild(typeElement);
146
147                 for (Entry<String, String> instanceEntry : serviceEntry.getValue().entrySet()) {
148                     Element instanceElement = XmlUtil.createElement(document, XmlNetconfConstants.INSTANCE_KEY, Optional.<String>absent());
149                     serviceElement.appendChild(instanceElement);
150
151                     Element nameElement = XmlUtil.createTextElement(document, NAME_KEY, instanceEntry.getKey(), Optional.<String>absent());
152                     instanceElement.appendChild(nameElement);
153
154                     Element providerElement = XmlUtil.createTextElement(document, PROVIDER_KEY, instanceEntry.getValue(), Optional.<String>absent());
155                     instanceElement.appendChild(providerElement);
156                 }
157             }
158
159         }
160         return root;
161     }
162
163     public static final class ServiceInstance {
164         public ServiceInstance(String moduleName, String instanceName) {
165             this.moduleName = moduleName;
166             this.instanceName = instanceName;
167         }
168
169         public static ServiceInstance fromString(String instanceId) {
170             instanceId = instanceId.trim();
171             Matcher matcher = p.matcher(instanceId);
172             if(matcher.matches() == false) {
173                 matcher = pDeprecated.matcher(instanceId);
174             }
175
176             Preconditions.checkArgument(matcher.matches(), "Unexpected format for provider, expected " + p.toString()
177                     + " or " + pDeprecated.toString() + " but was " + instanceId);
178
179             String factoryName = matcher.group(1);
180             String instanceName = matcher.group(2);
181             return new ServiceInstance(factoryName, instanceName);
182         }
183
184         private final String moduleName, instanceName;
185         private String serviceName;
186
187         public String getServiceName() {
188             return serviceName;
189         }
190
191         public void setServiceName(String serviceName) {
192             this.serviceName = serviceName;
193         }
194
195         public String getModuleName() {
196             return moduleName;
197         }
198
199         public String getInstanceName() {
200             return instanceName;
201         }
202
203         private static final String blueprint = "/"
204                 + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "["
205                 + XmlNetconfConstants.TYPE_KEY + "='%s']["
206                 + XmlNetconfConstants.NAME_KEY + "='%s']";
207
208         // TODO unify with xpath in RuntimeRpc
209
210         // Previous version of xpath, needs to be supported for backwards compatibility (persisted configs by config-persister)
211         private static final String blueprintRDeprecated = "/" + XmlNetconfConstants.CONFIG_KEY + "/"
212                 + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "\\["
213                 + XmlNetconfConstants.NAME_KEY + "='%s'\\]/" + XmlNetconfConstants.INSTANCE_KEY + "\\["
214                 + XmlNetconfConstants.NAME_KEY + "='%s'\\]";
215
216         private static final String blueprintR = "/"
217                 + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "\\["
218                 + XmlNetconfConstants.TYPE_KEY + "='%s'\\]\\["
219                 + XmlNetconfConstants.NAME_KEY + "='%s'\\]";
220
221         private static final Pattern pDeprecated = Pattern.compile(String.format(blueprintRDeprecated, "(.+)", "(.+)"));
222         private static final Pattern p = Pattern.compile(String.format(blueprintR, "(.+)", "(.+)"));
223
224         @Override
225         public String toString() {
226             return String.format(blueprint, moduleName, instanceName);
227         }
228
229         @Override
230         public int hashCode() {
231             final int prime = 31;
232             int result = 1;
233             result = prime * result + ((instanceName == null) ? 0 : instanceName.hashCode());
234             result = prime * result + ((moduleName == null) ? 0 : moduleName.hashCode());
235             return result;
236         }
237
238         @Override
239         public boolean equals(Object obj) {
240             if (this == obj)
241                 return true;
242             if (obj == null)
243                 return false;
244             if (getClass() != obj.getClass())
245                 return false;
246             ServiceInstance other = (ServiceInstance) obj;
247             if (instanceName == null) {
248                 if (other.instanceName != null)
249                     return false;
250             } else if (!instanceName.equals(other.instanceName))
251                 return false;
252             if (moduleName == null) {
253                 if (other.moduleName != null)
254                     return false;
255             } else if (!moduleName.equals(other.moduleName))
256                 return false;
257             return true;
258         }
259
260         public ObjectName getObjectName(String transactionName) {
261             return ObjectNameUtil.createTransactionModuleON(transactionName, moduleName, instanceName);
262         }
263
264         public static ServiceInstance fromObjectName(ObjectName on) {
265             return new ServiceInstance(ObjectNameUtil.getFactoryName(on), ObjectNameUtil.getInstanceName(on));
266         }
267     }
268
269 }