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