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