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