Merge "One more fix to pass release-prepareonly"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / ControllerContext.xtend
1 package org.opendaylight.controller.sal.restconf.impl
2
3 import com.google.common.base.Preconditions
4 import com.google.common.collect.BiMap
5 import com.google.common.collect.FluentIterable
6 import com.google.common.collect.HashBiMap
7 import java.net.URI
8 import java.net.URLDecoder
9 import java.net.URLEncoder
10 import java.util.ArrayList
11 import java.util.HashMap
12 import java.util.List
13 import java.util.Map
14 import java.util.concurrent.ConcurrentHashMap
15 import org.opendaylight.controller.sal.core.api.mount.MountInstance
16 import org.opendaylight.controller.sal.core.api.mount.MountService
17 import org.opendaylight.controller.sal.rest.impl.RestUtil
18 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
19 import org.opendaylight.yangtools.yang.common.QName
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
23 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
24 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
25 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
26 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
27 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
34 import org.opendaylight.yangtools.yang.model.api.Module
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext
37 import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener
38 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
39 import org.slf4j.LoggerFactory
40
41 import static com.google.common.base.Preconditions.*
42 import static javax.ws.rs.core.Response.Status.*
43
44 class ControllerContext implements SchemaServiceListener {
45     val static LOG = LoggerFactory.getLogger(ControllerContext)
46     val static ControllerContext INSTANCE = new ControllerContext
47     val static NULL_VALUE = "null"
48     val static MOUNT_MODULE = "yang-ext"
49     val static MOUNT_NODE = "mount"
50     public val static MOUNT = "yang-ext:mount"
51
52     @Property
53     var SchemaContext globalSchema;
54     
55     @Property
56     var MountService mountService;
57
58     private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
59     private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
60     private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
61
62     private new() {
63         if (INSTANCE !== null) {
64             throw new IllegalStateException("Already instantiated");
65         }
66     }
67
68     static def getInstance() {
69         return INSTANCE
70     }
71
72     private def void checkPreconditions() {
73         if (globalSchema === null) {
74             throw new ResponseException(SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
75         }
76     }
77
78     def setSchemas(SchemaContext schemas) {
79         onGlobalContextUpdated(schemas)
80     }
81
82     public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
83         checkPreconditions
84         val pathArgs = restconfInstance.split("/");
85         if (pathArgs.empty) {
86             return null;
87         }
88         if (pathArgs.head.empty) {
89             pathArgs.remove(0)
90         }
91         val startModule = pathArgs.head.toModuleName();
92         if (startModule === null) {
93             throw new ResponseException(BAD_REQUEST, "First node in URI has to be in format \"moduleName:nodeName\"")
94         }
95         val iiWithSchemaNode = collectPathArguments(InstanceIdentifier.builder(), pathArgs,
96             globalSchema.getLatestModule(startModule), null);
97         if (iiWithSchemaNode === null) {
98             throw new ResponseException(BAD_REQUEST, "URI has bad format")
99         }
100         return iiWithSchemaNode
101     }
102
103     private def getLatestModule(SchemaContext schema, String moduleName) {
104         checkArgument(schema !== null);
105         checkArgument(moduleName !== null && !moduleName.empty)
106         val modules = schema.modules.filter[m|m.name == moduleName]
107         return modules.filterLatestModule
108     }
109     
110     private def filterLatestModule(Iterable<Module> modules) {
111         var latestModule = modules.head
112         for (module : modules) {
113             if (module.revision.after(latestModule.revision)) {
114                 latestModule = module
115             }
116         }
117         return latestModule
118     }
119     
120     def findModuleByName(String moduleName) {
121         checkPreconditions
122         checkArgument(moduleName !== null && !moduleName.empty)
123         return globalSchema.getLatestModule(moduleName)
124     }
125     
126     def findModuleByName(MountInstance mountPoint, String moduleName) {
127         checkArgument(moduleName !== null && mountPoint !== null)
128         val mountPointSchema = mountPoint.schemaContext;
129         return mountPointSchema?.getLatestModule(moduleName);
130     }
131     
132     def findModuleByNamespace(URI namespace) {
133         checkPreconditions
134         checkArgument(namespace !== null)
135         val moduleSchemas = globalSchema.findModuleByNamespace(namespace)
136         return moduleSchemas?.filterLatestModule
137     }
138     
139     def findModuleByNamespace(MountInstance mountPoint, URI namespace) {
140         checkArgument(namespace !== null && mountPoint !== null)
141         val mountPointSchema = mountPoint.schemaContext;
142         val moduleSchemas = mountPointSchema?.findModuleByNamespace(namespace)
143         return moduleSchemas?.filterLatestModule
144     }
145
146     def String toFullRestconfIdentifier(InstanceIdentifier path) {
147         checkPreconditions
148         val elements = path.path;
149         val ret = new StringBuilder();
150         val startQName = elements.get(0).nodeType;
151         val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
152         var node = initialModule as DataSchemaNode;
153         for (element : elements) {
154             node = node.childByQName(element.nodeType);
155             ret.append(element.toRestconfIdentifier(node));
156         }
157         return ret.toString
158     }
159
160     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
161         '''/«argument.nodeType.toRestconfIdentifier()»'''
162     }
163
164     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
165         val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
166         val keyValues = argument.keyValues;
167         return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
168     }
169
170     private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
171         throw new IllegalArgumentException("Conversion of generic path argument is not supported");
172     }
173
174     def findModuleNameByNamespace(URI namespace) {
175         checkPreconditions
176         var moduleName = uriToModuleName.get(namespace)
177         if (moduleName === null) {
178             val module = findModuleByNamespace(namespace)
179             if (module === null) return null
180             moduleName = module.name
181             uriToModuleName.put(namespace, moduleName)
182         }
183         return moduleName
184     }
185     
186     def findModuleNameByNamespace(MountInstance mountPoint, URI namespace) {
187         val module = mountPoint.findModuleByNamespace(namespace);
188         return module?.name
189     }
190
191     def findNamespaceByModuleName(String moduleName) {
192         var namespace = moduleNameToUri.get(moduleName)
193         if (namespace === null) {
194             var module = findModuleByName(moduleName)
195             if(module === null) return null
196             namespace = module.namespace
197             uriToModuleName.put(namespace, moduleName)
198         }
199         return namespace
200     }
201     
202     def findNamespaceByModuleName(MountInstance mountPoint, String moduleName) {
203         val module = mountPoint.findModuleByName(moduleName)
204         return module?.namespace
205     }
206
207     def CharSequence toRestconfIdentifier(QName qname) {
208         checkPreconditions
209         var module = uriToModuleName.get(qname.namespace)
210         if (module === null) {
211             val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
212             if(moduleSchema === null) throw new IllegalArgumentException()
213             uriToModuleName.put(qname.namespace, moduleSchema.name)
214             module = moduleSchema.name;
215         }
216         return '''«module»:«qname.localName»''';
217     }
218
219     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
220         for (caze : container.cases) {
221             val ret = caze.childByQName(name)
222             if (ret !== null) {
223                 return ret;
224             }
225         }
226         return null;
227     }
228
229     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
230         val ret = container.getDataChildByName(name);
231         return ret;
232     }
233
234     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
235         return container.dataNodeChildByQName(name);
236     }
237
238     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
239         return container.dataNodeChildByQName(name);
240     }
241
242     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
243         return null;
244     }
245
246     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
247         var ret = container.getDataChildByName(name);
248         if (ret === null) {
249
250             // Find in Choice Cases
251             for (node : container.childNodes) {
252                 if (node instanceof ChoiceCaseNode) {
253                     val caseNode = (node as ChoiceCaseNode);
254                     ret = caseNode.childByQName(name);
255                     if (ret !== null) {
256                         return ret;
257                     }
258                 }
259             }
260         }
261         return ret;
262     }
263
264     private def toUriString(Object object) {
265         if(object === null) return "";
266         return URLEncoder.encode(object.toString)
267     }
268     
269     private def InstanceIdWithSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
270         DataNodeContainer parentNode, MountInstance mountPoint) {
271         checkNotNull(strings)
272         if (parentNode === null) {
273             return null;
274         }
275         if (strings.empty) {
276             return new InstanceIdWithSchemaNode(builder.toInstance, parentNode as DataSchemaNode, mountPoint)
277         }
278         
279         val nodeName = strings.head.toNodeName
280         val moduleName = strings.head.toModuleName
281         var DataSchemaNode targetNode = null
282         if (!moduleName.nullOrEmpty) {
283             // if it is mount point
284             if (moduleName == MOUNT_MODULE && nodeName == MOUNT_NODE) {
285                 if (mountPoint !== null) {
286                     throw new ResponseException(BAD_REQUEST, "Restconf supports just one mount point in URI.")
287                 }
288                 
289                 if (mountService === null) {
290                     throw new ResponseException(SERVICE_UNAVAILABLE, "MountService was not found. " 
291                         + "Finding behind mount points does not work."
292                     )
293                 }
294                 
295                 val partialPath = builder.toInstance;
296                 val mount = mountService.getMountPoint(partialPath)
297                 if (mount === null) {
298                     LOG.debug("Instance identifier to missing mount point: {}", partialPath)
299                     throw new ResponseException(BAD_REQUEST, "Mount point does not exist.")
300                 }
301                 
302                 val mountPointSchema = mount.schemaContext;
303                 if (mountPointSchema === null) {
304                     throw new ResponseException(BAD_REQUEST, "Mount point does not contain any schema with modules.")
305                 }
306                 
307                 if (strings.size == 1) { // any data node is not behind mount point
308                     return new InstanceIdWithSchemaNode(InstanceIdentifier.builder().toInstance, mountPointSchema, mount)
309                 }
310                 
311                 val moduleNameBehindMountPoint = strings.get(1).toModuleName()
312                 if (moduleNameBehindMountPoint === null) {
313                     throw new ResponseException(BAD_REQUEST,
314                         "First node after mount point in URI has to be in format \"moduleName:nodeName\"")
315                 }
316                 
317                 val moduleBehindMountPoint = mountPointSchema.getLatestModule(moduleNameBehindMountPoint)
318                 if (moduleBehindMountPoint === null) {
319                     throw new ResponseException(BAD_REQUEST,
320                         "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
321                 }
322                 
323                 return collectPathArguments(InstanceIdentifier.builder(), strings.subList(1, strings.size),
324                     moduleBehindMountPoint, mount);
325             }
326             
327             var Module module = null;
328             if (mountPoint === null) {
329                 module = globalSchema.getLatestModule(moduleName)
330                 if (module === null) {
331                     throw new ResponseException(BAD_REQUEST,
332                         "URI has bad format. \"" + moduleName + "\" module does not exist.")
333                 }
334             } else {
335                 module = mountPoint.schemaContext?.getLatestModule(moduleName)
336                 if (module === null) {
337                     throw new ResponseException(BAD_REQUEST,
338                         "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
339                 }
340             }
341             targetNode = parentNode.findInstanceDataChildByNameAndNamespace(nodeName, module.namespace)
342             if (targetNode === null) {
343                 throw new ResponseException(BAD_REQUEST, "URI has bad format. Possible reasons:\n" + 
344                     "1. \"" + strings.head + "\" was not found in parent data node.\n" + 
345                     "2. \"" + strings.head + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + strings.head + "\".")
346             }
347         } else { // string without module name
348             val potentialSchemaNodes = parentNode.findInstanceDataChildrenByName(nodeName)
349             if (potentialSchemaNodes.size > 1) {
350                 val StringBuilder namespacesOfPotentialModules = new StringBuilder;
351                 for (potentialNodeSchema : potentialSchemaNodes) {
352                     namespacesOfPotentialModules.append("   ").append(potentialNodeSchema.QName.namespace.toString).append("\n")
353                 }
354                 throw new ResponseException(BAD_REQUEST, "URI has bad format. Node \"" + nodeName + "\" is added as augment from more than one module. " 
355                         + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
356                         + "\nThe node is added as augment from modules with namespaces:\n" + namespacesOfPotentialModules)
357             }
358             targetNode = potentialSchemaNodes.head
359             if (targetNode === null) {
360                 throw new ResponseException(BAD_REQUEST, "URI has bad format. \"" + nodeName + "\" was not found in parent data node.\n")
361             }
362         }
363         
364         if (!(targetNode instanceof ListSchemaNode) && !(targetNode instanceof ContainerSchemaNode)) {
365             throw new ResponseException(BAD_REQUEST,"URI has bad format. Node \"" + strings.head + "\" must be Container or List yang type.")
366         }
367         // Number of consumed elements
368         var consumed = 1;
369         if (targetNode instanceof ListSchemaNode) {
370             val listNode = targetNode as ListSchemaNode;
371             val keysSize = listNode.keyDefinition.size
372
373             // every key has to be filled
374             if ((strings.length - consumed) < keysSize) {
375                 throw new ResponseException(BAD_REQUEST,"Missing key for list \"" + listNode.QName.localName + "\".")
376             }
377             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
378             val keyValues = new HashMap<QName, Object>();
379             var i = 0;
380             for (key : listNode.keyDefinition) {
381                 val uriKeyValue = uriKeyValues.get(i);
382
383                 // key value cannot be NULL
384                 if (uriKeyValue.equals(NULL_VALUE)) {
385                     throw new ResponseException(BAD_REQUEST, "URI has bad format. List \"" + listNode.QName.localName 
386                         + "\" cannot contain \"null\" value as a key."
387                     )
388                 }
389                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
390                 i = i + 1;
391             }
392             consumed = consumed + i;
393             builder.nodeWithKey(targetNode.QName, keyValues);
394         } else {
395
396             // Only one instance of node is allowed
397             builder.node(targetNode.QName);
398         }
399         if (targetNode instanceof DataNodeContainer) {
400             val remaining = strings.subList(consumed, strings.length);
401             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer, mountPoint);
402             return result
403         }
404
405         return new InstanceIdWithSchemaNode(builder.toInstance, targetNode, mountPoint)
406     }
407
408     def DataSchemaNode findInstanceDataChildByNameAndNamespace(DataNodeContainer container,
409         String name, URI namespace) {
410         Preconditions.checkNotNull(namespace)
411         val potentialSchemaNodes = container.findInstanceDataChildrenByName(name)
412         return potentialSchemaNodes.filter[n|n.QName.namespace == namespace].head
413     }
414     
415     def List<DataSchemaNode> findInstanceDataChildrenByName(DataNodeContainer container, String name) {
416         Preconditions.checkNotNull(container)
417         Preconditions.checkNotNull(name)
418         val instantiatedDataNodeContainers = new ArrayList
419         instantiatedDataNodeContainers.collectInstanceDataNodeContainers(container, name)
420         return instantiatedDataNodeContainers
421     }
422     
423     private def void collectInstanceDataNodeContainers(List<DataSchemaNode> potentialSchemaNodes, DataNodeContainer container,
424         String name) {
425         val nodes = container.childNodes.filter[n|n.QName.localName == name]
426         for (potentialNode : nodes) {
427             if (potentialNode.isInstantiatedDataSchema) {
428                 potentialSchemaNodes.add(potentialNode)
429             }
430         }
431         val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
432         for (caze : allCases) {
433             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name)
434         }
435     }
436     
437     def boolean isInstantiatedDataSchema(DataSchemaNode node) {
438         switch node {
439             LeafSchemaNode: return true
440             LeafListSchemaNode: return true
441             ContainerSchemaNode: return true
442             ListSchemaNode: return true
443             default: return false
444         }
445     }
446     
447     private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
448         checkNotNull(uriValue);
449         checkArgument(node instanceof LeafSchemaNode);
450         val urlDecoded = URLDecoder.decode(uriValue);
451         val typedef = (node as LeafSchemaNode).type;
452         
453         var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
454         if(decoded === null) {
455             var baseType = RestUtil.resolveBaseTypeFrom(typedef)
456             if(baseType instanceof IdentityrefTypeDefinition) {
457                 decoded = toQName(urlDecoded)
458             }
459         }
460         map.put(node.QName, decoded);
461     }
462
463     private static def String toModuleName(String str) {
464         checkNotNull(str)
465         if (str.contains(":")) {
466             val args = str.split(":");
467             if (args.size === 2) {
468                 return args.get(0);
469             }
470         }
471         return null;
472     }
473
474     private def String toNodeName(String str) {
475         if (str.contains(":")) {
476             val args = str.split(":");
477             if (args.size === 2) {
478                 return args.get(1);
479             }
480         }
481         return str;
482     }
483
484     private def QName toQName(String name) {
485         val module = name.toModuleName;
486         val node = name.toNodeName;
487         val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
488             .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
489         ;
490         return QName.create(namespace,node);
491     }
492
493     def getRpcDefinition(String name) {
494         return qnameToRpc.get(name.toQName)
495     }
496
497     override onGlobalContextUpdated(SchemaContext context) {
498         this.globalSchema = context;
499         for (operation : context.operations) {
500             val qname = operation.QName;
501             qnameToRpc.put(qname, operation);
502         }
503     }
504
505 }