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