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