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