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