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