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