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.core.api.mount.MountService
16 import org.opendaylight.controller.sal.rest.impl.RestUtil
17 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
18 import org.opendaylight.yangtools.yang.common.QName
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
23 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
24 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
25 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
26 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
32 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
33 import org.opendaylight.yangtools.yang.model.api.Module
34 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext
36 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
37 import org.slf4j.LoggerFactory
39 import static com.google.common.base.Preconditions.*
40 import java.util.ArrayList
42 class ControllerContext implements SchemaServiceListener {
43 val static LOG = LoggerFactory.getLogger(ControllerContext)
44 val static ControllerContext INSTANCE = new ControllerContext
45 val static NULL_VALUE = "null"
48 var SchemaContext globalSchema;
51 var MountService mountService;
53 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
54 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
55 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
58 if (INSTANCE !== null) {
59 throw new IllegalStateException("Already instantiated");
63 static def getInstance() {
67 private def void checkPreconditions() {
68 if (globalSchema === null) {
69 throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
73 def setSchemas(SchemaContext schemas) {
74 onGlobalContextUpdated(schemas)
77 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
79 val ret = InstanceIdentifier.builder();
80 val pathArgs = restconfInstance.split("/");
84 if (pathArgs.head.empty) {
87 val mountPoints = new ArrayList
88 val schemaNode = ret.collectPathArguments(pathArgs, globalSchema.findModule(pathArgs.head), mountPoints);
89 if (schemaNode === null) {
92 return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode, mountPoints.last)
95 private def findModule(SchemaContext context,String argument) {
96 checkNotNull(argument);
97 val startModule = argument.toModuleName();
98 return context.getLatestModule(startModule)
101 private def getLatestModule(SchemaContext schema,String moduleName) {
102 checkArgument(schema !== null);
103 checkArgument(moduleName !== null && !moduleName.empty)
104 val modules = schema.modules.filter[m|m.name == moduleName]
105 return modules.filterLatestModule
108 private def filterLatestModule(Iterable<Module> modules) {
109 var latestModule = modules.head
110 for (module : modules) {
111 if (module.revision.after(latestModule.revision)) {
112 latestModule = module
118 def findModuleByName(String moduleName) {
120 checkArgument(moduleName !== null && !moduleName.empty)
121 return globalSchema.getLatestModule(moduleName)
124 def findModuleByName(String moduleName, InstanceIdentifier partialPath) {
125 checkArgument(moduleName !== null && !moduleName.empty && partialPath !== null && !partialPath.path.empty)
126 val mountPointSchema = mountService?.getMountPoint(partialPath)?.schemaContext;
127 return mountPointSchema?.getLatestModule(moduleName);
130 def findModuleByNamespace(URI namespace) {
132 val moduleSchemas = globalSchema.findModuleByNamespace(namespace)
133 return moduleSchemas?.filterLatestModule
136 def findModuleByNamespace(URI namespace, InstanceIdentifier partialPath) {
137 checkArgument(namespace !== null && !namespace.toString.empty && partialPath !== null && !partialPath.path.empty)
138 val mountPointSchema = mountService?.getMountPoint(partialPath)?.schemaContext;
139 val moduleSchemas = mountPointSchema?.findModuleByNamespace(namespace)
140 return moduleSchemas?.filterLatestModule
143 def String toFullRestconfIdentifier(InstanceIdentifier path) {
145 val elements = path.path;
146 val ret = new StringBuilder();
147 val startQName = elements.get(0).nodeType;
148 val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
149 var node = initialModule as DataSchemaNode;
150 for (element : elements) {
151 node = node.childByQName(element.nodeType);
152 ret.append(element.toRestconfIdentifier(node));
157 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
158 '''/«argument.nodeType.toRestconfIdentifier()»'''
161 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
162 val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
163 val keyValues = argument.keyValues;
164 return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
167 private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
168 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
171 def findModuleNameByNamespace(URI namespace) {
173 var module = uriToModuleName.get(namespace)
174 if (module === null) {
175 val moduleSchemas = globalSchema.findModuleByNamespace(namespace);
176 if(moduleSchemas === null) return null
177 var latestModule = moduleSchemas.filterLatestModule
178 if(latestModule === null) return null
179 uriToModuleName.put(namespace, latestModule.name)
180 module = latestModule.name;
185 def findNamespaceByModuleName(String module) {
186 var namespace = moduleNameToUri.get(module)
187 if (namespace === null) {
188 var latestModule = globalSchema.getLatestModule(module)
189 if(latestModule === null) return null
190 namespace = latestModule.namespace
191 uriToModuleName.put(namespace, latestModule.name)
196 def CharSequence toRestconfIdentifier(QName qname) {
198 var module = uriToModuleName.get(qname.namespace)
199 if (module === null) {
200 val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
201 if(moduleSchema === null) throw new IllegalArgumentException()
202 uriToModuleName.put(qname.namespace, moduleSchema.name)
203 module = moduleSchema.name;
205 return '''«module»:«qname.localName»''';
208 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
209 for (caze : container.cases) {
210 val ret = caze.childByQName(name)
218 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
219 val ret = container.getDataChildByName(name);
223 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
224 return container.dataNodeChildByQName(name);
227 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
228 return container.dataNodeChildByQName(name);
231 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
235 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
236 var ret = container.getDataChildByName(name);
239 // Find in Choice Cases
240 for (node : container.childNodes) {
241 if (node instanceof ChoiceCaseNode) {
242 val caseNode = (node as ChoiceCaseNode);
243 ret = caseNode.childByQName(name);
253 private def toUriString(Object object) {
254 if(object === null) return "";
255 return URLEncoder.encode(object.toString)
258 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
259 DataNodeContainer parentNode, List<InstanceIdentifier> mountPoints) {
260 checkNotNull(strings)
261 if (parentNode === null) {
265 return parentNode as DataSchemaNode;
267 val nodeRef = strings.head;
269 val nodeName = nodeRef.toNodeName;
270 var targetNode = parentNode.findInstanceDataChild(nodeName);
271 if (targetNode instanceof ChoiceNode) {
275 if (targetNode === null) {
276 // Node is possibly in other mount point
277 val partialPath = builder.toInstance;
278 val mountPointSchema = mountService?.getMountPoint(partialPath)?.schemaContext;
279 if(mountPointSchema !== null) {
280 val module = mountPointSchema.findModule(strings.head)
281 if (module !== null) {
282 mountPoints.add(partialPath)
284 return builder.collectPathArguments(strings, module, mountPoints);
290 // Number of consumed elements
292 if (targetNode instanceof ListSchemaNode) {
293 val listNode = targetNode as ListSchemaNode;
294 val keysSize = listNode.keyDefinition.size
296 // every key has to be filled
297 if ((strings.length - consumed) < keysSize) {
300 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
301 val keyValues = new HashMap<QName, Object>();
303 for (key : listNode.keyDefinition) {
304 val uriKeyValue = uriKeyValues.get(i);
306 // key value cannot be NULL
307 if (uriKeyValue.equals(NULL_VALUE)) {
310 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
313 consumed = consumed + i;
314 builder.nodeWithKey(targetNode.QName, keyValues);
317 // Only one instance of node is allowed
318 builder.node(targetNode.QName);
320 if (targetNode instanceof DataNodeContainer) {
321 val remaining = strings.subList(consumed, strings.length);
322 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer, mountPoints);
329 static def DataSchemaNode findInstanceDataChild(DataNodeContainer container, String name) {
330 // FIXME: Add namespace comparison
331 var potentialNode = container.getDataChildByName(name);
332 if(potentialNode.instantiatedDataSchema) {
333 return potentialNode;
335 val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
336 for (caze : allCases) {
337 potentialNode = caze.findInstanceDataChild(name);
338 if(potentialNode !== null) {
339 return potentialNode;
345 static def boolean isInstantiatedDataSchema(DataSchemaNode node) {
347 LeafSchemaNode: return true
348 LeafListSchemaNode: return true
349 ContainerSchemaNode: return true
350 ListSchemaNode: return true
351 default: return false
355 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
356 checkNotNull(uriValue);
357 checkArgument(node instanceof LeafSchemaNode);
358 val urlDecoded = URLDecoder.decode(uriValue);
359 val typedef = (node as LeafSchemaNode).type;
361 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
362 if(decoded === null) {
363 var baseType = RestUtil.resolveBaseTypeFrom(typedef)
364 if(baseType instanceof IdentityrefTypeDefinition) {
365 decoded = toQName(urlDecoded)
368 map.put(node.QName, decoded);
371 private static def String toModuleName(String str) {
373 if (str.contains(":")) {
374 val args = str.split(":");
375 checkArgument(args.size === 2);
382 private def String toNodeName(String str) {
383 if (str.contains(":")) {
384 val args = str.split(":");
385 checkArgument(args.size === 2);
392 private def QName toQName(String name) {
393 val module = name.toModuleName;
394 val node = name.toNodeName;
395 val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
396 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
398 return QName.create(namespace,node);
401 def getRpcDefinition(String name) {
402 return qnameToRpc.get(name.toQName)
405 override onGlobalContextUpdated(SchemaContext context) {
406 this.globalSchema = context;
407 for (operation : context.operations) {
408 val qname = operation.QName;
409 qnameToRpc.put(qname, operation);