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
38 class ControllerContext implements SchemaServiceListener {
40 val static ControllerContext INSTANCE = new ControllerContext
42 val static NULL_VALUE = "null"
44 var SchemaContext schemas;
46 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
47 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
48 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
51 if (INSTANCE !== null) {
52 throw new IllegalStateException("Already instantiated");
56 static def getInstance() {
60 private def void checkPreconditions() {
61 if (schemas === null) {
62 throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
66 def setSchemas(SchemaContext schemas) {
67 onGlobalContextUpdated(schemas)
70 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
71 val ret = InstanceIdentifier.builder();
72 val pathArgs = restconfInstance.split("/");
76 if (pathArgs.head.empty) {
79 val schemaNode = ret.collectPathArguments(pathArgs, restconfInstance.findModule);
80 if (schemaNode === null) {
83 return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
86 private def findModule(String restconfInstance) {
88 checkNotNull(restconfInstance);
89 val pathArgs = restconfInstance.split("/");
93 val modulWithFirstYangStatement = pathArgs.filter[s|s.contains(":")].head
94 val startModule = modulWithFirstYangStatement.toModuleName();
95 return getLatestModule(startModule)
98 private def getLatestModule(String moduleName) {
100 checkArgument(moduleName !== null && !moduleName.empty)
101 val modules = schemas.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 = schemas.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 = schemas.findModuleByNamespace(namespace);
144 if(moduleSchemas === null) throw new IllegalArgumentException()
145 var latestModule = moduleSchemas.head
146 for (m : moduleSchemas) {
147 if (m.revision.after(latestModule.revision)) {
151 if(latestModule === null) throw new IllegalArgumentException()
152 uriToModuleName.put(namespace, latestModule.name)
153 module = latestModule.name;
158 def CharSequence toRestconfIdentifier(QName qname) {
160 var module = uriToModuleName.get(qname.namespace)
161 if (module === null) {
162 val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
163 if(moduleSchema === null) throw new IllegalArgumentException()
164 uriToModuleName.put(qname.namespace, moduleSchema.name)
165 module = moduleSchema.name;
167 return '''«module»:«qname.localName»''';
170 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
171 for (caze : container.cases) {
172 val ret = caze.childByQName(name)
180 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
181 val ret = container.getDataChildByName(name);
185 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
186 return container.dataNodeChildByQName(name);
189 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
190 return container.dataNodeChildByQName(name);
193 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
197 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
198 var ret = container.getDataChildByName(name);
201 // Find in Choice Cases
202 for (node : container.childNodes) {
203 if (node instanceof ChoiceCaseNode) {
204 val caseNode = (node as ChoiceCaseNode);
205 ret = caseNode.childByQName(name);
215 private def toUriString(Object object) {
216 if(object === null) return "";
217 return URLEncoder.encode(object.toString)
220 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
221 DataNodeContainer parentNode) {
222 checkNotNull(strings)
223 if (parentNode === null) {
227 return parentNode as DataSchemaNode;
229 val nodeRef = strings.head;
231 val nodeName = nodeRef.toNodeName();
232 val targetNode = parentNode.getDataChildByName(nodeName);
233 if (targetNode === null) {
234 val children = parentNode.childNodes
235 for (child : children) {
236 if (child instanceof ChoiceNode) {
237 val choice = child as ChoiceNode
238 for (caze : choice.cases) {
239 val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
247 if (targetNode instanceof ChoiceNode) {
251 // Number of consumed elements
253 if (targetNode instanceof ListSchemaNode) {
254 val listNode = targetNode as ListSchemaNode;
255 val keysSize = listNode.keyDefinition.size
257 // every key has to be filled
258 if ((strings.length - consumed) < keysSize) {
261 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
262 val keyValues = new HashMap<QName, Object>();
264 for (key : listNode.keyDefinition) {
265 val uriKeyValue = uriKeyValues.get(i);
267 // key value cannot be NULL
268 if (uriKeyValue.equals(NULL_VALUE)) {
271 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
274 consumed = consumed + i;
275 builder.nodeWithKey(targetNode.QName, keyValues);
278 // Only one instance of node is allowed
279 builder.node(targetNode.QName);
281 if (targetNode instanceof DataNodeContainer) {
282 val remaining = strings.subList(consumed, strings.length);
283 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
290 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
291 checkNotNull(uriValue);
292 checkArgument(node instanceof LeafSchemaNode);
293 val urlDecoded = URLDecoder.decode(uriValue);
294 val typedef = (node as LeafSchemaNode).type;
295 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
296 if(decoded == null) {
297 var baseType = typedef
298 while (baseType.baseType != null) {
299 baseType = baseType.baseType;
301 if(baseType instanceof IdentityrefTypeDefinition) {
302 decoded = toQName(urlDecoded)
305 map.put(node.QName, decoded);
308 private def String toModuleName(String str) {
310 if (str.contains(":")) {
311 val args = str.split(":");
312 checkArgument(args.size === 2);
319 private def String toNodeName(String str) {
320 if (str.contains(":")) {
321 val args = str.split(":");
322 checkArgument(args.size === 2);
329 private def QName toQName(String name) {
330 val module = name.toModuleName;
331 val node = name.toNodeName;
332 val namespace = moduleNameToUri.get(module);
333 return new QName(namespace, null, node);
336 def getRpcDefinition(String name) {
337 return qnameToRpc.get(name.toQName)
340 override onGlobalContextUpdated(SchemaContext context) {
341 this.schemas = context;
342 for (operation : context.operations) {
343 val qname = new QName(operation.QName.namespace, null, operation.QName.localName);
344 qnameToRpc.put(qname, operation);
349 * Resolve target type from leafref type.
351 * According to RFC 6020 referenced element has to be leaf (chapter 9.9).
352 * Therefore if other element is referenced then null value is returned.
354 * Currently only cases without path-predicate are supported.
358 * data schema node which contains reference
359 * @return type if leaf is referenced and it is possible to find referenced
360 * node in schema context. In other cases null value is returned
362 def LeafSchemaNode resolveTypeFromLeafref(LeafrefTypeDefinition leafRef, DataSchemaNode schemaNode) {
363 val xPath = leafRef.getPathStatement();
364 val module = SchemaContextUtil.findParentModule(schemas, schemaNode);
366 var SchemaNode foundSchemaNode
367 if (xPath.isAbsolute()) {
368 foundSchemaNode = SchemaContextUtil.findDataSchemaNode(schemas, module, xPath);
370 foundSchemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemas, module, schemaNode, xPath);
373 if (foundSchemaNode instanceof LeafSchemaNode) {
374 return foundSchemaNode as LeafSchemaNode;