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