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