Update MRI projects for Aluminium
[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.Preconditions;
11 import com.google.common.base.Splitter;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.Iterables;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.Closeable;
17 import java.io.UnsupportedEncodingException;
18 import java.net.URI;
19 import java.net.URLDecoder;
20 import java.net.URLEncoder;
21 import java.nio.charset.Charset;
22 import java.nio.charset.StandardCharsets;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.concurrent.atomic.AtomicReference;
33 import javax.annotation.PreDestroy;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
36 import javax.ws.rs.core.Response.Status;
37 import org.apache.aries.blueprint.annotation.service.Reference;
38 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
39 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
40 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
41 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
42 import org.opendaylight.netconf.sal.rest.api.Draft02;
43 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
44 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
45 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
46 import org.opendaylight.restconf.common.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.IllegalArgumentCodec;
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.EffectiveModelContext;
66 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
67 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
68 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.Module;
72 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 @Singleton
82 public final class ControllerContext implements EffectiveModelContextListener, Closeable {
83     // FIXME: this should be in md-sal somewhere
84     public static final String MOUNT = "yang-ext:mount";
85
86     private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
87
88     private static final String NULL_VALUE = "null";
89
90     private static final String MOUNT_MODULE = "yang-ext";
91
92     private static final String MOUNT_NODE = "mount";
93
94     private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
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         Preconditions.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         Preconditions.checkArgument(moduleName != null && mountPoint != null);
236
237         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
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         Preconditions.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         Preconditions.checkArgument(namespace != null && mountPoint != null);
253
254         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
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         Preconditions.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         Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
273
274         final SchemaContext schemaContext = mountPoint.getSchemaContext();
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 = mount.getSchemaContext();
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 : mountPoint.getSchemaContext();
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 = mount.getSchemaContext();
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(mountPoint.getSchemaContext(), 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         // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
543         return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
544     }
545
546     @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
547     private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
548             final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
549             final boolean returnJustMountPoint) {
550         Preconditions.checkNotNull(strings);
551
552         if (parentNode == null) {
553             return null;
554         }
555
556         if (strings.isEmpty()) {
557             return createContext(builder.build(), (DataSchemaNode) parentNode,
558                 mountPoint,mountPoint != null ? mountPoint.getEffectiveModelContext() : this.globalSchema);
559         }
560
561         final String head = strings.iterator().next();
562
563         if (head.isEmpty()) {
564             final List<String> remaining = strings.subList(1, strings.size());
565             return collectPathArguments(builder, remaining, parentNode, mountPoint, returnJustMountPoint);
566         }
567
568         final String nodeName = toNodeName(head);
569         final String moduleName = toModuleName(head);
570
571         DataSchemaNode targetNode = null;
572         if (!Strings.isNullOrEmpty(moduleName)) {
573             if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
574                 if (mountPoint != null) {
575                     throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
576                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
577                 }
578
579                 if (this.mountService == null) {
580                     throw new RestconfDocumentedException(
581                             "MountService was not found. Finding behind mount points does not work.",
582                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
583                 }
584
585                 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
586                 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
587                 if (!mountOpt.isPresent()) {
588                     LOG.debug("Instance identifier to missing mount point: {}", partialPath);
589                     throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
590                             ErrorTag.DATA_MISSING);
591                 }
592                 final DOMMountPoint mount = mountOpt.get();
593
594                 final EffectiveModelContext mountPointSchema = mount.getEffectiveModelContext();
595                 if (mountPointSchema == null) {
596                     throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
597                             ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
598                 }
599
600                 if (returnJustMountPoint || strings.size() == 1) {
601                     final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
602                     return new InstanceIdentifierContext<>(instance, mountPointSchema, mount, mountPointSchema);
603                 }
604
605                 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
606                 if (moduleNameBehindMountPoint == null) {
607                     throw new RestconfDocumentedException(
608                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
609                             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
610                 }
611
612                 final Iterator<? extends Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint)
613                         .iterator();
614                 if (!it.hasNext()) {
615                     throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
616                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
617                 }
618
619                 final List<String> subList = strings.subList(1, strings.size());
620                 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
621                         returnJustMountPoint);
622             }
623
624             Module module = null;
625             if (mountPoint == null) {
626                 checkPreconditions();
627                 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
628                 if (module == null) {
629                     throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
630                             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
631                 }
632             } else {
633                 final EffectiveModelContext schemaContext = mountPoint.getEffectiveModelContext();
634                 if (schemaContext != null) {
635                     module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
636                 } else {
637                     module = null;
638                 }
639                 if (module == null) {
640                     throw new RestconfDocumentedException("\"" + moduleName
641                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
642                 }
643             }
644
645             targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
646
647             if (targetNode == null && parentNode instanceof Module) {
648                 final RpcDefinition rpc;
649                 if (mountPoint == null) {
650                     rpc = getRpcDefinition(head, module.getRevision());
651                 } else {
652                     final String rpcName = toNodeName(head);
653                     rpc = getRpcDefinition(module, rpcName);
654                 }
655                 if (rpc != null) {
656                     return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
657                             mountPoint != null ? mountPoint.getEffectiveModelContext() : this.globalSchema);
658                 }
659             }
660
661             if (targetNode == null) {
662                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
663                         + "\" was not found in parent data node.\n" + " 2. \"" + head
664                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
665                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
666             }
667         } else {
668             final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
669             if (potentialSchemaNodes.size() > 1) {
670                 final StringBuilder strBuilder = new StringBuilder();
671                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
672                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
673                 }
674
675                 throw new RestconfDocumentedException(
676                         "URI has bad format. Node \""
677                                 + nodeName + "\" is added as augment from more than one module. "
678                                 + "Therefore the node must have module name "
679                                 + "and it has to be in format \"moduleName:nodeName\"."
680                                 + "\nThe node is added as augment from modules with namespaces:\n"
681                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
682             }
683
684             if (potentialSchemaNodes.isEmpty()) {
685                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
686                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
687             }
688
689             targetNode = potentialSchemaNodes.iterator().next();
690         }
691
692         if (!isListOrContainer(targetNode)) {
693             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
694                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
695         }
696
697         int consumed = 1;
698         if (targetNode instanceof ListSchemaNode) {
699             final ListSchemaNode listNode = (ListSchemaNode) targetNode;
700             final int keysSize = listNode.getKeyDefinition().size();
701             if (strings.size() - consumed < keysSize) {
702                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
703                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
704             }
705
706             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
707             final HashMap<QName, Object> keyValues = new HashMap<>();
708             int index = 0;
709             for (final QName key : listNode.getKeyDefinition()) {
710                 {
711                     final String uriKeyValue = uriKeyValues.get(index);
712                     if (uriKeyValue.equals(NULL_VALUE)) {
713                         throw new RestconfDocumentedException("URI has bad format. List \""
714                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
715                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
716                     }
717
718                     addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
719                     index++;
720                 }
721             }
722
723             consumed = consumed + index;
724             builder.nodeWithKey(targetNode.getQName(), keyValues);
725         } else {
726             builder.node(targetNode.getQName());
727         }
728
729         if (targetNode instanceof DataNodeContainer) {
730             final List<String> remaining = strings.subList(consumed, strings.size());
731             return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
732                     returnJustMountPoint);
733         }
734
735         return createContext(builder.build(), targetNode, mountPoint,
736             mountPoint != null ? mountPoint.getEffectiveModelContext() : this.globalSchema);
737     }
738
739     private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
740             final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint,
741             final EffectiveModelContext schemaContext) {
742         final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
743         return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
744     }
745
746     public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
747             final String name, final URI namespace) {
748         Preconditions.checkNotNull(namespace);
749
750         final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
751             node -> namespace.equals(node.getQName().getNamespace()));
752         return Iterables.getFirst(result, null);
753     }
754
755     public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
756             final String name) {
757         Preconditions.checkNotNull(container);
758         Preconditions.checkNotNull(name);
759
760         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
761         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
762         return instantiatedDataNodeContainers;
763     }
764
765     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
766             final DataNodeContainer container, final String name) {
767
768         final Iterable<? extends DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
769             node -> name.equals(node.getQName().getLocalName()));
770
771         // Can't combine this loop with the filter above because the filter is
772         // lazily-applied by Iterables.filter.
773         for (final DataSchemaNode potentialNode : nodes) {
774             if (isInstantiatedDataSchema(potentialNode)) {
775                 potentialSchemaNodes.add(potentialNode);
776             }
777         }
778
779         final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
780             ChoiceSchemaNode.class);
781         final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
782             ChoiceSchemaNode::getCases);
783         for (final CaseSchemaNode caze : Iterables.concat(map)) {
784             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
785         }
786     }
787
788     public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
789         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
790                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
791                 || node instanceof AnyxmlSchemaNode;
792     }
793
794     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
795             final DOMMountPoint mountPoint) {
796         Preconditions.checkNotNull(uriValue);
797         Preconditions.checkArgument(node instanceof LeafSchemaNode);
798
799         final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
800         final String urlDecoded = urlPathArgDecode(uriValue);
801         TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
802         final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
803         if (baseType instanceof LeafrefTypeDefinition) {
804             typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
805         }
806         final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
807         Object decoded = codec.deserialize(urlDecoded);
808         String additionalInfo = "";
809         if (decoded == null) {
810             if (typedef instanceof IdentityrefTypeDefinition) {
811                 decoded = toQName(schemaContext, urlDecoded);
812                 additionalInfo =
813                         "For key which is of type identityref it should be in format module_name:identity_name.";
814             }
815         }
816
817         if (decoded == null) {
818             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
819                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
820         }
821
822         map.put(node.getQName(), decoded);
823     }
824
825     private static String toModuleName(final String str) {
826         final int idx = str.indexOf(':');
827         if (idx == -1) {
828             return null;
829         }
830
831         // Make sure there is only one occurrence
832         if (str.indexOf(':', idx + 1) != -1) {
833             return null;
834         }
835
836         return str.substring(0, idx);
837     }
838
839     private static String toNodeName(final String str) {
840         final int idx = str.indexOf(':');
841         if (idx == -1) {
842             return str;
843         }
844
845         // Make sure there is only one occurrence
846         if (str.indexOf(':', idx + 1) != -1) {
847             return str;
848         }
849
850         return str.substring(idx + 1);
851     }
852
853     private QName toQName(final SchemaContext schemaContext, final String name,
854             final Optional<Revision> revisionDate) {
855         checkPreconditions();
856         final String module = toModuleName(name);
857         final String node = toNodeName(name);
858         final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
859         return m == null ? null : QName.create(m.getQNameModule(), node);
860     }
861
862     private QName toQName(final SchemaContext schemaContext, final String name) {
863         checkPreconditions();
864         final String module = toModuleName(name);
865         final String node = toNodeName(name);
866         final Collection<? extends Module> modules = schemaContext.findModules(module);
867         return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
868     }
869
870     private static boolean isListOrContainer(final DataSchemaNode node) {
871         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
872     }
873
874     public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
875         final QName validName = toQName(this.globalSchema, name, revisionDate);
876         return validName == null ? null : this.qnameToRpc.get().get(validName);
877     }
878
879     public RpcDefinition getRpcDefinition(final String name) {
880         final QName validName = toQName(this.globalSchema, name);
881         return validName == null ? null : this.qnameToRpc.get().get(validName);
882     }
883
884     private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
885         final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
886         for (final RpcDefinition rpcDefinition : module.getRpcs()) {
887             if (rpcQName.equals(rpcDefinition.getQName())) {
888                 return rpcDefinition;
889             }
890         }
891         return null;
892     }
893
894     @Override
895     public void onModelContextUpdated(final EffectiveModelContext context) {
896         if (context != null) {
897             final Collection<? extends RpcDefinition> defs = context.getOperations();
898             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
899
900             for (final RpcDefinition operation : defs) {
901                 newMap.put(operation.getQName(), operation);
902             }
903
904             // FIXME: still not completely atomic
905             this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
906             setGlobalSchema(context);
907         }
908     }
909
910     private static List<String> urlPathArgsDecode(final Iterable<String> strings) {
911         try {
912             final List<String> decodedPathArgs = new ArrayList<>();
913             for (final String pathArg : strings) {
914                 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
915                 decodedPathArgs.add(_decode);
916             }
917             return decodedPathArgs;
918         } catch (final UnsupportedEncodingException e) {
919             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
920                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
921         }
922     }
923
924     static String urlPathArgDecode(final String pathArg) {
925         if (pathArg == null) {
926             return null;
927         }
928         try {
929             return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
930         } catch (final UnsupportedEncodingException e) {
931             throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
932                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
933         }
934     }
935
936     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
937             final DOMMountPoint mount) {
938         if (argument instanceof NodeIdentifier) {
939             return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
940         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
941             return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
942                 (ListSchemaNode) node, mount);
943         } else if (argument != null && node != null) {
944             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
945         } else {
946             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
947         }
948     }
949
950     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
951         return "/" + toRestconfIdentifier(argument.getNodeType(),node);
952     }
953
954     private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
955             final ListSchemaNode node, final DOMMountPoint mount) {
956         final QName nodeType = argument.getNodeType();
957         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
958
959         final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
960
961         final List<QName> keyDefinition = node.getKeyDefinition();
962         boolean hasElements = false;
963         for (final QName key : keyDefinition) {
964             for (final DataSchemaNode listChild : node.getChildNodes()) {
965                 if (listChild.getQName().equals(key)) {
966                     if (!hasElements) {
967                         hasElements = true;
968                     } else {
969                         builder.append('/');
970                     }
971
972                     Preconditions.checkState(listChild instanceof LeafSchemaNode,
973                         "List key has to consist of leaves, not %s", listChild);
974
975                     final Object value = argument.getValue(key);
976                     try {
977                         builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
978                     } catch (final UnsupportedEncodingException e) {
979                         LOG.error("Error parsing URI: {}", value, e);
980                         return null;
981                     }
982                     break;
983                 }
984             }
985         }
986
987         return builder.toString();
988     }
989
990     public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
991         try {
992             return this.dataNormalizer.toNormalized(legacy);
993         } catch (final NullPointerException e) {
994             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
995         }
996     }
997
998     public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
999         try {
1000             return this.dataNormalizer.toLegacy(instanceIdentifier);
1001         } catch (final NullPointerException e) {
1002             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
1003         } catch (final DataNormalizationException e) {
1004             throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1005         }
1006     }
1007
1008     public boolean isNodeMixin(final YangInstanceIdentifier path) {
1009         final DataNormalizationOperation<?> operation;
1010         try {
1011             operation = this.dataNormalizer.getOperation(path);
1012         } catch (final DataNormalizationException e) {
1013             throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1014         }
1015         return operation.isMixin();
1016     }
1017 }