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