1 package org.opendaylight.controller.sal.restconf.impl
3 import com.google.common.collect.BiMap
4 import com.google.common.collect.FluentIterable
5 import com.google.common.collect.HashBiMap
7 import java.net.URLDecoder
8 import java.net.URLEncoder
9 import java.util.HashMap
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
36 import static com.google.common.base.Preconditions.*
37 import org.opendaylight.controller.sal.core.api.mount.MountService
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
40 class ControllerContext implements SchemaServiceListener {
41 val static LOG = LoggerFactory.getLogger(ControllerContext)
42 val static ControllerContext INSTANCE = new ControllerContext
43 val static NULL_VALUE = "null"
46 var SchemaContext globalSchema;
49 var MountService mountService;
51 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
52 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
53 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
56 if (INSTANCE !== null) {
57 throw new IllegalStateException("Already instantiated");
61 static def getInstance() {
65 private def void checkPreconditions() {
66 if (globalSchema === null) {
67 throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
71 def setSchemas(SchemaContext schemas) {
72 onGlobalContextUpdated(schemas)
75 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
76 val ret = InstanceIdentifier.builder();
77 val pathArgs = restconfInstance.split("/");
81 if (pathArgs.head.empty) {
84 val schemaNode = ret.collectPathArguments(pathArgs, globalSchema.findModule(pathArgs.head));
85 if (schemaNode === null) {
88 return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
91 private static def findModule(SchemaContext context,String argument) {
93 checkNotNull(argument);
94 val startModule = argument.toModuleName();
95 return context.getLatestModule(startModule)
98 static def getLatestModule(SchemaContext schema,String moduleName) {
99 checkArgument(schema != null);
100 checkArgument(moduleName !== null && !moduleName.empty)
101 val modules = schema.modules.filter[m|m.name == moduleName]
102 var latestModule = modules.head
103 for (module : modules) {
104 if (module.revision.after(latestModule.revision)) {
105 latestModule = module
111 def String toFullRestconfIdentifier(InstanceIdentifier path) {
113 val elements = path.path;
114 val ret = new StringBuilder();
115 val startQName = elements.get(0).nodeType;
116 val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
117 var node = initialModule as DataSchemaNode;
118 for (element : elements) {
119 node = node.childByQName(element.nodeType);
120 ret.append(element.toRestconfIdentifier(node));
125 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
126 '''/«argument.nodeType.toRestconfIdentifier()»'''
129 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
130 val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
131 val keyValues = argument.keyValues;
132 return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
135 private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
136 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
139 def findModuleByNamespace(URI namespace) {
141 var module = uriToModuleName.get(namespace)
142 if (module === null) {
143 val moduleSchemas = globalSchema.findModuleByNamespace(namespace);
144 if(moduleSchemas === null) return null
145 var latestModule = moduleSchemas.head
146 for (m : moduleSchemas) {
147 if (m.revision.after(latestModule.revision)) {
151 if(latestModule === null) return null
152 uriToModuleName.put(namespace, latestModule.name)
153 module = latestModule.name;
158 def findNamespaceByModule(String module) {
159 var namespace = moduleNameToUri.get(module)
160 if (namespace === null) {
161 val moduleSchemas = globalSchema.modules.filter[it|it.name.equals(module)]
162 var latestModule = moduleSchemas.head
163 for (m : moduleSchemas) {
164 if (m.revision.after(latestModule.revision)) {
168 if(latestModule === null) return null
169 namespace = latestModule.namespace
170 uriToModuleName.put(namespace, latestModule.name)
175 def CharSequence toRestconfIdentifier(QName qname) {
177 var module = uriToModuleName.get(qname.namespace)
178 if (module === null) {
179 val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
180 if(moduleSchema === null) throw new IllegalArgumentException()
181 uriToModuleName.put(qname.namespace, moduleSchema.name)
182 module = moduleSchema.name;
184 return '''«module»:«qname.localName»''';
187 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
188 for (caze : container.cases) {
189 val ret = caze.childByQName(name)
197 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
198 val ret = container.getDataChildByName(name);
202 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
203 return container.dataNodeChildByQName(name);
206 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
207 return container.dataNodeChildByQName(name);
210 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
214 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
215 var ret = container.getDataChildByName(name);
218 // Find in Choice Cases
219 for (node : container.childNodes) {
220 if (node instanceof ChoiceCaseNode) {
221 val caseNode = (node as ChoiceCaseNode);
222 ret = caseNode.childByQName(name);
232 private def toUriString(Object object) {
233 if(object === null) return "";
234 return URLEncoder.encode(object.toString)
237 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
238 DataNodeContainer parentNode) {
239 checkNotNull(strings)
240 if (parentNode === null) {
244 return parentNode as DataSchemaNode;
246 val nodeRef = strings.head;
248 val nodeName = nodeRef.toNodeName;
249 var targetNode = parentNode.findInstanceDataChild(nodeName);
250 if (targetNode instanceof ChoiceNode) {
254 if (targetNode === null) {
255 // Node is possibly in other mount point
256 val partialPath = builder.toInstance;
257 val mountPointSchema = mountService?.getMountPoint(partialPath)?.schemaContext;
258 if(mountPointSchema != null) {
259 return builder.collectPathArguments(strings, mountPointSchema.findModule(strings.head));
265 // Number of consumed elements
267 if (targetNode instanceof ListSchemaNode) {
268 val listNode = targetNode as ListSchemaNode;
269 val keysSize = listNode.keyDefinition.size
271 // every key has to be filled
272 if ((strings.length - consumed) < keysSize) {
275 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
276 val keyValues = new HashMap<QName, Object>();
278 for (key : listNode.keyDefinition) {
279 val uriKeyValue = uriKeyValues.get(i);
281 // key value cannot be NULL
282 if (uriKeyValue.equals(NULL_VALUE)) {
285 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
288 consumed = consumed + i;
289 builder.nodeWithKey(targetNode.QName, keyValues);
292 // Only one instance of node is allowed
293 builder.node(targetNode.QName);
295 if (targetNode instanceof DataNodeContainer) {
296 val remaining = strings.subList(consumed, strings.length);
297 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
304 static def DataSchemaNode findInstanceDataChild(DataNodeContainer container, String name) {
305 // FIXME: Add namespace comparison
306 var potentialNode = container.getDataChildByName(name);
307 if(potentialNode.instantiatedDataSchema) {
308 return potentialNode;
310 val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
311 for (caze : allCases) {
312 potentialNode = caze.findInstanceDataChild(name);
313 if(potentialNode != null) {
314 return potentialNode;
320 static def boolean isInstantiatedDataSchema(DataSchemaNode node) {
322 LeafSchemaNode: return true
323 LeafListSchemaNode: return true
324 ContainerSchemaNode: return true
325 ListSchemaNode: return true
326 default: return false
330 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
331 checkNotNull(uriValue);
332 checkArgument(node instanceof LeafSchemaNode);
333 val urlDecoded = URLDecoder.decode(uriValue);
334 val typedef = (node as LeafSchemaNode).type;
336 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
337 if(decoded === null) {
338 var baseType = RestUtil.resolveBaseTypeFrom(typedef)
339 if(baseType instanceof IdentityrefTypeDefinition) {
340 decoded = toQName(urlDecoded)
343 map.put(node.QName, decoded);
346 private static def String toModuleName(String str) {
348 if (str.contains(":")) {
349 val args = str.split(":");
350 checkArgument(args.size === 2);
357 private def String toNodeName(String str) {
358 if (str.contains(":")) {
359 val args = str.split(":");
360 checkArgument(args.size === 2);
367 private def QName toQName(String name) {
368 val module = name.toModuleName;
369 val node = name.toNodeName;
370 val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
371 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
373 return QName.create(namespace,node);
376 def getRpcDefinition(String name) {
377 return qnameToRpc.get(name.toQName)
380 override onGlobalContextUpdated(SchemaContext context) {
381 this.globalSchema = context;
382 for (operation : context.operations) {
383 val qname = operation.QName;
384 qnameToRpc.put(qname, operation);