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