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