1 package org.opendaylight.controller.sal.restconf.impl
3 import com.google.common.collect.BiMap
4 import com.google.common.collect.HashBiMap
6 import java.net.URLDecoder
7 import java.net.URLEncoder
8 import java.util.HashMap
11 import java.util.concurrent.ConcurrentHashMap
12 import javax.ws.rs.core.Response
13 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener
14 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
15 import org.opendaylight.yangtools.yang.common.QName
16 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
17 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
21 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
22 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
23 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
24 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
25 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
26 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
27 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
28 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext
30 import org.opendaylight.yangtools.yang.model.api.SchemaNode
31 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition
32 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil
34 import static com.google.common.base.Preconditions.*
35 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
36 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
37 import org.slf4j.LoggerFactory
38 import com.google.common.collect.FluentIterable
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 private 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) throw new IllegalArgumentException()
146 var latestModule = moduleSchemas.head
147 for (m : moduleSchemas) {
148 if (m.revision.after(latestModule.revision)) {
152 if(latestModule === null) throw new IllegalArgumentException()
153 uriToModuleName.put(namespace, latestModule.name)
154 module = latestModule.name;
159 def CharSequence toRestconfIdentifier(QName qname) {
161 var module = uriToModuleName.get(qname.namespace)
162 if (module === null) {
163 val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
164 if(moduleSchema === null) throw new IllegalArgumentException()
165 uriToModuleName.put(qname.namespace, moduleSchema.name)
166 module = moduleSchema.name;
168 return '''«module»:«qname.localName»''';
171 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
172 for (caze : container.cases) {
173 val ret = caze.childByQName(name)
181 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
182 val ret = container.getDataChildByName(name);
186 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
187 return container.dataNodeChildByQName(name);
190 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
191 return container.dataNodeChildByQName(name);
194 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
198 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
199 var ret = container.getDataChildByName(name);
202 // Find in Choice Cases
203 for (node : container.childNodes) {
204 if (node instanceof ChoiceCaseNode) {
205 val caseNode = (node as ChoiceCaseNode);
206 ret = caseNode.childByQName(name);
216 private def toUriString(Object object) {
217 if(object === null) return "";
218 return URLEncoder.encode(object.toString)
221 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
222 DataNodeContainer parentNode) {
223 checkNotNull(strings)
224 if (parentNode === null) {
228 return parentNode as DataSchemaNode;
230 val nodeRef = strings.head;
232 val nodeName = nodeRef.toNodeName();
233 val targetNode = parentNode.getDataChildByName(nodeName);
234 if (targetNode === null) {
235 val children = parentNode.childNodes
236 for (child : children) {
237 if (child instanceof ChoiceNode) {
238 val choice = child as ChoiceNode
239 for (caze : choice.cases) {
240 val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
248 if (targetNode instanceof ChoiceNode) {
252 // Number of consumed elements
254 if (targetNode instanceof ListSchemaNode) {
255 val listNode = targetNode as ListSchemaNode;
256 val keysSize = listNode.keyDefinition.size
258 // every key has to be filled
259 if ((strings.length - consumed) < keysSize) {
262 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
263 val keyValues = new HashMap<QName, Object>();
265 for (key : listNode.keyDefinition) {
266 val uriKeyValue = uriKeyValues.get(i);
268 // key value cannot be NULL
269 if (uriKeyValue.equals(NULL_VALUE)) {
272 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
275 consumed = consumed + i;
276 builder.nodeWithKey(targetNode.QName, keyValues);
279 // Only one instance of node is allowed
280 builder.node(targetNode.QName);
282 if (targetNode instanceof DataNodeContainer) {
283 val remaining = strings.subList(consumed, strings.length);
284 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
291 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
292 checkNotNull(uriValue);
293 checkArgument(node instanceof LeafSchemaNode);
294 val urlDecoded = URLDecoder.decode(uriValue);
295 val typedef = (node as LeafSchemaNode).type;
297 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
298 if(decoded == null) {
299 var baseType = typedef
300 while (baseType.baseType != null) {
301 baseType = baseType.baseType;
303 if(baseType instanceof IdentityrefTypeDefinition) {
304 decoded = toQName(urlDecoded)
307 map.put(node.QName, decoded);
310 private def String toModuleName(String str) {
312 if (str.contains(":")) {
313 val args = str.split(":");
314 checkArgument(args.size === 2);
321 private def String toNodeName(String str) {
322 if (str.contains(":")) {
323 val args = str.split(":");
324 checkArgument(args.size === 2);
331 private def QName toQName(String name) {
332 val module = name.toModuleName;
333 val node = name.toNodeName;
334 val namespace = FluentIterable.from(schemas.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
335 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
337 return QName.create(namespace,node);
340 def getRpcDefinition(String name) {
341 return qnameToRpc.get(name.toQName)
344 override onGlobalContextUpdated(SchemaContext context) {
345 this.schemas = context;
346 for (operation : context.operations) {
347 val qname = operation.QName;
348 qnameToRpc.put(qname, operation);
353 * Resolve target type from leafref type.
355 * According to RFC 6020 referenced element has to be leaf (chapter 9.9).
356 * Therefore if other element is referenced then null value is returned.
358 * Currently only cases without path-predicate are supported.
362 * data schema node which contains reference
363 * @return type if leaf is referenced and it is possible to find referenced
364 * node in schema context. In other cases null value is returned
366 def LeafSchemaNode resolveTypeFromLeafref(LeafrefTypeDefinition leafRef, DataSchemaNode schemaNode) {
367 val xPath = leafRef.getPathStatement();
368 val module = SchemaContextUtil.findParentModule(schemas, schemaNode);
370 var SchemaNode foundSchemaNode
371 if (xPath.isAbsolute()) {
372 foundSchemaNode = SchemaContextUtil.findDataSchemaNode(schemas, module, xPath);
374 foundSchemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemas, module, schemaNode, xPath);
377 if (foundSchemaNode instanceof LeafSchemaNode) {
378 return foundSchemaNode as LeafSchemaNode;