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