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