Bug 2327: Handle binary data in NormalizedNode streaming
[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         this.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         this.onGlobalContextUpdated(schemas);
119     }
120
121     public InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
122         return this.toIdentifier(restconfInstance, false);
123     }
124
125     public SchemaContext getGlobalSchema() {
126         return globalSchema;
127     }
128
129     public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
130         return this.toIdentifier(restconfInstance, true);
131     }
132
133     private InstanceIdentifierContext toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
134         this.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         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         InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
150         Module latestModule = globalSchema.findModuleByName(startModule, null);
151         InstanceIdentifierContext iiWithSchemaNode = this.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         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         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         this.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         this.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         this.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         this.checkPreconditions();
225         Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
226                 && mountPoint != null);
227
228         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         this.checkPreconditions();
235
236         final Iterable<PathArgument> elements = path.getPathArguments();
237         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             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         this.checkPreconditions();
256
257         final Iterable<PathArgument> elements = path.getPathArguments();
258         final StringBuilder builder = new StringBuilder();
259         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             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         this.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         this.checkPreconditions();
301
302         SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
303         return schemaContext == null ? null : schemaContext.getModules();
304     }
305
306     public Set<Module> getAllModules() {
307         this.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         this.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         Module restconfModule = getRestconfModule();
343         if (restconfModule == null) {
344             return null;
345         }
346
347         Set<GroupingDefinition> groupings = restconfModule.getGroupings();
348
349         Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
350
351         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
352
353         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         Set<GroupingDefinition> groupings = restconfModule.getGroupings();
376         Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
377         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
378
379         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             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             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             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             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         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                     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         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                 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                     YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
518                     return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
519                 }
520
521                 if (strings.size() == 1) {
522                     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                 List<String> subList = strings.subList(1, strings.size());
540                 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
541                         returnJustMountPoint);
542             }
543
544             Module module = null;
545             if (mountPoint == null) {
546                 module = globalSchema.findModuleByName(moduleName, null);
547                 if (module == null) {
548                     throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
549                             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
550                 }
551             } else {
552                 SchemaContext schemaContext = mountPoint.getSchemaContext();
553                 if (schemaContext != null) {
554                     module = schemaContext.findModuleByName(moduleName, null);
555                 } else {
556                     module = null;
557                 }
558                 if (module == null) {
559                     throw new RestconfDocumentedException("\"" + moduleName
560                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
561                 }
562             }
563
564             targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
565             if (targetNode == null) {
566                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
567                         + "\" was not found in parent data node.\n" + " 2. \"" + head
568                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
569                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
570             }
571         } else {
572             final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
573             if (potentialSchemaNodes.size() > 1) {
574                 final StringBuilder strBuilder = new StringBuilder();
575                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
576                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
577                 }
578
579                 throw new RestconfDocumentedException(
580                         "URI has bad format. Node \""
581                                 + nodeName
582                                 + "\" is added as augment from more than one module. "
583                                 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
584                                 + "\nThe node is added as augment from modules with namespaces:\n"
585                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
586             }
587
588             if (potentialSchemaNodes.isEmpty()) {
589                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
590                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
591             }
592
593             targetNode = potentialSchemaNodes.iterator().next();
594         }
595
596         if (!ControllerContext.isListOrContainer(targetNode)) {
597             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
598                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
599         }
600
601         int consumed = 1;
602         if ((targetNode instanceof ListSchemaNode)) {
603             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
604             final int keysSize = listNode.getKeyDefinition().size();
605             if ((strings.size() - consumed) < keysSize) {
606                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
607                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
608             }
609
610             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
611             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
612             int i = 0;
613             for (final QName key : listNode.getKeyDefinition()) {
614                 {
615                     final String uriKeyValue = uriKeyValues.get(i);
616                     if (uriKeyValue.equals(NULL_VALUE)) {
617                         throw new RestconfDocumentedException("URI has bad format. List \""
618                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
619                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
620                     }
621
622                     this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
623                     i++;
624                 }
625             }
626
627             consumed = consumed + i;
628             builder.nodeWithKey(targetNode.getQName(), keyValues);
629         } else {
630             builder.node(targetNode.getQName());
631         }
632
633         if ((targetNode instanceof DataNodeContainer)) {
634             final List<String> remaining = strings.subList(consumed, strings.size());
635             return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
636                     returnJustMountPoint);
637         }
638
639         return new InstanceIdentifierContext(builder.toInstance(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
640     }
641
642     public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
643             final URI namespace) {
644         Preconditions.<URI> checkNotNull(namespace);
645
646         final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
647
648         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
649             @Override
650             public boolean apply(final DataSchemaNode node) {
651                 return Objects.equal(node.getQName().getNamespace(), namespace);
652             }
653         };
654
655         Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
656         return Iterables.getFirst(result, null);
657     }
658
659     public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
660         Preconditions.<DataNodeContainer> checkNotNull(container);
661         Preconditions.<String> checkNotNull(name);
662
663         List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
664         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
665         return instantiatedDataNodeContainers;
666     }
667
668     private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
669         @Override
670         public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
671             return node.getCases();
672         }
673     };
674
675     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
676             final DataNodeContainer container, final String name) {
677
678         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
679             @Override
680             public boolean apply(final DataSchemaNode node) {
681                 return Objects.equal(node.getQName().getLocalName(), name);
682             }
683         };
684
685         Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
686
687         // Can't combine this loop with the filter above because the filter is
688         // lazily-applied by Iterables.filter.
689         for (final DataSchemaNode potentialNode : nodes) {
690             if (isInstantiatedDataSchema(potentialNode)) {
691                 potentialSchemaNodes.add(potentialNode);
692             }
693         }
694
695         Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
696         Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
697
698         final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
699         for (final ChoiceCaseNode caze : allCases) {
700             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
701         }
702     }
703
704     public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
705         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
706                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
707                 || node instanceof AnyXmlSchemaNode;
708     }
709
710     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
711             final DOMMountPoint mountPoint) {
712         Preconditions.<String> checkNotNull(uriValue);
713         Preconditions.checkArgument((node instanceof LeafSchemaNode));
714
715         final String urlDecoded = urlPathArgDecode(uriValue);
716         final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
717         Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
718
719         Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
720         String additionalInfo = "";
721         if (decoded == null) {
722             TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
723             if ((baseType instanceof IdentityrefTypeDefinition)) {
724                 decoded = this.toQName(urlDecoded);
725                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
726             }
727         }
728
729         if (decoded == null) {
730             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
731                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
732         }
733
734         map.put(node.getQName(), decoded);
735     }
736
737     private static String toModuleName(final String str) {
738         final int idx = str.indexOf(':');
739         if (idx == -1) {
740             return null;
741         }
742
743         // Make sure there is only one occurrence
744         if (str.indexOf(':', idx + 1) != -1) {
745             return null;
746         }
747
748         return str.substring(0, idx);
749     }
750
751     private static String toNodeName(final String str) {
752         final int idx = str.indexOf(':');
753         if (idx == -1) {
754             return str;
755         }
756
757         // Make sure there is only one occurrence
758         if (str.indexOf(':', idx + 1) != -1) {
759             return str;
760         }
761
762         return str.substring(idx + 1);
763     }
764
765     private QName toQName(final String name) {
766         final String module = toModuleName(name);
767         final String node = toNodeName(name);
768         final Module m = globalSchema.findModuleByName(module, null);
769         return m == null ? null : QName.create(m.getQNameModule(), node);
770     }
771
772     private static boolean isListOrContainer(final DataSchemaNode node) {
773         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
774     }
775
776     public RpcDefinition getRpcDefinition(final String name) {
777         final QName validName = this.toQName(name);
778         return validName == null ? null : this.qnameToRpc.get().get(validName);
779     }
780
781     @Override
782     public void onGlobalContextUpdated(final SchemaContext context) {
783         if (context != null) {
784             final Collection<RpcDefinition> defs = context.getOperations();
785             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
786
787             for (final RpcDefinition operation : defs) {
788                 newMap.put(operation.getQName(), operation);
789             }
790
791             // FIXME: still not completely atomic
792             this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
793             this.setGlobalSchema(context);
794         }
795     }
796
797     public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
798         try {
799             List<String> decodedPathArgs = new ArrayList<String>();
800             for (final String pathArg : strings) {
801                 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
802                 decodedPathArgs.add(_decode);
803             }
804             return decodedPathArgs;
805         } catch (UnsupportedEncodingException e) {
806             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
807                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
808         }
809     }
810
811     public String urlPathArgDecode(final String pathArg) {
812         if (pathArg != null) {
813             try {
814                 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
815             } catch (UnsupportedEncodingException e) {
816                 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
817                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
818             }
819         }
820
821         return null;
822     }
823
824     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
825         if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
826             return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
827         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
828             return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
829         } else if (argument != null && node != null) {
830             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
831         } else {
832             throw new IllegalArgumentException("Unhandled parameter types: "
833                     + Arrays.<Object> asList(argument, node).toString());
834         }
835     }
836
837     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
838         return "/" + this.toRestconfIdentifier(argument.getNodeType());
839     }
840
841     private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
842             final ListSchemaNode node) {
843         QName nodeType = argument.getNodeType();
844         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
845         final Map<QName, Object> keyValues = argument.getKeyValues();
846
847         StringBuilder builder = new StringBuilder();
848         builder.append('/');
849         builder.append(nodeIdentifier);
850         builder.append('/');
851
852         List<QName> keyDefinition = node.getKeyDefinition();
853         boolean hasElements = false;
854         for (final QName key : keyDefinition) {
855             if (!hasElements) {
856                 hasElements = true;
857             } else {
858                 builder.append('/');
859             }
860
861             try {
862                 builder.append(this.toUriString(keyValues.get(key)));
863             } catch (UnsupportedEncodingException e) {
864                 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
865                 return null;
866             }
867         }
868
869         return builder.toString();
870     }
871
872     private static DataSchemaNode childByQName(final Object container, final QName name) {
873         if (container instanceof ChoiceCaseNode) {
874             return childByQName((ChoiceCaseNode) container, name);
875         } else if (container instanceof ChoiceNode) {
876             return childByQName((ChoiceNode) container, name);
877         } else if (container instanceof ContainerSchemaNode) {
878             return childByQName((ContainerSchemaNode) container, name);
879         } else if (container instanceof ListSchemaNode) {
880             return childByQName((ListSchemaNode) container, name);
881         } else if (container instanceof DataSchemaNode) {
882             return childByQName((DataSchemaNode) container, name);
883         } else if (container instanceof Module) {
884             return childByQName((Module) container, name);
885         } else {
886             throw new IllegalArgumentException("Unhandled parameter types: "
887                     + Arrays.<Object> asList(container, name).toString());
888         }
889     }
890
891     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
892             final CompositeNode compositeNode) {
893         try {
894             return dataNormalizer.toNormalized(legacy, compositeNode);
895         } catch (NullPointerException e) {
896             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
897         }
898     }
899
900     public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
901         try {
902             return dataNormalizer.toNormalized(legacy);
903         } catch (NullPointerException e) {
904             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
905         }
906     }
907
908     public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
909             final NormalizedNode<?,?> normalizedNode) {
910         try {
911             return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
912         } catch (NullPointerException e) {
913             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
914         }
915     }
916
917     public DataNormalizationOperation<?> getRootOperation() {
918         return dataNormalizer.getRootOperation();
919     }
920
921 }