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.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     private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
370         @Override
371         public boolean apply(final GroupingDefinition g) {
372             return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
373         }
374     };
375
376     public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
377         Module restconfModule = getRestconfModule();
378         if (restconfModule == null) {
379             return null;
380         }
381
382         Set<GroupingDefinition> groupings = restconfModule.getGroupings();
383
384         Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_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     private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
394         @Override
395         public boolean apply(final GroupingDefinition g) {
396             return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
397         }
398     };
399
400     public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
401         Module restconfModule = inRestconfModule;
402         if (restconfModule == null) {
403             restconfModule = getRestconfModule();
404         }
405
406         if (restconfModule == null) {
407             return null;
408         }
409
410         Set<GroupingDefinition> groupings = restconfModule.getGroupings();
411         Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
412         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
413
414         List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
415                 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
416         final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
417
418         if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
419             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
420                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
421             return Iterables.getFirst(instances, null);
422         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
423             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
424                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
425             return Iterables.getFirst(instances, null);
426         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
427             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
428                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
429             final DataSchemaNode modules = Iterables.getFirst(instances, null);
430             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
431                     Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
432             return Iterables.getFirst(instances, null);
433         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
434             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
435                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
436             return Iterables.getFirst(instances, null);
437         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
438             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
439                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
440             final DataSchemaNode modules = Iterables.getFirst(instances, null);
441             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
442                     Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
443             return Iterables.getFirst(instances, null);
444         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
445             List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
446                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447             return Iterables.getFirst(instances, null);
448         }
449
450         return null;
451     }
452
453     private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
454         for (final ChoiceCaseNode caze : container.getCases()) {
455             final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
456             if (ret != null) {
457                 return ret;
458             }
459         }
460
461         return null;
462     }
463
464     private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
465         return container.getDataChildByName(name);
466     }
467
468     private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
469         return ControllerContext.dataNodeChildByQName(container, name);
470     }
471
472     private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
473         return ControllerContext.dataNodeChildByQName(container, name);
474     }
475
476     private static DataSchemaNode childByQName(final Module container, final QName name) {
477         return ControllerContext.dataNodeChildByQName(container, name);
478     }
479
480     private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
481         return null;
482     }
483
484     private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
485         DataSchemaNode ret = container.getDataChildByName(name);
486         if (ret == null) {
487             for (final DataSchemaNode node : container.getChildNodes()) {
488                 if ((node instanceof ChoiceNode)) {
489                     final ChoiceNode choiceNode = ((ChoiceNode) node);
490                     DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
491                     if (childByQName != null) {
492                         return childByQName;
493                     }
494                 }
495             }
496         }
497         return ret;
498     }
499
500     private String toUriString(final Object object) throws UnsupportedEncodingException {
501         return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
502     }
503
504     private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
505             final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
506             final boolean returnJustMountPoint) {
507         Preconditions.<List<String>> checkNotNull(strings);
508
509         if (parentNode == null) {
510             return null;
511         }
512
513         if (strings.isEmpty()) {
514             return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
515         }
516
517         String head = strings.iterator().next();
518         final String nodeName = toNodeName(head);
519         final String moduleName = ControllerContext.toModuleName(head);
520
521         DataSchemaNode targetNode = null;
522         if (!Strings.isNullOrEmpty(moduleName)) {
523             if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
524                     && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
525                 if (mountPoint != null) {
526                     throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
527                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
528                 }
529
530                 if (mountService == null) {
531                     throw new RestconfDocumentedException(
532                             "MountService was not found. Finding behind mount points does not work.",
533                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
534                 }
535
536                 final YangInstanceIdentifier partialPath = builder.toInstance();
537                 final MountInstance mount = mountService.getMountPoint(partialPath);
538                 if (mount == null) {
539                     LOG.debug("Instance identifier to missing mount point: {}", partialPath);
540                     throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
541                             ErrorTag.UNKNOWN_ELEMENT);
542                 }
543
544                 final SchemaContext mountPointSchema = mount.getSchemaContext();
545                 if (mountPointSchema == null) {
546                     throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
547                             ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
548                 }
549
550                 if (returnJustMountPoint) {
551                     YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
552                     return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
553                 }
554
555                 if (strings.size() == 1) {
556                     YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
557                     return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
558                 }
559
560                 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
561                 if (moduleNameBehindMountPoint == null) {
562                     throw new RestconfDocumentedException(
563                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
564                             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
565                 }
566
567                 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
568                 if (moduleBehindMountPoint == null) {
569                     throw new RestconfDocumentedException("\"" + moduleName
570                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
571                 }
572
573                 List<String> subList = strings.subList(1, strings.size());
574                 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
575                         returnJustMountPoint);
576             }
577
578             Module module = null;
579             if (mountPoint == null) {
580                 module = globalSchema.findModuleByName(moduleName, null);
581                 if (module == null) {
582                     throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
583                             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
584                 }
585             } else {
586                 SchemaContext schemaContext = mountPoint.getSchemaContext();
587                 if (schemaContext != null) {
588                     module = schemaContext.findModuleByName(moduleName, null);
589                 } else {
590                     module = null;
591                 }
592                 if (module == null) {
593                     throw new RestconfDocumentedException("\"" + moduleName
594                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
595                 }
596             }
597
598             targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
599             if (targetNode == null) {
600                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
601                         + "\" was not found in parent data node.\n" + " 2. \"" + head
602                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
603                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
604             }
605         } else {
606             final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
607             if (potentialSchemaNodes.size() > 1) {
608                 final StringBuilder strBuilder = new StringBuilder();
609                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
610                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
611                 }
612
613                 throw new RestconfDocumentedException(
614                         "URI has bad format. Node \""
615                                 + nodeName
616                                 + "\" is added as augment from more than one module. "
617                                 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
618                                 + "\nThe node is added as augment from modules with namespaces:\n"
619                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
620             }
621
622             if (potentialSchemaNodes.isEmpty()) {
623                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
624                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
625             }
626
627             targetNode = potentialSchemaNodes.iterator().next();
628         }
629
630         if (!ControllerContext.isListOrContainer(targetNode)) {
631             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
632                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
633         }
634
635         int consumed = 1;
636         if ((targetNode instanceof ListSchemaNode)) {
637             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
638             final int keysSize = listNode.getKeyDefinition().size();
639             if ((strings.size() - consumed) < keysSize) {
640                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
641                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
642             }
643
644             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
645             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
646             int i = 0;
647             for (final QName key : listNode.getKeyDefinition()) {
648                 {
649                     final String uriKeyValue = uriKeyValues.get(i);
650                     if (uriKeyValue.equals(NULL_VALUE)) {
651                         throw new RestconfDocumentedException("URI has bad format. List \""
652                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
653                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
654                     }
655
656                     this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
657                     i++;
658                 }
659             }
660
661             consumed = consumed + i;
662             builder.nodeWithKey(targetNode.getQName(), keyValues);
663         } else {
664             builder.node(targetNode.getQName());
665         }
666
667         if ((targetNode instanceof DataNodeContainer)) {
668             final List<String> remaining = strings.subList(consumed, strings.size());
669             return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
670                     returnJustMountPoint);
671         }
672
673         return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
674     }
675
676     public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
677             final URI namespace) {
678         Preconditions.<URI> checkNotNull(namespace);
679
680         final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
681
682         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
683             @Override
684             public boolean apply(final DataSchemaNode node) {
685                 return Objects.equal(node.getQName().getNamespace(), namespace);
686             }
687         };
688
689         Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
690         return Iterables.getFirst(result, null);
691     }
692
693     public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
694         Preconditions.<DataNodeContainer> checkNotNull(container);
695         Preconditions.<String> checkNotNull(name);
696
697         List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
698         this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
699         return instantiatedDataNodeContainers;
700     }
701
702     private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
703         @Override
704         public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
705             return node.getCases();
706         }
707     };
708
709     private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
710             final DataNodeContainer container, final String name) {
711
712         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
713             @Override
714             public boolean apply(final DataSchemaNode node) {
715                 return Objects.equal(node.getQName().getLocalName(), name);
716             }
717         };
718
719         Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
720
721         // Can't combine this loop with the filter above because the filter is
722         // lazily-applied by Iterables.filter.
723         for (final DataSchemaNode potentialNode : nodes) {
724             if (this.isInstantiatedDataSchema(potentialNode)) {
725                 potentialSchemaNodes.add(potentialNode);
726             }
727         }
728
729         Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
730         Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
731
732         final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
733         for (final ChoiceCaseNode caze : allCases) {
734             this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
735         }
736     }
737
738     public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
739         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
740                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
741                 || node instanceof AnyXmlSchemaNode;
742     }
743
744     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
745             final MountInstance mountPoint) {
746         Preconditions.<String> checkNotNull(uriValue);
747         Preconditions.checkArgument((node instanceof LeafSchemaNode));
748
749         final String urlDecoded = urlPathArgDecode(uriValue);
750         final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
751         Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
752
753         Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
754         String additionalInfo = "";
755         if (decoded == null) {
756             TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
757             if ((baseType instanceof IdentityrefTypeDefinition)) {
758                 decoded = this.toQName(urlDecoded);
759                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
760             }
761         }
762
763         if (decoded == null) {
764             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
765                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
766         }
767
768         map.put(node.getQName(), decoded);
769     }
770
771     private static String toModuleName(final String str) {
772         final int idx = str.indexOf(':');
773         if (idx == -1) {
774             return null;
775         }
776
777         // Make sure there is only one occurrence
778         if (str.indexOf(':', idx + 1) != -1) {
779             return null;
780         }
781
782         return str.substring(0, idx);
783     }
784
785     private static String toNodeName(final String str) {
786         final int idx = str.indexOf(':');
787         if (idx == -1) {
788             return str;
789         }
790
791         // Make sure there is only one occurrence
792         if (str.indexOf(':', idx + 1) != -1) {
793             return str;
794         }
795
796         return str.substring(idx + 1);
797     }
798
799     private QName toQName(final String name) {
800         final String module = toModuleName(name);
801         final String node = toNodeName(name);
802         final Module m = globalSchema.findModuleByName(module, null);
803         return m == null ? null : QName.create(m.getQNameModule(), node);
804     }
805
806     private static boolean isListOrContainer(final DataSchemaNode node) {
807         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
808     }
809
810     public RpcDefinition getRpcDefinition(final String name) {
811         final QName validName = this.toQName(name);
812         return validName == null ? null : this.qnameToRpc.get().get(validName);
813     }
814
815     @Override
816     public void onGlobalContextUpdated(final SchemaContext context) {
817         if (context != null) {
818             final Collection<RpcDefinition> defs = context.getOperations();
819             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
820
821             for (final RpcDefinition operation : defs) {
822                 newMap.put(operation.getQName(), operation);
823             }
824
825             // FIXME: still not completely atomic
826             this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
827             this.setGlobalSchema(context);
828         }
829     }
830
831     public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
832         try {
833             List<String> decodedPathArgs = new ArrayList<String>();
834             for (final String pathArg : strings) {
835                 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
836                 decodedPathArgs.add(_decode);
837             }
838             return decodedPathArgs;
839         } catch (UnsupportedEncodingException e) {
840             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
841                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
842         }
843     }
844
845     public String urlPathArgDecode(final String pathArg) {
846         if (pathArg != null) {
847             try {
848                 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
849             } catch (UnsupportedEncodingException e) {
850                 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
851                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
852             }
853         }
854
855         return null;
856     }
857
858     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
859         if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
860             return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
861         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
862             return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
863         } else if (argument != null && node != null) {
864             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
865         } else {
866             throw new IllegalArgumentException("Unhandled parameter types: "
867                     + Arrays.<Object> asList(argument, node).toString());
868         }
869     }
870
871     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
872         StringBuilder builder = new StringBuilder();
873         builder.append("/");
874         QName nodeType = argument.getNodeType();
875         builder.append(this.toRestconfIdentifier(nodeType));
876         return builder.toString();
877     }
878
879     private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
880             final ListSchemaNode node) {
881         QName nodeType = argument.getNodeType();
882         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
883         final Map<QName, Object> keyValues = argument.getKeyValues();
884
885         StringBuilder builder = new StringBuilder();
886         builder.append("/");
887         builder.append(nodeIdentifier);
888         builder.append("/");
889
890         List<QName> keyDefinition = node.getKeyDefinition();
891         boolean hasElements = false;
892         for (final QName key : keyDefinition) {
893             if (!hasElements) {
894                 hasElements = true;
895             } else {
896                 builder.append("/");
897             }
898
899             try {
900                 builder.append(this.toUriString(keyValues.get(key)));
901             } catch (UnsupportedEncodingException e) {
902                 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
903                 return null;
904             }
905         }
906
907         return builder.toString();
908     }
909
910     private static DataSchemaNode childByQName(final Object container, final QName name) {
911         if (container instanceof ChoiceCaseNode) {
912             return childByQName((ChoiceCaseNode) container, name);
913         } else if (container instanceof ChoiceNode) {
914             return childByQName((ChoiceNode) container, name);
915         } else if (container instanceof ContainerSchemaNode) {
916             return childByQName((ContainerSchemaNode) container, name);
917         } else if (container instanceof ListSchemaNode) {
918             return childByQName((ListSchemaNode) container, name);
919         } else if (container instanceof DataSchemaNode) {
920             return childByQName((DataSchemaNode) container, name);
921         } else if (container instanceof Module) {
922             return childByQName((Module) container, name);
923         } else {
924             throw new IllegalArgumentException("Unhandled parameter types: "
925                     + Arrays.<Object> asList(container, name).toString());
926         }
927     }
928 }