Bug 8115: Change URI decoding from ISO-8859-1 to UTF-8
[netconf.git] / opendaylight / 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.Function;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicate;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.Iterables;
19 import java.io.UnsupportedEncodingException;
20 import java.net.URI;
21 import java.net.URLDecoder;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.concurrent.atomic.AtomicReference;
33 import javax.ws.rs.core.Response.Status;
34 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
36 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
38 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
39 import org.opendaylight.netconf.sal.rest.api.Draft02;
40 import org.opendaylight.netconf.sal.rest.impl.RestUtil;
41 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
42 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
43 import org.opendaylight.yangtools.concepts.Codec;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
51 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
65 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 public class ControllerContext implements SchemaContextListener {
73     private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
74
75     private final static ControllerContext INSTANCE = new ControllerContext();
76
77     private final static String NULL_VALUE = "null";
78
79     private final static String MOUNT_MODULE = "yang-ext";
80
81     private final static String MOUNT_NODE = "mount";
82
83     public final static String MOUNT = "yang-ext:mount";
84
85     private final static String URI_ENCODING_CHAR_SET = "UTF-8";
86
87     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
88
89     private static final YangInstanceIdentifier ROOT = YangInstanceIdentifier.builder().build();
90
91     private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
92             new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
93
94     private volatile SchemaContext globalSchema;
95     private volatile DOMMountPointService mountService;
96
97     private DataNormalizer dataNormalizer;
98
99     public void setGlobalSchema(final SchemaContext globalSchema) {
100         this.globalSchema = globalSchema;
101         dataNormalizer = new DataNormalizer(globalSchema);
102     }
103
104     public void setMountService(final DOMMountPointService mountService) {
105         this.mountService = mountService;
106     }
107
108     private ControllerContext() {
109     }
110
111     public static ControllerContext getInstance() {
112         return ControllerContext.INSTANCE;
113     }
114
115     private void checkPreconditions() {
116         if (globalSchema == null) {
117             throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
118         }
119     }
120
121     public void setSchemas(final SchemaContext schemas) {
122         onGlobalContextUpdated(schemas);
123     }
124
125     public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
126         return toIdentifier(restconfInstance, false);
127     }
128
129     public SchemaContext getGlobalSchema() {
130         return globalSchema;
131     }
132
133     public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
134         return toIdentifier(restconfInstance, true);
135     }
136
137     private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
138         checkPreconditions();
139
140         if(restconfInstance == null) {
141             return new InstanceIdentifierContext<>(ROOT, globalSchema, null, 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 = ControllerContext.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 = 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 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 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 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 = 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 = ControllerContext.childByQName(node, _nodeType);
258             if (potentialNode == null || !ControllerContext.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 = 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 = ControllerContext.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 globalSchema.getModules();
332     }
333
334     private static final 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 = globalSchema;
346         }
347
348         return toRestconfIdentifier(schema, qname);
349     }
350
351     public CharSequence toRestconfIdentifier(final QName qname) {
352         checkPreconditions();
353
354         return toRestconfIdentifier(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(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
367     }
368
369     private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
370         @Override
371         public boolean apply(final GroupingDefinition g) {
372             return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
373         }
374     };
375
376     public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
377         final Module restconfModule = getRestconfModule();
378         if (restconfModule == null) {
379             return null;
380         }
381
382         final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
383
384         final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
385
386         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
387
388         final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
389                 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
390         return Iterables.getFirst(instanceDataChildrenByName, null);
391     }
392
393     private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
394         @Override
395         public boolean apply(final GroupingDefinition g) {
396             return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
397         }
398     };
399
400     public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
401         Module restconfModule = inRestconfModule;
402         if (restconfModule == null) {
403             restconfModule = getRestconfModule();
404         }
405
406         if (restconfModule == null) {
407             return null;
408         }
409
410         final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
411         final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
412         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
413
414         final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
415                 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
416         final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
417
418         if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
419             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
420                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
421             return Iterables.getFirst(instances, null);
422         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
423             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
424                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
425             return Iterables.getFirst(instances, null);
426         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
427             List<DataSchemaNode> instances = findInstanceDataChildrenByName(
428                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
429             final DataSchemaNode modules = Iterables.getFirst(instances, null);
430             instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
431                     Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
432             return Iterables.getFirst(instances, null);
433         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
434             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
435                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
436             return Iterables.getFirst(instances, null);
437         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
438             List<DataSchemaNode> instances = findInstanceDataChildrenByName(
439                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
440             final DataSchemaNode modules = Iterables.getFirst(instances, null);
441             instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
442                     Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
443             return Iterables.getFirst(instances, null);
444         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
445             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
446                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447             return Iterables.getFirst(instances, null);
448         }
449
450         return null;
451     }
452
453     private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
454         for (final ChoiceCaseNode caze : container.getCases()) {
455             final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
456             if (ret != null) {
457                 return ret;
458             }
459         }
460
461         return null;
462     }
463
464     private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
465         return container.getDataChildByName(name);
466     }
467
468     private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
469         return ControllerContext.dataNodeChildByQName(container, name);
470     }
471
472     private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
473         return ControllerContext.dataNodeChildByQName(container, name);
474     }
475
476     private static DataSchemaNode childByQName(final Module container, final QName name) {
477         return ControllerContext.dataNodeChildByQName(container, name);
478     }
479
480     private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
481         return null;
482     }
483
484     private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
485         final DataSchemaNode ret = container.getDataChildByName(name);
486         if (ret == null) {
487             for (final DataSchemaNode node : container.getChildNodes()) {
488                 if ((node instanceof ChoiceSchemaNode)) {
489                     final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
490                     final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
491                     if (childByQName != null) {
492                         return childByQName;
493                     }
494                 }
495             }
496         }
497         return ret;
498     }
499
500     private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
501         final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
502         return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
503     }
504
505     private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
506             final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
507             final boolean returnJustMountPoint) {
508         Preconditions.<List<String>> checkNotNull(strings);
509
510         if (parentNode == null) {
511             return null;
512         }
513
514         if (strings.isEmpty()) {
515             return createContext(builder.build(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
516         }
517
518         final String head = strings.iterator().next();
519         final String nodeName = toNodeName(head);
520         final String moduleName = ControllerContext.toModuleName(head);
521
522         DataSchemaNode targetNode = null;
523         if (!Strings.isNullOrEmpty(moduleName)) {
524             if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
525                     && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
526                 if (mountPoint != null) {
527                     throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
528                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
529                 }
530
531                 if (mountService == null) {
532                     throw new RestconfDocumentedException(
533                             "MountService was not found. Finding behind mount points does not work.",
534                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
535                 }
536
537                 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
538                 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
539                 if (!mountOpt.isPresent()) {
540                     LOG.debug("Instance identifier to missing mount point: {}", partialPath);
541                     throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
542                             ErrorTag.DATA_MISSING);
543                 }
544                 final DOMMountPoint mount = mountOpt.get();
545
546                 final SchemaContext mountPointSchema = mount.getSchemaContext();
547                 if (mountPointSchema == null) {
548                     throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
549                             ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
550                 }
551
552                 if (returnJustMountPoint || strings.size() == 1) {
553                     final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
554                     return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
555                 }
556
557                 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
558                 if (moduleNameBehindMountPoint == null) {
559                     throw new RestconfDocumentedException(
560                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
561                             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
562                 }
563
564                 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
565                 if (moduleBehindMountPoint == null) {
566                     throw new RestconfDocumentedException("\"" + moduleName
567                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
568                 }
569
570                 final List<String> subList = strings.subList(1, strings.size());
571                 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
572                         returnJustMountPoint);
573             }
574
575             Module module = null;
576             if (mountPoint == null) {
577                 checkPreconditions();
578                 module = globalSchema.findModuleByName(moduleName, null);
579                 if (module == null) {
580                     throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
581                             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
582                 }
583             } else {
584                 final SchemaContext schemaContext = mountPoint.getSchemaContext();
585                 if (schemaContext != null) {
586                     module = schemaContext.findModuleByName(moduleName, null);
587                 } else {
588                     module = null;
589                 }
590                 if (module == null) {
591                     throw new RestconfDocumentedException("\"" + moduleName
592                             + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
593                 }
594             }
595
596             targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
597
598             if (targetNode == null && parentNode instanceof Module) {
599                 final RpcDefinition rpc;
600                 if (mountPoint == null) {
601                     rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
602                 } else {
603                     final String rpcName = toNodeName(head);
604                     rpc = ControllerContext.getInstance().getRpcDefinition(module, rpcName);
605                 }
606                 if (rpc != null) {
607                     return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
608                             mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
609                 }
610             }
611
612             if (targetNode == null) {
613                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
614                         + "\" was not found in parent data node.\n" + " 2. \"" + head
615                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
616                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
617             }
618         } else {
619             final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
620             if (potentialSchemaNodes.size() > 1) {
621                 final StringBuilder strBuilder = new StringBuilder();
622                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
623                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
624                 }
625
626                 throw new RestconfDocumentedException(
627                         "URI has bad format. Node \""
628                                 + nodeName
629                                 + "\" is added as augment from more than one module. "
630                                 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
631                                 + "\nThe node is added as augment from modules with namespaces:\n"
632                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
633             }
634
635             if (potentialSchemaNodes.isEmpty()) {
636                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
637                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
638             }
639
640             targetNode = potentialSchemaNodes.iterator().next();
641         }
642
643         if (!ControllerContext.isListOrContainer(targetNode)) {
644             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
645                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
646         }
647
648         int consumed = 1;
649         if ((targetNode instanceof ListSchemaNode)) {
650             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
651             final int keysSize = listNode.getKeyDefinition().size();
652             if ((strings.size() - consumed) < keysSize) {
653                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
654                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
655             }
656
657             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
658             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
659             int i = 0;
660             for (final QName key : listNode.getKeyDefinition()) {
661                 {
662                     final String uriKeyValue = uriKeyValues.get(i);
663                     if (uriKeyValue.equals(NULL_VALUE)) {
664                         throw new RestconfDocumentedException("URI has bad format. List \""
665                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
666                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
667                     }
668
669                     addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
670                     i++;
671                 }
672             }
673
674             consumed = consumed + i;
675             builder.nodeWithKey(targetNode.getQName(), keyValues);
676         } else {
677             builder.node(targetNode.getQName());
678         }
679
680         if ((targetNode instanceof DataNodeContainer)) {
681             final List<String> remaining = strings.subList(consumed, strings.size());
682             return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
683                     returnJustMountPoint);
684         }
685
686         return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
687     }
688
689     private InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
690             final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
691
692         final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
693         return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
694     }
695
696     public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
697             final URI namespace) {
698         Preconditions.<URI> checkNotNull(namespace);
699
700         final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
701
702         final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
703             @Override
704             public boolean apply(final DataSchemaNode node) {
705                 return Objects.equal(node.getQName().getNamespace(), namespace);
706             }
707         };
708
709         final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
710         return Iterables.getFirst(result, null);
711     }
712
713     public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
714         Preconditions.<DataNodeContainer> checkNotNull(container);
715         Preconditions.<String> checkNotNull(name);
716
717         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
718         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
719         return instantiatedDataNodeContainers;
720     }
721
722     private static final Function<ChoiceSchemaNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceSchemaNode, Set<ChoiceCaseNode>>() {
723         @Override
724         public Set<ChoiceCaseNode> apply(final ChoiceSchemaNode node) {
725             return node.getCases();
726         }
727     };
728
729     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
730             final DataNodeContainer container, final String name) {
731
732         final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
733             @Override
734             public boolean apply(final DataSchemaNode node) {
735                 return Objects.equal(node.getQName().getLocalName(), name);
736             }
737         };
738
739         final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
740
741         // Can't combine this loop with the filter above because the filter is
742         // lazily-applied by Iterables.filter.
743         for (final DataSchemaNode potentialNode : nodes) {
744             if (isInstantiatedDataSchema(potentialNode)) {
745                 potentialSchemaNodes.add(potentialNode);
746             }
747         }
748
749         final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
750         final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
751
752         final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
753         for (final ChoiceCaseNode caze : allCases) {
754             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
755         }
756     }
757
758     public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
759         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
760                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
761                 || node instanceof AnyXmlSchemaNode;
762     }
763
764     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
765             final DOMMountPoint mountPoint) {
766         Preconditions.checkNotNull(uriValue);
767         Preconditions.checkArgument((node instanceof LeafSchemaNode));
768
769         final String urlDecoded = urlPathArgDecode(uriValue);
770         TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
771         final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
772         if (baseType instanceof LeafrefTypeDefinition) {
773             typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, globalSchema, node);
774         }
775         Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
776         Object decoded = codec.deserialize(urlDecoded);
777         String additionalInfo = "";
778         if (decoded == null) {
779             if ((baseType instanceof IdentityrefTypeDefinition)) {
780                 decoded = toQName(urlDecoded, null);
781                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
782             }
783         }
784
785         if (decoded == null) {
786             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
787                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
788         }
789
790         map.put(node.getQName(), decoded);
791     }
792
793     private static String toModuleName(final String str) {
794         final int idx = str.indexOf(':');
795         if (idx == -1) {
796             return null;
797         }
798
799         // Make sure there is only one occurrence
800         if (str.indexOf(':', idx + 1) != -1) {
801             return null;
802         }
803
804         return str.substring(0, idx);
805     }
806
807     private static String toNodeName(final String str) {
808         final int idx = str.indexOf(':');
809         if (idx == -1) {
810             return str;
811         }
812
813         // Make sure there is only one occurrence
814         if (str.indexOf(':', idx + 1) != -1) {
815             return str;
816         }
817
818         return str.substring(idx + 1);
819     }
820
821     private QName toQName(final String name, final Date revisionDate) {
822         checkPreconditions();
823         final String module = toModuleName(name);
824         final String node = toNodeName(name);
825         final Module m = globalSchema.findModuleByName(module, revisionDate);
826         return m == null ? null : QName.create(m.getQNameModule(), node);
827     }
828
829     private static boolean isListOrContainer(final DataSchemaNode node) {
830         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
831     }
832
833     public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) {
834         final QName validName = toQName(name, revisionDate);
835         return validName == null ? null : qnameToRpc.get().get(validName);
836     }
837
838     private RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
839         QName rpcQName = QName.create(module.getQNameModule(), rpcName);
840         for (RpcDefinition rpcDefinition : module.getRpcs()) {
841             if (rpcQName.equals(rpcDefinition.getQName())) {
842                 return rpcDefinition;
843             }
844         }
845         return null;
846     }
847
848     @Override
849     public void onGlobalContextUpdated(final SchemaContext context) {
850         if (context != null) {
851             final Collection<RpcDefinition> defs = context.getOperations();
852             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
853
854             for (final RpcDefinition operation : defs) {
855                 newMap.put(operation.getQName(), operation);
856             }
857
858             // FIXME: still not completely atomic
859             qnameToRpc.set(ImmutableMap.copyOf(newMap));
860             setGlobalSchema(context);
861         }
862     }
863
864     public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
865         try {
866             final List<String> decodedPathArgs = new ArrayList<String>();
867             for (final String pathArg : strings) {
868                 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
869                 decodedPathArgs.add(_decode);
870             }
871             return decodedPathArgs;
872         } catch (final UnsupportedEncodingException e) {
873             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
874                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
875         }
876     }
877
878     public String urlPathArgDecode(final String pathArg) {
879         if (pathArg != null) {
880             try {
881                 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
882             } catch (final UnsupportedEncodingException e) {
883                 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
884                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
885             }
886         }
887
888         return null;
889     }
890
891     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node, final DOMMountPoint mount) {
892         if (argument instanceof NodeIdentifier) {
893             return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
894         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
895             return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node, mount);
896         } else if (argument != null && node != null) {
897             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
898         } else {
899             throw new IllegalArgumentException("Unhandled parameter types: "
900                     + Arrays.<Object> asList(argument, node).toString());
901         }
902     }
903
904     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
905         return "/" + this.toRestconfIdentifier(argument.getNodeType(),node);
906     }
907
908     private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
909             final ListSchemaNode node, final DOMMountPoint mount) {
910         final QName nodeType = argument.getNodeType();
911         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
912         final Map<QName, Object> keyValues = argument.getKeyValues();
913
914         final StringBuilder builder = new StringBuilder();
915         builder.append('/');
916         builder.append(nodeIdentifier);
917         builder.append('/');
918
919         final List<QName> keyDefinition = node.getKeyDefinition();
920         boolean hasElements = false;
921         for (final QName key : keyDefinition) {
922             for (final DataSchemaNode listChild : node.getChildNodes()) {
923                 if (listChild.getQName().equals(key)) {
924                     if (!hasElements) {
925                         hasElements = true;
926                     } else {
927                         builder.append('/');
928                     }
929
930                     try {
931                         Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
932                         builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
933                     } catch (final UnsupportedEncodingException e) {
934                         LOG.error("Error parsing URI: {}", keyValues.get(key), e);
935                         return null;
936                     }
937                     break;
938                 }
939             }
940         }
941
942         return builder.toString();
943     }
944
945     private static DataSchemaNode childByQName(final Object container, final QName name) {
946         if (container instanceof ChoiceCaseNode) {
947             return childByQName((ChoiceCaseNode) container, name);
948         } else if (container instanceof ChoiceSchemaNode) {
949             return childByQName((ChoiceSchemaNode) container, name);
950         } else if (container instanceof ContainerSchemaNode) {
951             return childByQName((ContainerSchemaNode) container, name);
952         } else if (container instanceof ListSchemaNode) {
953             return childByQName((ListSchemaNode) container, name);
954         } else if (container instanceof DataSchemaNode) {
955             return childByQName((DataSchemaNode) container, name);
956         } else if (container instanceof Module) {
957             return childByQName((Module) container, name);
958         } else {
959             throw new IllegalArgumentException("Unhandled parameter types: "
960                     + Arrays.<Object> asList(container, name).toString());
961         }
962     }
963
964     public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
965         try {
966             return dataNormalizer.toNormalized(legacy);
967         } catch (final NullPointerException e) {
968             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
969         }
970     }
971
972     public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
973         try {
974             return dataNormalizer.toLegacy(instanceIdentifier);
975         } catch (final NullPointerException e) {
976             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
977         } catch (final DataNormalizationException e) {
978             throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
979         }
980     }
981
982     public boolean isNodeMixin(final YangInstanceIdentifier path) {
983         final DataNormalizationOperation<?> operation;
984         try {
985             operation = dataNormalizer.getOperation(path);
986         } catch (final DataNormalizationException e) {
987             throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
988         }
989         return operation.isMixin();
990     }
991
992     public DataNormalizationOperation<?> getRootOperation() {
993         return dataNormalizer.getRootOperation();
994     }
995
996 }