BUG-1281: use SchemaContext lookups
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / ControllerContext.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sal.restconf.impl;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.BiMap;
17 import com.google.common.collect.HashBiMap;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Iterables;
20
21 import java.io.UnsupportedEncodingException;
22 import java.net.URI;
23 import java.net.URLDecoder;
24 import java.net.URLEncoder;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.concurrent.atomic.AtomicReference;
34
35 import javax.ws.rs.core.Response.Status;
36
37 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
38 import org.opendaylight.controller.sal.core.api.mount.MountService;
39 import org.opendaylight.controller.sal.rest.api.Draft02;
40 import org.opendaylight.controller.sal.rest.impl.RestUtil;
41 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
43 import org.opendaylight.yangtools.concepts.Codec;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
53 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public class ControllerContext implements SchemaContextListener {
70     private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
71
72     private final static ControllerContext INSTANCE = new ControllerContext();
73
74     private final static String NULL_VALUE = "null";
75
76     private final static String MOUNT_MODULE = "yang-ext";
77
78     private final static String MOUNT_NODE = "mount";
79
80     public final static String MOUNT = "yang-ext:mount";
81
82     private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
83
84     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
85
86     private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
87
88     private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
89
90     private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
91             new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
92
93     private volatile SchemaContext globalSchema;
94     private volatile MountService mountService;
95
96     public void setGlobalSchema(final SchemaContext globalSchema) {
97         this.globalSchema = globalSchema;
98     }
99
100     public void setMountService(final MountService mountService) {
101         this.mountService = mountService;
102     }
103
104     private ControllerContext() {
105     }
106
107     public static ControllerContext getInstance() {
108         return ControllerContext.INSTANCE;
109     }
110
111     private void checkPreconditions() {
112         if (globalSchema == null) {
113             throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
114         }
115     }
116
117     public void setSchemas(final SchemaContext schemas) {
118         this.onGlobalContextUpdated(schemas);
119     }
120
121     public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
122         return this.toIdentifier(restconfInstance, false);
123     }
124
125     public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
126         return this.toIdentifier(restconfInstance, true);
127     }
128
129     private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
130         this.checkPreconditions();
131
132         final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
133         omitFirstAndLastEmptyString(pathArgs);
134         if (pathArgs.isEmpty()) {
135             return null;
136         }
137
138         String first = pathArgs.iterator().next();
139         final String startModule = ControllerContext.toModuleName(first);
140         if (startModule == null) {
141             throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
142                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
143         }
144
145         InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
146         Module latestModule = globalSchema.findModuleByName(startModule, null);
147         InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
148                 toMountPointIdentifier);
149
150         if (iiWithSchemaNode == null) {
151             throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
152         }
153
154         return iiWithSchemaNode;
155     }
156
157     private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
158         if (list.isEmpty()) {
159             return list;
160         }
161
162         String head = list.iterator().next();
163         if (head.isEmpty()) {
164             list.remove(0);
165         }
166
167         if (list.isEmpty()) {
168             return list;
169         }
170
171         String last = list.get(list.size() - 1);
172         if (last.isEmpty()) {
173             list.remove(list.size() - 1);
174         }
175
176         return list;
177     }
178     public Module findModuleByName(final String moduleName) {
179         this.checkPreconditions();
180         Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
181         return globalSchema.findModuleByName(moduleName, null);
182     }
183
184     public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
185         Preconditions.checkArgument(moduleName != null && mountPoint != null);
186
187         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
188         if (mountPointSchema == null) {
189             return null;
190         }
191
192         return mountPointSchema.findModuleByName(moduleName, null);
193     }
194
195     public Module findModuleByNamespace(final URI namespace) {
196         this.checkPreconditions();
197         Preconditions.checkArgument(namespace != null);
198         return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
199     }
200
201     public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
202         Preconditions.checkArgument(namespace != null && mountPoint != null);
203
204         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
205         if (mountPointSchema == null) {
206             return null;
207         }
208
209         return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
210     }
211
212     public Module findModuleByNameAndRevision(final QName module) {
213         this.checkPreconditions();
214         Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
215
216         return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
217     }
218
219     public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
220         this.checkPreconditions();
221         Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
222                 && mountPoint != null);
223
224         SchemaContext schemaContext = mountPoint.getSchemaContext();
225         return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
226                 module.getRevision());
227     }
228
229     public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
230         this.checkPreconditions();
231
232         final Iterable<PathArgument> elements = path.getPathArguments();
233         PathArgument head = elements.iterator().next();
234         final QName startQName = head.getNodeType();
235         final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
236                 startQName.getRevision());
237         DataNodeContainer node = initialModule;
238         for (final PathArgument element : elements) {
239             QName _nodeType = element.getNodeType();
240             final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
241             if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
242                 return null;
243             }
244             node = (DataNodeContainer) potentialNode;
245         }
246
247         return node;
248     }
249
250     public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
251         this.checkPreconditions();
252
253         final Iterable<PathArgument> elements = path.getPathArguments();
254         final StringBuilder builder = new StringBuilder();
255         PathArgument head = elements.iterator().next();
256         final QName startQName = head.getNodeType();
257         final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
258                 startQName.getRevision());
259         DataNodeContainer node = initialModule;
260         for (final PathArgument element : elements) {
261             QName _nodeType = element.getNodeType();
262             final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
263             if (!ControllerContext.isListOrContainer(potentialNode)) {
264                 return null;
265             }
266             node = ((DataNodeContainer) potentialNode);
267             builder.append(this.convertToRestconfIdentifier(element, node));
268         }
269
270         return builder.toString();
271     }
272
273     public String findModuleNameByNamespace(final URI namespace) {
274         this.checkPreconditions();
275
276         String moduleName = this.uriToModuleName.get(namespace);
277         if (moduleName == null) {
278             final Module module = this.findModuleByNamespace(namespace);
279             if (module != null) {
280                 moduleName = module.getName();
281                 this.uriToModuleName.put(namespace, moduleName);
282             }
283         }
284
285         return moduleName;
286     }
287
288     public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
289         final Module module = this.findModuleByNamespace(mountPoint, namespace);
290         return module == null ? null : module.getName();
291     }
292
293     public URI findNamespaceByModuleName(final String moduleName) {
294         URI namespace = this.moduleNameToUri.get(moduleName);
295         if (namespace == null) {
296             Module module = this.findModuleByName(moduleName);
297             if (module != null) {
298                 URI _namespace = module.getNamespace();
299                 namespace = _namespace;
300                 this.uriToModuleName.put(namespace, moduleName);
301             }
302         }
303         return namespace;
304     }
305
306     public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
307         final Module module = this.findModuleByName(mountPoint, moduleName);
308         return module == null ? null : module.getNamespace();
309     }
310
311     public Set<Module> getAllModules(final MountInstance mountPoint) {
312         this.checkPreconditions();
313
314         SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
315         return schemaContext == null ? null : schemaContext.getModules();
316     }
317
318     public Set<Module> getAllModules() {
319         this.checkPreconditions();
320         return globalSchema.getModules();
321     }
322
323     public CharSequence toRestconfIdentifier(final QName qname) {
324         this.checkPreconditions();
325
326         String module = this.uriToModuleName.get(qname.getNamespace());
327         if (module == null) {
328             final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
329                     qname.getRevision());
330             if (moduleSchema == null) {
331                 return null;
332             }
333
334             this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
335             module = moduleSchema.getName();
336         }
337
338         StringBuilder builder = new StringBuilder();
339         builder.append(module);
340         builder.append(":");
341         builder.append(qname.getLocalName());
342         return builder.toString();
343     }
344
345     public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
346         if (mountPoint == null) {
347             return null;
348         }
349
350         SchemaContext schemaContext = mountPoint.getSchemaContext();
351
352         final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
353                 qname.getRevision());
354         if (moduleSchema == null) {
355             return null;
356         }
357
358         StringBuilder builder = new StringBuilder();
359         builder.append(moduleSchema.getName());
360         builder.append(":");
361         builder.append(qname.getLocalName());
362         return builder.toString();
363     }
364
365     public Module getRestconfModule() {
366         return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
367     }
368
369     public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
370         Module restconfModule = getRestconfModule();
371         if (restconfModule == null) {
372             return null;
373         }
374
375         Set<GroupingDefinition> groupings = restconfModule.getGroupings();
376
377         final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
378             @Override
379             public boolean apply(final GroupingDefinition g) {
380                 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
381             }
382         };
383
384         Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
385
386         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
387
388         List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
389                 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
390         return Iterables.getFirst(instanceDataChildrenByName, null);
391     }
392
393     public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
394         Module restconfModule = inRestconfModule;
395         if (restconfModule == null) {
396             restconfModule = getRestconfModule();
397         }
398
399         if (restconfModule == null) {
400             return null;
401         }
402
403         Set<GroupingDefinition> groupings = restconfModule.getGroupings();
404
405         final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
406             @Override
407             public boolean apply(final GroupingDefinition g) {
408                 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
409             }
410         };
411
412         Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
413
414         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
415
416         List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
417                 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
418         final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
419
420         if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
421             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
422                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
423             return Iterables.getFirst(instances, null);
424         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
425             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
426                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
427             return Iterables.getFirst(instances, null);
428         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
429             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
430                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
431             final DataSchemaNode modules = Iterables.getFirst(instances, null);
432             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
433                     Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
434             return Iterables.getFirst(instances, null);
435         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
436             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
437                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
438             return Iterables.getFirst(instances, null);
439         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
440             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
441                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
442             final DataSchemaNode modules = Iterables.getFirst(instances, null);
443             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
444                     Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
445             return Iterables.getFirst(instances, null);
446         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
447             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
448                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
449             return Iterables.getFirst(instances, null);
450         }
451
452         return null;
453     }
454
455     private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
456         for (final ChoiceCaseNode caze : container.getCases()) {
457             final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
458             if (ret != null) {
459                 return ret;
460             }
461         }
462
463         return null;
464     }
465
466     private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
467         return container.getDataChildByName(name);
468     }
469
470     private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
471         return ControllerContext.dataNodeChildByQName(container, name);
472     }
473
474     private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
475         return ControllerContext.dataNodeChildByQName(container, name);
476     }
477
478     private static DataSchemaNode childByQName(final Module container, final QName name) {
479         return ControllerContext.dataNodeChildByQName(container, name);
480     }
481
482     private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
483         return null;
484     }
485
486     private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
487         DataSchemaNode ret = container.getDataChildByName(name);
488         if (ret == null) {
489             for (final DataSchemaNode node : container.getChildNodes()) {
490                 if ((node instanceof ChoiceNode)) {
491                     final ChoiceNode choiceNode = ((ChoiceNode) node);
492                     DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
493                     if (childByQName != null) {
494                         return childByQName;
495                     }
496                 }
497             }
498         }
499         return ret;
500     }
501
502     private String toUriString(final Object object) throws UnsupportedEncodingException {
503         return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
504     }
505
506     private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
507             final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
508             final boolean returnJustMountPoint) {
509         Preconditions.<List<String>> checkNotNull(strings);
510
511         if (parentNode == null) {
512             return null;
513         }
514
515         if (strings.isEmpty()) {
516             return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
517         }
518
519         String head = strings.iterator().next();
520         final String nodeName = toNodeName(head);
521         final String moduleName = ControllerContext.toModuleName(head);
522
523         DataSchemaNode targetNode = null;
524         if (!Strings.isNullOrEmpty(moduleName)) {
525             if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
526                     && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
527                 if (mountPoint != null) {
528                     throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
529                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
530                 }
531
532                 if (mountService == null) {
533                     throw new RestconfDocumentedException(
534                             "MountService was not found. Finding behind mount points does not work.",
535                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
536                 }
537
538                 final YangInstanceIdentifier partialPath = builder.toInstance();
539                 final MountInstance mount = mountService.getMountPoint(partialPath);
540                 if (mount == null) {
541                     LOG.debug("Instance identifier to missing mount point: {}", partialPath);
542                     throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
543                             ErrorTag.UNKNOWN_ELEMENT);
544                 }
545
546                 final SchemaContext mountPointSchema = mount.getSchemaContext();
547                 if (mountPointSchema == null) {
548                     throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
549                             ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
550                 }
551
552                 if (returnJustMountPoint) {
553                     YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
554                     return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
555                 }
556
557                 if (strings.size() == 1) {
558                     YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
559                     return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
560                 }
561
562                 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
563                 if (moduleNameBehindMountPoint == null) {
564                     throw new RestconfDocumentedException(
565                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
566                             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
567                 }
568
569                 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
570                 if (moduleBehindMountPoint == null) {
571                     throw new RestconfDocumentedException("\"" + moduleName
572                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
573                 }
574
575                 List<String> subList = strings.subList(1, strings.size());
576                 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
577                         returnJustMountPoint);
578             }
579
580             Module module = null;
581             if (mountPoint == null) {
582                 module = globalSchema.findModuleByName(moduleName, null);
583                 if (module == null) {
584                     throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
585                             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
586                 }
587             } else {
588                 SchemaContext schemaContext = mountPoint.getSchemaContext();
589                 if (schemaContext != null) {
590                     module = schemaContext.findModuleByName(moduleName, null);
591                 } else {
592                     module = null;
593                 }
594                 if (module == null) {
595                     throw new RestconfDocumentedException("\"" + moduleName
596                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
597                 }
598             }
599
600             targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
601             if (targetNode == null) {
602                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
603                         + "\" was not found in parent data node.\n" + " 2. \"" + head
604                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
605                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
606             }
607         } else {
608             final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
609             if (potentialSchemaNodes.size() > 1) {
610                 final StringBuilder strBuilder = new StringBuilder();
611                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
612                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
613                 }
614
615                 throw new RestconfDocumentedException(
616                         "URI has bad format. Node \""
617                                 + nodeName
618                                 + "\" is added as augment from more than one module. "
619                                 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
620                                 + "\nThe node is added as augment from modules with namespaces:\n"
621                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
622             }
623
624             if (potentialSchemaNodes.isEmpty()) {
625                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
626                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
627             }
628
629             targetNode = potentialSchemaNodes.iterator().next();
630         }
631
632         if (!ControllerContext.isListOrContainer(targetNode)) {
633             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
634                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
635         }
636
637         int consumed = 1;
638         if ((targetNode instanceof ListSchemaNode)) {
639             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
640             final int keysSize = listNode.getKeyDefinition().size();
641             if ((strings.size() - consumed) < keysSize) {
642                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
643                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
644             }
645
646             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
647             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
648             int i = 0;
649             for (final QName key : listNode.getKeyDefinition()) {
650                 {
651                     final String uriKeyValue = uriKeyValues.get(i);
652                     if (uriKeyValue.equals(NULL_VALUE)) {
653                         throw new RestconfDocumentedException("URI has bad format. List \""
654                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
655                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
656                     }
657
658                     this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
659                     i++;
660                 }
661             }
662
663             consumed = consumed + i;
664             builder.nodeWithKey(targetNode.getQName(), keyValues);
665         } else {
666             builder.node(targetNode.getQName());
667         }
668
669         if ((targetNode instanceof DataNodeContainer)) {
670             final List<String> remaining = strings.subList(consumed, strings.size());
671             return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
672                     returnJustMountPoint);
673         }
674
675         return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
676     }
677
678     public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
679             final URI namespace) {
680         Preconditions.<URI> checkNotNull(namespace);
681
682         final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
683
684         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
685             @Override
686             public boolean apply(final DataSchemaNode node) {
687                 return Objects.equal(node.getQName().getNamespace(), namespace);
688             }
689         };
690
691         Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
692         return Iterables.getFirst(result, null);
693     }
694
695     public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
696         Preconditions.<DataNodeContainer> checkNotNull(container);
697         Preconditions.<String> checkNotNull(name);
698
699         List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
700         this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
701         return instantiatedDataNodeContainers;
702     }
703
704     private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
705             final DataNodeContainer container, final String name) {
706
707         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
708             @Override
709             public boolean apply(final DataSchemaNode node) {
710                 return Objects.equal(node.getQName().getLocalName(), name);
711             }
712         };
713
714         Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
715
716         // Can't combine this loop with the filter above because the filter is
717         // lazily-applied by Iterables.filter.
718         for (final DataSchemaNode potentialNode : nodes) {
719             if (this.isInstantiatedDataSchema(potentialNode)) {
720                 potentialSchemaNodes.add(potentialNode);
721             }
722         }
723
724         Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
725
726         final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
727             @Override
728             public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
729                 return node.getCases();
730             }
731         };
732
733         Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
734                 choiceFunction);
735
736         final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
737         for (final ChoiceCaseNode caze : allCases) {
738             this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
739         }
740     }
741
742     public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
743         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
744                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
745                 || node instanceof AnyXmlSchemaNode;
746     }
747
748     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
749             final MountInstance mountPoint) {
750         Preconditions.<String> checkNotNull(uriValue);
751         Preconditions.checkArgument((node instanceof LeafSchemaNode));
752
753         final String urlDecoded = urlPathArgDecode(uriValue);
754         final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
755         Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
756
757         Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
758         String additionalInfo = "";
759         if (decoded == null) {
760             TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
761             if ((baseType instanceof IdentityrefTypeDefinition)) {
762                 decoded = this.toQName(urlDecoded);
763                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
764             }
765         }
766
767         if (decoded == null) {
768             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
769                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
770         }
771
772         map.put(node.getQName(), decoded);
773     }
774
775     private static String toModuleName(final String str) {
776         final int idx = str.indexOf(':');
777         if (idx == -1) {
778             return null;
779         }
780
781         // Make sure there is only one occurrence
782         if (str.indexOf(':', idx + 1) != -1) {
783             return null;
784         }
785
786         return str.substring(0, idx);
787     }
788
789     private static String toNodeName(final String str) {
790         final int idx = str.indexOf(':');
791         if (idx == -1) {
792             return str;
793         }
794
795         // Make sure there is only one occurrence
796         if (str.indexOf(':', idx + 1) != -1) {
797             return str;
798         }
799
800         return str.substring(idx + 1);
801     }
802
803     private QName toQName(final String name) {
804         final String module = toModuleName(name);
805         final String node = toNodeName(name);
806         final Module m = globalSchema.findModuleByName(module, null);
807         return m == null ? null : QName.create(m.getQNameModule(), node);
808     }
809
810     private static boolean isListOrContainer(final DataSchemaNode node) {
811         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
812     }
813
814     public RpcDefinition getRpcDefinition(final String name) {
815         final QName validName = this.toQName(name);
816         return validName == null ? null : this.qnameToRpc.get().get(validName);
817     }
818
819     @Override
820     public void onGlobalContextUpdated(final SchemaContext context) {
821         if (context != null) {
822             final Collection<RpcDefinition> defs = context.getOperations();
823             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
824
825             for (final RpcDefinition operation : defs) {
826                 newMap.put(operation.getQName(), operation);
827             }
828
829             // FIXME: still not completely atomic
830             this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
831             this.setGlobalSchema(context);
832         }
833     }
834
835     public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
836         try {
837             List<String> decodedPathArgs = new ArrayList<String>();
838             for (final String pathArg : strings) {
839                 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
840                 decodedPathArgs.add(_decode);
841             }
842             return decodedPathArgs;
843         } catch (UnsupportedEncodingException e) {
844             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
845                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
846         }
847     }
848
849     public String urlPathArgDecode(final String pathArg) {
850         if (pathArg != null) {
851             try {
852                 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
853             } catch (UnsupportedEncodingException e) {
854                 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
855                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
856             }
857         }
858
859         return null;
860     }
861
862     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
863         if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
864             return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
865         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
866             return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
867         } else if (argument != null && node != null) {
868             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
869         } else {
870             throw new IllegalArgumentException("Unhandled parameter types: "
871                     + Arrays.<Object> asList(argument, node).toString());
872         }
873     }
874
875     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
876         StringBuilder builder = new StringBuilder();
877         builder.append("/");
878         QName nodeType = argument.getNodeType();
879         builder.append(this.toRestconfIdentifier(nodeType));
880         return builder.toString();
881     }
882
883     private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
884             final ListSchemaNode node) {
885         QName nodeType = argument.getNodeType();
886         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
887         final Map<QName, Object> keyValues = argument.getKeyValues();
888
889         StringBuilder builder = new StringBuilder();
890         builder.append("/");
891         builder.append(nodeIdentifier);
892         builder.append("/");
893
894         List<QName> keyDefinition = node.getKeyDefinition();
895         boolean hasElements = false;
896         for (final QName key : keyDefinition) {
897             if (!hasElements) {
898                 hasElements = true;
899             } else {
900                 builder.append("/");
901             }
902
903             try {
904                 builder.append(this.toUriString(keyValues.get(key)));
905             } catch (UnsupportedEncodingException e) {
906                 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
907                 return null;
908             }
909         }
910
911         return builder.toString();
912     }
913
914     private static DataSchemaNode childByQName(final Object container, final QName name) {
915         if (container instanceof ChoiceCaseNode) {
916             return childByQName((ChoiceCaseNode) container, name);
917         } else if (container instanceof ChoiceNode) {
918             return childByQName((ChoiceNode) container, name);
919         } else if (container instanceof ContainerSchemaNode) {
920             return childByQName((ContainerSchemaNode) container, name);
921         } else if (container instanceof ListSchemaNode) {
922             return childByQName((ListSchemaNode) container, name);
923         } else if (container instanceof DataSchemaNode) {
924             return childByQName((DataSchemaNode) container, name);
925         } else if (container instanceof Module) {
926             return childByQName((Module) container, name);
927         } else {
928             throw new IllegalArgumentException("Unhandled parameter types: "
929                     + Arrays.<Object> asList(container, name).toString());
930         }
931     }
932 }