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