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
37 class ControllerContext implements SchemaServiceListener {
39 val static ControllerContext INSTANCE = new ControllerContext
41 val static NULL_VALUE = "null"
43 var SchemaContext schemas;
45 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
46 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
47 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
50 if (INSTANCE !== null) {
51 throw new IllegalStateException("Already instantiated");
55 static def getInstance() {
59 private def void checkPreconditions() {
60 if (schemas === null) {
61 throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
65 def setSchemas(SchemaContext schemas) {
66 onGlobalContextUpdated(schemas)
69 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
70 val ret = InstanceIdentifier.builder();
71 val pathArgs = restconfInstance.split("/");
75 if (pathArgs.head.empty) {
78 val schemaNode = ret.collectPathArguments(pathArgs, restconfInstance.findModule);
79 if (schemaNode === null) {
82 return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
85 private def findModule(String restconfInstance) {
87 checkNotNull(restconfInstance);
88 val pathArgs = restconfInstance.split("/");
92 val modulWithFirstYangStatement = pathArgs.filter[s|s.contains(":")].head
93 val startModule = modulWithFirstYangStatement.toModuleName();
94 return getLatestModule(startModule)
97 private def getLatestModule(String moduleName) {
99 checkArgument(moduleName !== null && !moduleName.empty)
100 val modules = schemas.modules.filter[m|m.name == moduleName]
101 var latestModule = modules.head
102 for (module : modules) {
103 if (module.revision.after(latestModule.revision)) {
104 latestModule = module
110 def String toFullRestconfIdentifier(InstanceIdentifier path) {
112 val elements = path.path;
113 val ret = new StringBuilder();
114 val startQName = elements.get(0).nodeType;
115 val initialModule = schemas.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
116 var node = initialModule as DataSchemaNode;
117 for (element : elements) {
118 node = node.childByQName(element.nodeType);
119 ret.append(element.toRestconfIdentifier(node));
124 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
125 '''/«argument.nodeType.toRestconfIdentifier()»'''
128 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
129 val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
130 val keyValues = argument.keyValues;
131 return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
134 private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
135 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
138 def findModuleByNamespace(URI namespace) {
140 var module = uriToModuleName.get(namespace)
141 if (module === null) {
142 val moduleSchemas = schemas.findModuleByNamespace(namespace);
143 if(moduleSchemas === null) throw new IllegalArgumentException()
144 var latestModule = moduleSchemas.head
145 for (m : moduleSchemas) {
146 if (m.revision.after(latestModule.revision)) {
150 if(latestModule === null) throw new IllegalArgumentException()
151 uriToModuleName.put(namespace, latestModule.name)
152 module = latestModule.name;
157 def CharSequence toRestconfIdentifier(QName qname) {
159 var module = uriToModuleName.get(qname.namespace)
160 if (module === null) {
161 val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
162 if(moduleSchema === null) throw new IllegalArgumentException()
163 uriToModuleName.put(qname.namespace, moduleSchema.name)
164 module = moduleSchema.name;
166 return '''«module»:«qname.localName»''';
169 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
170 for (caze : container.cases) {
171 val ret = caze.childByQName(name)
179 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
180 val ret = container.getDataChildByName(name);
184 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
185 return container.dataNodeChildByQName(name);
188 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
189 return container.dataNodeChildByQName(name);
192 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
196 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
197 var ret = container.getDataChildByName(name);
200 // Find in Choice Cases
201 for (node : container.childNodes) {
202 if (node instanceof ChoiceCaseNode) {
203 val caseNode = (node as ChoiceCaseNode);
204 ret = caseNode.childByQName(name);
214 private def toUriString(Object object) {
215 if(object === null) return "";
216 return URLEncoder.encode(object.toString)
219 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
220 DataNodeContainer parentNode) {
221 checkNotNull(strings)
222 if (parentNode === null) {
226 return parentNode as DataSchemaNode;
228 val nodeRef = strings.head;
230 val nodeName = nodeRef.toNodeName();
231 val targetNode = parentNode.getDataChildByName(nodeName);
232 if (targetNode === null) {
233 val children = parentNode.childNodes
234 for (child : children) {
235 if (child instanceof ChoiceNode) {
236 val choice = child as ChoiceNode
237 for (caze : choice.cases) {
238 val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
246 if (targetNode instanceof ChoiceNode) {
250 // Number of consumed elements
252 if (targetNode instanceof ListSchemaNode) {
253 val listNode = targetNode as ListSchemaNode;
254 val keysSize = listNode.keyDefinition.size
256 // every key has to be filled
257 if ((strings.length - consumed) < keysSize) {
260 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
261 val keyValues = new HashMap<QName, Object>();
263 for (key : listNode.keyDefinition) {
264 val uriKeyValue = uriKeyValues.get(i);
266 // key value cannot be NULL
267 if (uriKeyValue.equals(NULL_VALUE)) {
270 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
273 consumed = consumed + i;
274 builder.nodeWithKey(targetNode.QName, keyValues);
277 // Only one instance of node is allowed
278 builder.node(targetNode.QName);
280 if (targetNode instanceof DataNodeContainer) {
281 val remaining = strings.subList(consumed, strings.length);
282 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
289 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
290 checkNotNull(uriValue);
291 checkArgument(node instanceof LeafSchemaNode);
292 val urlDecoded = URLDecoder.decode(uriValue);
293 val typedef = (node as LeafSchemaNode).type;
294 val decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
295 map.put(node.QName, decoded);
298 private def String toModuleName(String str) {
300 if (str.contains(":")) {
301 val args = str.split(":");
302 checkArgument(args.size === 2);
309 private def String toNodeName(String str) {
310 if (str.contains(":")) {
311 val args = str.split(":");
312 checkArgument(args.size === 2);
319 private def QName toQName(String name) {
320 val module = name.toModuleName;
321 val node = name.toNodeName;
322 val namespace = moduleNameToUri.get(module);
323 return new QName(namespace, null, node);
326 def getRpcDefinition(String name) {
327 return qnameToRpc.get(name.toQName)
330 override onGlobalContextUpdated(SchemaContext context) {
331 this.schemas = context;
332 for (operation : context.operations) {
333 val qname = new QName(operation.QName.namespace, null, operation.QName.localName);
334 qnameToRpc.put(qname, operation);
339 * Resolve target type from leafref type.
341 * According to RFC 6020 referenced element has to be leaf (chapter 9.9).
342 * Therefore if other element is referenced then null value is returned.
344 * Currently only cases without path-predicate are supported.
348 * data schema node which contains reference
349 * @return type if leaf is referenced and it is possible to find referenced
350 * node in schema context. In other cases null value is returned
352 def LeafSchemaNode resolveTypeFromLeafref(LeafrefTypeDefinition leafRef, DataSchemaNode schemaNode) {
353 val xPath = leafRef.getPathStatement();
354 val module = SchemaContextUtil.findParentModule(schemas, schemaNode);
356 var SchemaNode foundSchemaNode
357 if (xPath.isAbsolute()) {
358 foundSchemaNode = SchemaContextUtil.findDataSchemaNode(schemas, module, xPath);
360 foundSchemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemas, module, schemaNode, xPath);
363 if (foundSchemaNode instanceof LeafSchemaNode) {
364 return foundSchemaNode as LeafSchemaNode;