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