Merge "Simplify method isMutualExclusive in Subnet. Remove redundant 'if' statements."
[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.rest.impl.RestUtil
16 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
17 import org.opendaylight.yangtools.yang.common.QName
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
23 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
24 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
25 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext
33 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
34 import org.slf4j.LoggerFactory
35
36 import static com.google.common.base.Preconditions.*
37
38 class ControllerContext implements SchemaServiceListener {
39     val static LOG = LoggerFactory.getLogger(ControllerContext)
40     val static ControllerContext INSTANCE = new ControllerContext
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     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) return null
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) return null
151             uriToModuleName.put(namespace, latestModule.name)
152             module = latestModule.name;
153         }
154         return module
155     }
156
157     def findNamespaceByModule(String module) {
158         var namespace = moduleNameToUri.get(module)
159         if (namespace === null) {
160             val moduleSchemas = schemas.modules.filter[it|it.name.equals(module)]
161             var latestModule = moduleSchemas.head
162             for (m : moduleSchemas) {
163                 if (m.revision.after(latestModule.revision)) {
164                     latestModule = m
165                 }
166             }
167             if(latestModule === null) return null
168             namespace = latestModule.namespace
169             uriToModuleName.put(namespace, latestModule.name)
170         }
171         return namespace
172     }
173
174     def CharSequence toRestconfIdentifier(QName qname) {
175         checkPreconditions
176         var module = uriToModuleName.get(qname.namespace)
177         if (module === null) {
178             val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
179             if(moduleSchema === null) throw new IllegalArgumentException()
180             uriToModuleName.put(qname.namespace, moduleSchema.name)
181             module = moduleSchema.name;
182         }
183         return '''«module»:«qname.localName»''';
184     }
185
186     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
187         for (caze : container.cases) {
188             val ret = caze.childByQName(name)
189             if (ret !== null) {
190                 return ret;
191             }
192         }
193         return null;
194     }
195
196     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
197         val ret = container.getDataChildByName(name);
198         return ret;
199     }
200
201     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
202         return container.dataNodeChildByQName(name);
203     }
204
205     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
206         return container.dataNodeChildByQName(name);
207     }
208
209     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
210         return null;
211     }
212
213     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
214         var ret = container.getDataChildByName(name);
215         if (ret === null) {
216
217             // Find in Choice Cases
218             for (node : container.childNodes) {
219                 if (node instanceof ChoiceCaseNode) {
220                     val caseNode = (node as ChoiceCaseNode);
221                     ret = caseNode.childByQName(name);
222                     if (ret !== null) {
223                         return ret;
224                     }
225                 }
226             }
227         }
228         return ret;
229     }
230
231     private def toUriString(Object object) {
232         if(object === null) return "";
233         return URLEncoder.encode(object.toString)
234     }
235
236     private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
237         DataNodeContainer parentNode) {
238         checkNotNull(strings)
239         if (parentNode === null) {
240             return null;
241         }
242         if (strings.empty) {
243             return parentNode as DataSchemaNode;
244         }
245         val nodeRef = strings.head;
246
247         val nodeName = nodeRef.toNodeName();
248         val targetNode = parentNode.getDataChildByName(nodeName);
249         if (targetNode === null) {
250             val children = parentNode.childNodes
251             for (child : children) {
252                 if (child instanceof ChoiceNode) {
253                     val choice = child as ChoiceNode
254                     for (caze : choice.cases) {
255                         val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
256                         if (result !== null)
257                             return result
258                     }
259                 }
260             }
261             return null
262         }
263         if (targetNode instanceof ChoiceNode) {
264             return null
265         }
266
267         // Number of consumed elements
268         var consumed = 1;
269         if (targetNode instanceof ListSchemaNode) {
270             val listNode = targetNode as ListSchemaNode;
271             val keysSize = listNode.keyDefinition.size
272
273             // every key has to be filled
274             if ((strings.length - consumed) < keysSize) {
275                 return null;
276             }
277             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
278             val keyValues = new HashMap<QName, Object>();
279             var i = 0;
280             for (key : listNode.keyDefinition) {
281                 val uriKeyValue = uriKeyValues.get(i);
282
283                 // key value cannot be NULL
284                 if (uriKeyValue.equals(NULL_VALUE)) {
285                     return null
286                 }
287                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
288                 i = i + 1;
289             }
290             consumed = consumed + i;
291             builder.nodeWithKey(targetNode.QName, keyValues);
292         } else {
293
294             // Only one instance of node is allowed
295             builder.node(targetNode.QName);
296         }
297         if (targetNode instanceof DataNodeContainer) {
298             val remaining = strings.subList(consumed, strings.length);
299             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
300             return result
301         }
302
303         return targetNode
304     }
305
306     private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
307         checkNotNull(uriValue);
308         checkArgument(node instanceof LeafSchemaNode);
309         val urlDecoded = URLDecoder.decode(uriValue);
310         val typedef = (node as LeafSchemaNode).type;
311         
312         var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
313         if(decoded === null) {
314             var baseType = RestUtil.resolveBaseTypeFrom(typedef)
315             if(baseType instanceof IdentityrefTypeDefinition) {
316                 decoded = toQName(urlDecoded)
317             }
318         }
319         map.put(node.QName, decoded);
320     }
321
322     private def String toModuleName(String str) {
323         checkNotNull(str)
324         if (str.contains(":")) {
325             val args = str.split(":");
326             checkArgument(args.size === 2);
327             return args.get(0);
328         } else {
329             return null;
330         }
331     }
332
333     private def String toNodeName(String str) {
334         if (str.contains(":")) {
335             val args = str.split(":");
336             checkArgument(args.size === 2);
337             return args.get(1);
338         } else {
339             return str;
340         }
341     }
342
343     private def QName toQName(String name) {
344         val module = name.toModuleName;
345         val node = name.toNodeName;
346         val namespace = FluentIterable.from(schemas.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
347             .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
348         ;
349         return QName.create(namespace,node);
350     }
351
352     def getRpcDefinition(String name) {
353         return qnameToRpc.get(name.toQName)
354     }
355
356     override onGlobalContextUpdated(SchemaContext context) {
357         this.schemas = context;
358         for (operation : context.operations) {
359             val qname = operation.QName;
360             qnameToRpc.put(qname, operation);
361         }
362     }
363
364 }