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