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