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.RestUtil
16 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
17 import org.opendaylight.yangtools.yang.common.QName
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
23 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
24 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
25 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext
33 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
34 import org.slf4j.LoggerFactory
36 import static com.google.common.base.Preconditions.*
38 class ControllerContext implements SchemaServiceListener {
39 val static LOG = LoggerFactory.getLogger(ControllerContext)
40 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 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) return null
144 var latestModule = moduleSchemas.head
145 for (m : moduleSchemas) {
146 if (m.revision.after(latestModule.revision)) {
150 if(latestModule === null) return null
151 uriToModuleName.put(namespace, latestModule.name)
152 module = latestModule.name;
157 def findNamespaceByModule(String module) {
158 var namespace = moduleNameToUri.get(module)
159 if (namespace === null) {
160 val moduleSchemas = schemas.modules.filter[it|it.name.equals(module)]
161 var latestModule = moduleSchemas.head
162 for (m : moduleSchemas) {
163 if (m.revision.after(latestModule.revision)) {
167 if(latestModule === null) return null
168 namespace = latestModule.namespace
169 uriToModuleName.put(namespace, latestModule.name)
174 def CharSequence toRestconfIdentifier(QName qname) {
176 var module = uriToModuleName.get(qname.namespace)
177 if (module === null) {
178 val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
179 if(moduleSchema === null) throw new IllegalArgumentException()
180 uriToModuleName.put(qname.namespace, moduleSchema.name)
181 module = moduleSchema.name;
183 return '''«module»:«qname.localName»''';
186 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
187 for (caze : container.cases) {
188 val ret = caze.childByQName(name)
196 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
197 val ret = container.getDataChildByName(name);
201 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
202 return container.dataNodeChildByQName(name);
205 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
206 return container.dataNodeChildByQName(name);
209 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
213 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
214 var ret = container.getDataChildByName(name);
217 // Find in Choice Cases
218 for (node : container.childNodes) {
219 if (node instanceof ChoiceCaseNode) {
220 val caseNode = (node as ChoiceCaseNode);
221 ret = caseNode.childByQName(name);
231 private def toUriString(Object object) {
232 if(object === null) return "";
233 return URLEncoder.encode(object.toString)
236 private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
237 DataNodeContainer parentNode) {
238 checkNotNull(strings)
239 if (parentNode === null) {
243 return parentNode as DataSchemaNode;
245 val nodeRef = strings.head;
247 val nodeName = nodeRef.toNodeName();
248 val targetNode = parentNode.getDataChildByName(nodeName);
249 if (targetNode === null) {
250 val children = parentNode.childNodes
251 for (child : children) {
252 if (child instanceof ChoiceNode) {
253 val choice = child as ChoiceNode
254 for (caze : choice.cases) {
255 val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
263 if (targetNode instanceof ChoiceNode) {
267 // Number of consumed elements
269 if (targetNode instanceof ListSchemaNode) {
270 val listNode = targetNode as ListSchemaNode;
271 val keysSize = listNode.keyDefinition.size
273 // every key has to be filled
274 if ((strings.length - consumed) < keysSize) {
277 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
278 val keyValues = new HashMap<QName, Object>();
280 for (key : listNode.keyDefinition) {
281 val uriKeyValue = uriKeyValues.get(i);
283 // key value cannot be NULL
284 if (uriKeyValue.equals(NULL_VALUE)) {
287 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
290 consumed = consumed + i;
291 builder.nodeWithKey(targetNode.QName, keyValues);
294 // Only one instance of node is allowed
295 builder.node(targetNode.QName);
297 if (targetNode instanceof DataNodeContainer) {
298 val remaining = strings.subList(consumed, strings.length);
299 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
306 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
307 checkNotNull(uriValue);
308 checkArgument(node instanceof LeafSchemaNode);
309 val urlDecoded = URLDecoder.decode(uriValue);
310 val typedef = (node as LeafSchemaNode).type;
312 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
313 if(decoded === null) {
314 var baseType = RestUtil.resolveBaseTypeFrom(typedef)
315 if(baseType instanceof IdentityrefTypeDefinition) {
316 decoded = toQName(urlDecoded)
319 map.put(node.QName, decoded);
322 private def String toModuleName(String str) {
324 if (str.contains(":")) {
325 val args = str.split(":");
326 checkArgument(args.size === 2);
333 private def String toNodeName(String str) {
334 if (str.contains(":")) {
335 val args = str.split(":");
336 checkArgument(args.size === 2);
343 private def QName toQName(String name) {
344 val module = name.toModuleName;
345 val node = name.toNodeName;
346 val namespace = FluentIterable.from(schemas.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
347 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
349 return QName.create(namespace,node);
352 def getRpcDefinition(String name) {
353 return qnameToRpc.get(name.toQName)
356 override onGlobalContextUpdated(SchemaContext context) {
357 this.schemas = context;
358 for (operation : context.operations) {
359 val qname = operation.QName;
360 qnameToRpc.put(qname, operation);