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