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