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