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