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