5908624515f80a1a0b66695fda555236c6e78c0f
[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
566         if (head.isEmpty()) {
567             final List<String> remaining = strings.subList(1, strings.size());
568             return collectPathArguments(builder, remaining, parentNode, mountPoint, returnJustMountPoint);
569         }
570
571         final String nodeName = toNodeName(head);
572         final String moduleName = toModuleName(head);
573
574         DataSchemaNode targetNode = null;
575         if (!Strings.isNullOrEmpty(moduleName)) {
576             if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
577                 if (mountPoint != null) {
578                     throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
579                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
580                 }
581
582                 if (this.mountService == null) {
583                     throw new RestconfDocumentedException(
584                             "MountService was not found. Finding behind mount points does not work.",
585                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
586                 }
587
588                 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
589                 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
590                 if (!mountOpt.isPresent()) {
591                     LOG.debug("Instance identifier to missing mount point: {}", partialPath);
592                     throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
593                             ErrorTag.DATA_MISSING);
594                 }
595                 final DOMMountPoint mount = mountOpt.get();
596
597                 final SchemaContext mountPointSchema = mount.getSchemaContext();
598                 if (mountPointSchema == null) {
599                     throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
600                             ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
601                 }
602
603                 if (returnJustMountPoint || strings.size() == 1) {
604                     final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
605                     return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
606                 }
607
608                 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
609                 if (moduleNameBehindMountPoint == null) {
610                     throw new RestconfDocumentedException(
611                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
612                             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
613                 }
614
615                 final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
616                 if (!it.hasNext()) {
617                     throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
618                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
619                 }
620
621                 final List<String> subList = strings.subList(1, strings.size());
622                 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
623                         returnJustMountPoint);
624             }
625
626             Module module = null;
627             if (mountPoint == null) {
628                 checkPreconditions();
629                 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
630                 if (module == null) {
631                     throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
632                             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
633                 }
634             } else {
635                 final SchemaContext schemaContext = mountPoint.getSchemaContext();
636                 if (schemaContext != null) {
637                     module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
638                 } else {
639                     module = null;
640                 }
641                 if (module == null) {
642                     throw new RestconfDocumentedException("\"" + moduleName
643                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
644                 }
645             }
646
647             targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
648
649             if (targetNode == null && parentNode instanceof Module) {
650                 final RpcDefinition rpc;
651                 if (mountPoint == null) {
652                     rpc = getRpcDefinition(head, module.getRevision());
653                 } else {
654                     final String rpcName = toNodeName(head);
655                     rpc = getRpcDefinition(module, rpcName);
656                 }
657                 if (rpc != null) {
658                     return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
659                             mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
660                 }
661             }
662
663             if (targetNode == null) {
664                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
665                         + "\" was not found in parent data node.\n" + " 2. \"" + head
666                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
667                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
668             }
669         } else {
670             final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
671             if (potentialSchemaNodes.size() > 1) {
672                 final StringBuilder strBuilder = new StringBuilder();
673                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
674                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
675                 }
676
677                 throw new RestconfDocumentedException(
678                         "URI has bad format. Node \""
679                                 + nodeName + "\" is added as augment from more than one module. "
680                                 + "Therefore the node must have module name "
681                                 + "and it has to be in format \"moduleName:nodeName\"."
682                                 + "\nThe node is added as augment from modules with namespaces:\n"
683                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
684             }
685
686             if (potentialSchemaNodes.isEmpty()) {
687                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
688                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
689             }
690
691             targetNode = potentialSchemaNodes.iterator().next();
692         }
693
694         if (!isListOrContainer(targetNode)) {
695             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
696                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
697         }
698
699         int consumed = 1;
700         if (targetNode instanceof ListSchemaNode) {
701             final ListSchemaNode listNode = (ListSchemaNode) targetNode;
702             final int keysSize = listNode.getKeyDefinition().size();
703             if (strings.size() - consumed < keysSize) {
704                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
705                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
706             }
707
708             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
709             final HashMap<QName, Object> keyValues = new HashMap<>();
710             int index = 0;
711             for (final QName key : listNode.getKeyDefinition()) {
712                 {
713                     final String uriKeyValue = uriKeyValues.get(index);
714                     if (uriKeyValue.equals(NULL_VALUE)) {
715                         throw new RestconfDocumentedException("URI has bad format. List \""
716                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
717                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
718                     }
719
720                     addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
721                     index++;
722                 }
723             }
724
725             consumed = consumed + index;
726             builder.nodeWithKey(targetNode.getQName(), keyValues);
727         } else {
728             builder.node(targetNode.getQName());
729         }
730
731         if (targetNode instanceof DataNodeContainer) {
732             final List<String> remaining = strings.subList(consumed, strings.size());
733             return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
734                     returnJustMountPoint);
735         }
736
737         return createContext(builder.build(), targetNode, mountPoint,
738             mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
739     }
740
741     private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
742             final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
743         final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
744         return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
745     }
746
747     public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
748             final String name, final URI namespace) {
749         Preconditions.checkNotNull(namespace);
750
751         final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
752             node -> namespace.equals(node.getQName().getNamespace()));
753         return Iterables.getFirst(result, null);
754     }
755
756     public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
757             final String name) {
758         Preconditions.checkNotNull(container);
759         Preconditions.checkNotNull(name);
760
761         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
762         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
763         return instantiatedDataNodeContainers;
764     }
765
766     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
767             final DataNodeContainer container, final String name) {
768
769         final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
770             node -> name.equals(node.getQName().getLocalName()));
771
772         // Can't combine this loop with the filter above because the filter is
773         // lazily-applied by Iterables.filter.
774         for (final DataSchemaNode potentialNode : nodes) {
775             if (isInstantiatedDataSchema(potentialNode)) {
776                 potentialSchemaNodes.add(potentialNode);
777             }
778         }
779
780         final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
781             ChoiceSchemaNode.class);
782         final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
783             choice -> choice.getCases().values());
784         for (final CaseSchemaNode caze : Iterables.concat(map)) {
785             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
786         }
787     }
788
789     public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
790         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
791                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
792                 || node instanceof AnyXmlSchemaNode;
793     }
794
795     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
796             final DOMMountPoint mountPoint) {
797         Preconditions.checkNotNull(uriValue);
798         Preconditions.checkArgument(node instanceof LeafSchemaNode);
799
800         final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
801         final String urlDecoded = urlPathArgDecode(uriValue);
802         TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
803         final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
804         if (baseType instanceof LeafrefTypeDefinition) {
805             typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
806         }
807         final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
808         Object decoded = codec.deserialize(urlDecoded);
809         String additionalInfo = "";
810         if (decoded == null) {
811             if (typedef instanceof IdentityrefTypeDefinition) {
812                 decoded = toQName(schemaContext, urlDecoded);
813                 additionalInfo =
814                         "For key which is of type identityref it should be in format module_name:identity_name.";
815             }
816         }
817
818         if (decoded == null) {
819             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
820                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
821         }
822
823         map.put(node.getQName(), decoded);
824     }
825
826     private static String toModuleName(final String str) {
827         final int idx = str.indexOf(':');
828         if (idx == -1) {
829             return null;
830         }
831
832         // Make sure there is only one occurrence
833         if (str.indexOf(':', idx + 1) != -1) {
834             return null;
835         }
836
837         return str.substring(0, idx);
838     }
839
840     private static String toNodeName(final String str) {
841         final int idx = str.indexOf(':');
842         if (idx == -1) {
843             return str;
844         }
845
846         // Make sure there is only one occurrence
847         if (str.indexOf(':', idx + 1) != -1) {
848             return str;
849         }
850
851         return str.substring(idx + 1);
852     }
853
854     private QName toQName(final SchemaContext schemaContext, final String name,
855             final Optional<Revision> revisionDate) {
856         checkPreconditions();
857         final String module = toModuleName(name);
858         final String node = toNodeName(name);
859         final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
860         return m == null ? null : QName.create(m.getQNameModule(), node);
861     }
862
863     private QName toQName(final SchemaContext schemaContext, final String name) {
864         checkPreconditions();
865         final String module = toModuleName(name);
866         final String node = toNodeName(name);
867         final Set<Module> modules = schemaContext.findModules(module);
868         return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
869     }
870
871     private static boolean isListOrContainer(final DataSchemaNode node) {
872         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
873     }
874
875     public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
876         final QName validName = toQName(this.globalSchema, name, revisionDate);
877         return validName == null ? null : this.qnameToRpc.get().get(validName);
878     }
879
880     public RpcDefinition getRpcDefinition(final String name) {
881         final QName validName = toQName(this.globalSchema, name);
882         return validName == null ? null : this.qnameToRpc.get().get(validName);
883     }
884
885     private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
886         final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
887         for (final RpcDefinition rpcDefinition : module.getRpcs()) {
888             if (rpcQName.equals(rpcDefinition.getQName())) {
889                 return rpcDefinition;
890             }
891         }
892         return null;
893     }
894
895     @Override
896     public void onGlobalContextUpdated(final SchemaContext context) {
897         if (context != null) {
898             final Collection<RpcDefinition> defs = context.getOperations();
899             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
900
901             for (final RpcDefinition operation : defs) {
902                 newMap.put(operation.getQName(), operation);
903             }
904
905             // FIXME: still not completely atomic
906             this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
907             setGlobalSchema(context);
908         }
909     }
910
911     public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
912         try {
913             final List<String> decodedPathArgs = new ArrayList<>();
914             for (final String pathArg : strings) {
915                 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
916                 decodedPathArgs.add(_decode);
917             }
918             return decodedPathArgs;
919         } catch (final UnsupportedEncodingException e) {
920             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
921                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
922         }
923     }
924
925     public String urlPathArgDecode(final String pathArg) {
926         if (pathArg != null) {
927             try {
928                 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
929             } catch (final UnsupportedEncodingException e) {
930                 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
931                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
932             }
933         }
934
935         return null;
936     }
937
938     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
939             final DOMMountPoint mount) {
940         if (argument instanceof NodeIdentifier) {
941             return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
942         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
943             return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
944                 (ListSchemaNode) node, mount);
945         } else if (argument != null && node != null) {
946             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
947         } else {
948             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
949         }
950     }
951
952     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
953         return "/" + toRestconfIdentifier(argument.getNodeType(),node);
954     }
955
956     private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
957             final ListSchemaNode node, final DOMMountPoint mount) {
958         final QName nodeType = argument.getNodeType();
959         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
960
961         final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
962
963         final List<QName> keyDefinition = node.getKeyDefinition();
964         boolean hasElements = false;
965         for (final QName key : keyDefinition) {
966             for (final DataSchemaNode listChild : node.getChildNodes()) {
967                 if (listChild.getQName().equals(key)) {
968                     if (!hasElements) {
969                         hasElements = true;
970                     } else {
971                         builder.append('/');
972                     }
973
974                     Preconditions.checkState(listChild instanceof LeafSchemaNode,
975                         "List key has to consist of leaves, not %s", listChild);
976
977                     final Object value = argument.getValue(key);
978                     try {
979                         builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
980                     } catch (final UnsupportedEncodingException e) {
981                         LOG.error("Error parsing URI: {}", value, e);
982                         return null;
983                     }
984                     break;
985                 }
986             }
987         }
988
989         return builder.toString();
990     }
991
992     public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
993         try {
994             return this.dataNormalizer.toNormalized(legacy);
995         } catch (final NullPointerException e) {
996             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
997         }
998     }
999
1000     public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
1001         try {
1002             return this.dataNormalizer.toLegacy(instanceIdentifier);
1003         } catch (final NullPointerException e) {
1004             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
1005         } catch (final DataNormalizationException e) {
1006             throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1007         }
1008     }
1009
1010     public boolean isNodeMixin(final YangInstanceIdentifier path) {
1011         final DataNormalizationOperation<?> operation;
1012         try {
1013             operation = this.dataNormalizer.getOperation(path);
1014         } catch (final DataNormalizationException e) {
1015             throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1016         }
1017         return operation.isMixin();
1018     }
1019
1020     public DataNormalizationOperation<?> getRootOperation() {
1021         return this.dataNormalizer.getRootOperation();
1022     }
1023 }