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