Fixed RESTConf support for identity-ref build-in datatype
[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.collect.BiMap
4 import com.google.common.collect.FluentIterable
5 import com.google.common.collect.HashBiMap
6 import java.net.URI
7 import java.net.URLDecoder
8 import java.net.URLEncoder
9 import java.util.HashMap
10 import java.util.List
11 import java.util.Map
12 import java.util.concurrent.ConcurrentHashMap
13 import javax.ws.rs.core.Response
14 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener
15 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
16 import org.opendaylight.yangtools.yang.common.QName
17 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
22 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
23 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
24 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
25 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
26 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
27 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
28 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext
32 import org.opendaylight.yangtools.yang.model.api.SchemaNode
33 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
34 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition
35 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil
36 import org.slf4j.LoggerFactory
37
38 import static com.google.common.base.Preconditions.*
39
40 class ControllerContext implements SchemaServiceListener {
41     val static LOG = LoggerFactory.getLogger(ControllerContext)
42     val static ControllerContext INSTANCE = new ControllerContext
43     val static NULL_VALUE = "null"
44
45     var SchemaContext schemas;
46
47     private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
48     private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
49     private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
50
51     private new() {
52         if (INSTANCE !== null) {
53             throw new IllegalStateException("Already instantiated");
54         }
55     }
56
57     static def getInstance() {
58         return INSTANCE
59     }
60
61     private def void checkPreconditions() {
62         if (schemas === null) {
63             throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
64         }
65     }
66
67     def setSchemas(SchemaContext schemas) {
68         onGlobalContextUpdated(schemas)
69     }
70
71     public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
72         val ret = InstanceIdentifier.builder();
73         val pathArgs = restconfInstance.split("/");
74         if (pathArgs.empty) {
75             return null;
76         }
77         if (pathArgs.head.empty) {
78             pathArgs.remove(0)
79         }
80         val schemaNode = ret.collectPathArguments(pathArgs, restconfInstance.findModule);
81         if (schemaNode === null) {
82             return null
83         }
84         return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
85     }
86
87     private def findModule(String restconfInstance) {
88         checkPreconditions
89         checkNotNull(restconfInstance);
90         val pathArgs = restconfInstance.split("/");
91         if (pathArgs.empty) {
92             return null;
93         }
94         val modulWithFirstYangStatement = pathArgs.filter[s|s.contains(":")].head
95         val startModule = modulWithFirstYangStatement.toModuleName();
96         return getLatestModule(startModule)
97     }
98
99     def getLatestModule(String moduleName) {
100         checkPreconditions
101         checkArgument(moduleName !== null && !moduleName.empty)
102         val modules = schemas.modules.filter[m|m.name == moduleName]
103         var latestModule = modules.head
104         for (module : modules) {
105             if (module.revision.after(latestModule.revision)) {
106                 latestModule = module
107             }
108         }
109         return latestModule
110     }
111
112     def String toFullRestconfIdentifier(InstanceIdentifier path) {
113         checkPreconditions
114         val elements = path.path;
115         val ret = new StringBuilder();
116         val startQName = elements.get(0).nodeType;
117         val initialModule = schemas.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
118         var node = initialModule as DataSchemaNode;
119         for (element : elements) {
120             node = node.childByQName(element.nodeType);
121             ret.append(element.toRestconfIdentifier(node));
122         }
123         return ret.toString
124     }
125
126     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
127         '''/«argument.nodeType.toRestconfIdentifier()»'''
128     }
129
130     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
131         val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
132         val keyValues = argument.keyValues;
133         return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
134     }
135
136     private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
137         throw new IllegalArgumentException("Conversion of generic path argument is not supported");
138     }
139
140     def findModuleByNamespace(URI namespace) {
141         checkPreconditions
142         var module = uriToModuleName.get(namespace)
143         if (module === null) {
144             val moduleSchemas = schemas.findModuleByNamespace(namespace);
145             if(moduleSchemas === null) return null
146             var latestModule = moduleSchemas.head
147             for (m : moduleSchemas) {
148                 if (m.revision.after(latestModule.revision)) {
149                     latestModule = m
150                 }
151             }
152             if(latestModule === null) return null
153             uriToModuleName.put(namespace, latestModule.name)
154             module = latestModule.name;
155         }
156         return module
157     }
158
159     def findNamespaceByModule(String module) {
160         var namespace = moduleNameToUri.get(module)
161         if (namespace === null) {
162             val moduleSchemas = schemas.modules.filter[it|it.name.equals(module)]
163             var latestModule = moduleSchemas.head
164             for (m : moduleSchemas) {
165                 if (m.revision.after(latestModule.revision)) {
166                     latestModule = m
167                 }
168             }
169             if(latestModule === null) return null
170             namespace = latestModule.namespace
171             uriToModuleName.put(namespace, latestModule.name)
172         }
173         return namespace
174     }
175
176     def CharSequence toRestconfIdentifier(QName qname) {
177         checkPreconditions
178         var module = uriToModuleName.get(qname.namespace)
179         if (module === null) {
180             val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
181             if(moduleSchema === null) throw new IllegalArgumentException()
182             uriToModuleName.put(qname.namespace, moduleSchema.name)
183             module = moduleSchema.name;
184         }
185         return '''«module»:«qname.localName»''';
186     }
187
188     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
189         for (caze : container.cases) {
190             val ret = caze.childByQName(name)
191             if (ret !== null) {
192                 return ret;
193             }
194         }
195         return null;
196     }
197
198     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
199         val ret = container.getDataChildByName(name);
200         return ret;
201     }
202
203     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
204         return container.dataNodeChildByQName(name);
205     }
206
207     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
208         return container.dataNodeChildByQName(name);
209     }
210
211     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
212         return null;
213     }
214
215     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
216         var ret = container.getDataChildByName(name);
217         if (ret === null) {
218
219             // Find in Choice Cases
220             for (node : container.childNodes) {
221                 if (node instanceof ChoiceCaseNode) {
222                     val caseNode = (node as ChoiceCaseNode);
223                     ret = caseNode.childByQName(name);
224                     if (ret !== null) {
225                         return ret;
226                     }
227                 }
228             }
229         }
230         return ret;
231     }
232
233     private def toUriString(Object object) {
234         if(object === null) return "";
235         return URLEncoder.encode(object.toString)
236     }
237
238     private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
239         DataNodeContainer parentNode) {
240         checkNotNull(strings)
241         if (parentNode === null) {
242             return null;
243         }
244         if (strings.empty) {
245             return parentNode as DataSchemaNode;
246         }
247         val nodeRef = strings.head;
248
249         val nodeName = nodeRef.toNodeName();
250         val targetNode = parentNode.getDataChildByName(nodeName);
251         if (targetNode === null) {
252             val children = parentNode.childNodes
253             for (child : children) {
254                 if (child instanceof ChoiceNode) {
255                     val choice = child as ChoiceNode
256                     for (caze : choice.cases) {
257                         val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
258                         if (result !== null)
259                             return result
260                     }
261                 }
262             }
263             return null
264         }
265         if (targetNode instanceof ChoiceNode) {
266             return null
267         }
268
269         // Number of consumed elements
270         var consumed = 1;
271         if (targetNode instanceof ListSchemaNode) {
272             val listNode = targetNode as ListSchemaNode;
273             val keysSize = listNode.keyDefinition.size
274
275             // every key has to be filled
276             if ((strings.length - consumed) < keysSize) {
277                 return null;
278             }
279             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
280             val keyValues = new HashMap<QName, Object>();
281             var i = 0;
282             for (key : listNode.keyDefinition) {
283                 val uriKeyValue = uriKeyValues.get(i);
284
285                 // key value cannot be NULL
286                 if (uriKeyValue.equals(NULL_VALUE)) {
287                     return null
288                 }
289                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
290                 i = i + 1;
291             }
292             consumed = consumed + i;
293             builder.nodeWithKey(targetNode.QName, keyValues);
294         } else {
295
296             // Only one instance of node is allowed
297             builder.node(targetNode.QName);
298         }
299         if (targetNode instanceof DataNodeContainer) {
300             val remaining = strings.subList(consumed, strings.length);
301             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
302             return result
303         }
304
305         return targetNode
306     }
307
308     private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
309         checkNotNull(uriValue);
310         checkArgument(node instanceof LeafSchemaNode);
311         val urlDecoded = URLDecoder.decode(uriValue);
312         val typedef = (node as LeafSchemaNode).type;
313         
314         var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
315         if(decoded === null) {
316             var baseType = typedef
317             while (baseType.baseType !== null) {
318                 baseType = baseType.baseType;
319             }
320             if(baseType instanceof IdentityrefTypeDefinition) {
321                 decoded = toQName(urlDecoded)
322             }
323         }
324         map.put(node.QName, decoded);
325     }
326
327     private def String toModuleName(String str) {
328         checkNotNull(str)
329         if (str.contains(":")) {
330             val args = str.split(":");
331             checkArgument(args.size === 2);
332             return args.get(0);
333         } else {
334             return null;
335         }
336     }
337
338     private def String toNodeName(String str) {
339         if (str.contains(":")) {
340             val args = str.split(":");
341             checkArgument(args.size === 2);
342             return args.get(1);
343         } else {
344             return str;
345         }
346     }
347
348     private def QName toQName(String name) {
349         val module = name.toModuleName;
350         val node = name.toNodeName;
351         val namespace = FluentIterable.from(schemas.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
352             .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
353         ;
354         return QName.create(namespace,node);
355     }
356
357     def getRpcDefinition(String name) {
358         return qnameToRpc.get(name.toQName)
359     }
360
361     override onGlobalContextUpdated(SchemaContext context) {
362         this.schemas = context;
363         for (operation : context.operations) {
364             val qname = operation.QName;
365             qnameToRpc.put(qname, operation);
366         }
367     }
368
369     /**
370      * Resolve target type from leafref type.
371      * 
372      * According to RFC 6020 referenced element has to be leaf (chapter 9.9).
373      * Therefore if other element is referenced then null value is returned.
374      * 
375      * Currently only cases without path-predicate are supported.
376      * 
377      * @param leafRef
378      * @param schemaNode
379      *            data schema node which contains reference
380      * @return type if leaf is referenced and it is possible to find referenced
381      *         node in schema context. In other cases null value is returned
382      */
383     def LeafSchemaNode resolveTypeFromLeafref(LeafrefTypeDefinition leafRef, DataSchemaNode schemaNode) {
384         val xPath = leafRef.getPathStatement();
385         val module = SchemaContextUtil.findParentModule(schemas, schemaNode);
386
387         var SchemaNode foundSchemaNode
388         if (xPath.isAbsolute()) {
389             foundSchemaNode = SchemaContextUtil.findDataSchemaNode(schemas, module, xPath);
390         } else {
391             foundSchemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemas, module, schemaNode, xPath);
392         }
393
394         if (foundSchemaNode instanceof LeafSchemaNode) {
395             return foundSchemaNode as LeafSchemaNode;
396         }
397
398         return null;
399     }
400 }