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