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