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