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