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.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.data.impl.codec.TypeDefinitionAwareCodec
23 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
24 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
25 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
26 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
27 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
28 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext
32 import org.opendaylight.yangtools.yang.model.api.SchemaNode
33 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
34 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition
35 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil
36 import org.slf4j.LoggerFactory
38 import static com.google.common.base.Preconditions.*
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"
45 var SchemaContext schemas;
47 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
48 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
49 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
52 if (INSTANCE !== null) {
53 throw new IllegalStateException("Already instantiated");
57 static def getInstance() {
61 private def void checkPreconditions() {
62 if (schemas === null) {
63 throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
67 def setSchemas(SchemaContext schemas) {
68 onGlobalContextUpdated(schemas)
71 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
72 val ret = InstanceIdentifier.builder();
73 val pathArgs = restconfInstance.split("/");
77 if (pathArgs.head.empty) {
80 val schemaNode = ret.collectPathArguments(pathArgs, restconfInstance.findModule);
81 if (schemaNode === null) {
84 return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
87 private def findModule(String restconfInstance) {
89 checkNotNull(restconfInstance);
90 val pathArgs = restconfInstance.split("/");
94 val modulWithFirstYangStatement = pathArgs.filter[s|s.contains(":")].head
95 val startModule = modulWithFirstYangStatement.toModuleName();
96 return getLatestModule(startModule)
99 def getLatestModule(String moduleName) {
101 checkArgument(moduleName !== null && !moduleName.empty)
102 val modules = schemas.modules.filter[m|m.name == moduleName]
103 var latestModule = modules.head
104 for (module : modules) {
105 if (module.revision.after(latestModule.revision)) {
106 latestModule = module
112 def String toFullRestconfIdentifier(InstanceIdentifier path) {
114 val elements = path.path;
115 val ret = new StringBuilder();
116 val startQName = elements.get(0).nodeType;
117 val initialModule = schemas.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
118 var node = initialModule as DataSchemaNode;
119 for (element : elements) {
120 node = node.childByQName(element.nodeType);
121 ret.append(element.toRestconfIdentifier(node));
126 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
127 '''/«argument.nodeType.toRestconfIdentifier()»'''
130 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
131 val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
132 val keyValues = argument.keyValues;
133 return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
136 private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
137 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
140 def findModuleByNamespace(URI namespace) {
142 var module = uriToModuleName.get(namespace)
143 if (module === null) {
144 val moduleSchemas = schemas.findModuleByNamespace(namespace);
145 if(moduleSchemas === null) return null
146 var latestModule = moduleSchemas.head
147 for (m : moduleSchemas) {
148 if (m.revision.after(latestModule.revision)) {
152 if(latestModule === null) return null
153 uriToModuleName.put(namespace, latestModule.name)
154 module = latestModule.name;
159 def findNamespaceByModule(String module) {
160 var namespace = moduleNameToUri.get(module)
161 if (namespace === null) {
162 val moduleSchemas = schemas.modules.filter[it|it.name.equals(module)]
163 var latestModule = moduleSchemas.head
164 for (m : moduleSchemas) {
165 if (m.revision.after(latestModule.revision)) {
169 if(latestModule === null) return null
170 namespace = latestModule.namespace
171 uriToModuleName.put(namespace, latestModule.name)
176 def CharSequence toRestconfIdentifier(QName qname) {
178 var module = uriToModuleName.get(qname.namespace)
179 if (module === null) {
180 val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
181 if(moduleSchema === null) throw new IllegalArgumentException()
182 uriToModuleName.put(qname.namespace, moduleSchema.name)
183 module = moduleSchema.name;
185 return '''«module»:«qname.localName»''';
188 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
189 for (caze : container.cases) {
190 val ret = caze.childByQName(name)
198 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
199 val ret = container.getDataChildByName(name);
203 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
204 return container.dataNodeChildByQName(name);
207 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
208 return container.dataNodeChildByQName(name);
211 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
215 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
216 var ret = container.getDataChildByName(name);
219 // Find in Choice Cases
220 for (node : container.childNodes) {
221 if (node instanceof ChoiceCaseNode) {
222 val caseNode = (node as ChoiceCaseNode);
223 ret = caseNode.childByQName(name);
233 private def toUriString(Object object) {
234 if(object === null) return "";
235 return URLEncoder.encode(object.toString)
238 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
239 DataNodeContainer parentNode) {
240 checkNotNull(strings)
241 if (parentNode === null) {
245 return parentNode as DataSchemaNode;
247 val nodeRef = strings.head;
249 val nodeName = nodeRef.toNodeName();
250 val targetNode = parentNode.getDataChildByName(nodeName);
251 if (targetNode === null) {
252 val children = parentNode.childNodes
253 for (child : children) {
254 if (child instanceof ChoiceNode) {
255 val choice = child as ChoiceNode
256 for (caze : choice.cases) {
257 val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
265 if (targetNode instanceof ChoiceNode) {
269 // Number of consumed elements
271 if (targetNode instanceof ListSchemaNode) {
272 val listNode = targetNode as ListSchemaNode;
273 val keysSize = listNode.keyDefinition.size
275 // every key has to be filled
276 if ((strings.length - consumed) < keysSize) {
279 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
280 val keyValues = new HashMap<QName, Object>();
282 for (key : listNode.keyDefinition) {
283 val uriKeyValue = uriKeyValues.get(i);
285 // key value cannot be NULL
286 if (uriKeyValue.equals(NULL_VALUE)) {
289 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
292 consumed = consumed + i;
293 builder.nodeWithKey(targetNode.QName, keyValues);
296 // Only one instance of node is allowed
297 builder.node(targetNode.QName);
299 if (targetNode instanceof DataNodeContainer) {
300 val remaining = strings.subList(consumed, strings.length);
301 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
308 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
309 checkNotNull(uriValue);
310 checkArgument(node instanceof LeafSchemaNode);
311 val urlDecoded = URLDecoder.decode(uriValue);
312 val typedef = (node as LeafSchemaNode).type;
314 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
315 if(decoded === null) {
316 var baseType = typedef
317 while (baseType.baseType !== null) {
318 baseType = baseType.baseType;
320 if(baseType instanceof IdentityrefTypeDefinition) {
321 decoded = toQName(urlDecoded)
324 map.put(node.QName, decoded);
327 private def String toModuleName(String str) {
329 if (str.contains(":")) {
330 val args = str.split(":");
331 checkArgument(args.size === 2);
338 private def String toNodeName(String str) {
339 if (str.contains(":")) {
340 val args = str.split(":");
341 checkArgument(args.size === 2);
348 private def QName toQName(String name) {
349 val module = name.toModuleName;
350 val node = name.toNodeName;
351 val namespace = FluentIterable.from(schemas.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
352 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
354 return QName.create(namespace,node);
357 def getRpcDefinition(String name) {
358 return qnameToRpc.get(name.toQName)
361 override onGlobalContextUpdated(SchemaContext context) {
362 this.schemas = context;
363 for (operation : context.operations) {
364 val qname = operation.QName;
365 qnameToRpc.put(qname, operation);
370 * Resolve target type from leafref type.
372 * According to RFC 6020 referenced element has to be leaf (chapter 9.9).
373 * Therefore if other element is referenced then null value is returned.
375 * Currently only cases without path-predicate are supported.
379 * data schema node which contains reference
380 * @return type if leaf is referenced and it is possible to find referenced
381 * node in schema context. In other cases null value is returned
383 def LeafSchemaNode resolveTypeFromLeafref(LeafrefTypeDefinition leafRef, DataSchemaNode schemaNode) {
384 val xPath = leafRef.getPathStatement();
385 val module = SchemaContextUtil.findParentModule(schemas, schemaNode);
387 var SchemaNode foundSchemaNode
388 if (xPath.isAbsolute()) {
389 foundSchemaNode = SchemaContextUtil.findDataSchemaNode(schemas, module, xPath);
391 foundSchemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemas, module, schemaNode, xPath);
394 if (foundSchemaNode instanceof LeafSchemaNode) {
395 return foundSchemaNode as LeafSchemaNode;