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