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