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