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