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