BUG 2805 - Fixed Restconf RPC calls and POST to create data
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / 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.controller.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.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
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.controller.sal.rest.api.Draft02;
40 import org.opendaylight.controller.sal.rest.impl.RestUtil;
41 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
42 import org.opendaylight.controller.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.CompositeNode;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
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 = "ISO-8859-1";
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         final InstanceIdentifierContext iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
160                 toMountPointIdentifier);
161
162         if (iiWithSchemaNode == null) {
163             throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
164         }
165
166         return iiWithSchemaNode;
167     }
168
169     private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
170         if (list.isEmpty()) {
171             return list;
172         }
173
174         final String head = list.iterator().next();
175         if (head.isEmpty()) {
176             list.remove(0);
177         }
178
179         if (list.isEmpty()) {
180             return list;
181         }
182
183         final String last = list.get(list.size() - 1);
184         if (last.isEmpty()) {
185             list.remove(list.size() - 1);
186         }
187
188         return list;
189     }
190     public Module findModuleByName(final String moduleName) {
191         checkPreconditions();
192         Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
193         return globalSchema.findModuleByName(moduleName, null);
194     }
195
196     public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
197         Preconditions.checkArgument(moduleName != null && mountPoint != null);
198
199         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
200         if (mountPointSchema == null) {
201             return null;
202         }
203
204         return mountPointSchema.findModuleByName(moduleName, null);
205     }
206
207     public Module findModuleByNamespace(final URI namespace) {
208         checkPreconditions();
209         Preconditions.checkArgument(namespace != null);
210         return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
211     }
212
213     public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
214         Preconditions.checkArgument(namespace != null && mountPoint != null);
215
216         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
217         if (mountPointSchema == null) {
218             return null;
219         }
220
221         return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
222     }
223
224     public Module findModuleByNameAndRevision(final QName module) {
225         checkPreconditions();
226         Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
227
228         return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
229     }
230
231     public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
232         checkPreconditions();
233         Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
234                 && mountPoint != null);
235
236         final SchemaContext schemaContext = mountPoint.getSchemaContext();
237         return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
238                 module.getRevision());
239     }
240
241     public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
242         checkPreconditions();
243
244         final Iterable<PathArgument> elements = path.getPathArguments();
245         final PathArgument head = elements.iterator().next();
246         final QName startQName = head.getNodeType();
247         final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
248                 startQName.getRevision());
249         DataNodeContainer node = initialModule;
250         for (final PathArgument element : elements) {
251             final QName _nodeType = element.getNodeType();
252             final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
253             if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
254                 return null;
255             }
256             node = (DataNodeContainer) potentialNode;
257         }
258
259         return node;
260     }
261
262     public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
263         checkPreconditions();
264
265         final Iterable<PathArgument> elements = path.getPathArguments();
266         final StringBuilder builder = new StringBuilder();
267         final PathArgument head = elements.iterator().next();
268         final QName startQName = head.getNodeType();
269         final SchemaContext schemaContext;
270         if (mount != null) {
271             schemaContext = mount.getSchemaContext();
272         } else {
273             schemaContext = globalSchema;
274         }
275         final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
276                 startQName.getRevision());
277         DataNodeContainer node = initialModule;
278         for (final PathArgument element : elements) {
279             if (!(element instanceof AugmentationIdentifier)) {
280                 final QName _nodeType = element.getNodeType();
281                 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
282                 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)) {
283                     if (!ControllerContext.isListOrContainer(potentialNode)) {
284                         return null;
285                     }
286                     builder.append(convertToRestconfIdentifier(element, (DataNodeContainer) potentialNode, mount));
287                     node = (DataNodeContainer) potentialNode;
288                 }
289             }
290         }
291
292         return builder.toString();
293     }
294
295     public String findModuleNameByNamespace(final URI namespace) {
296         checkPreconditions();
297
298         final Module module = this.findModuleByNamespace(namespace);
299         return module == null ? null : module.getName();
300     }
301
302     public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
303         final Module module = this.findModuleByNamespace(mountPoint, namespace);
304         return module == null ? null : module.getName();
305     }
306
307     public URI findNamespaceByModuleName(final String moduleName) {
308         final Module module = this.findModuleByName(moduleName);
309         return module == null ? null : module.getNamespace();
310     }
311
312     public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
313         final Module module = this.findModuleByName(mountPoint, moduleName);
314         return module == null ? null : module.getNamespace();
315     }
316
317     public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
318         checkPreconditions();
319
320         final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
321         return schemaContext == null ? null : schemaContext.getModules();
322     }
323
324     public Set<Module> getAllModules() {
325         checkPreconditions();
326         return globalSchema.getModules();
327     }
328
329     private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
330         final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
331         return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
332     }
333
334     public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
335         final SchemaContext schema;
336         if (mount != null) {
337             schema = mount.getSchemaContext();
338         } else {
339             checkPreconditions();
340             schema = globalSchema;
341         }
342
343         return toRestconfIdentifier(schema, qname);
344     }
345
346     public CharSequence toRestconfIdentifier(final QName qname) {
347         checkPreconditions();
348
349         return toRestconfIdentifier(globalSchema, qname);
350     }
351
352     public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
353         if (mountPoint == null) {
354             return null;
355         }
356
357         return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
358     }
359
360     public Module getRestconfModule() {
361         return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
362     }
363
364     private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
365         @Override
366         public boolean apply(final GroupingDefinition g) {
367             return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
368         }
369     };
370
371     public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
372         final Module restconfModule = getRestconfModule();
373         if (restconfModule == null) {
374             return null;
375         }
376
377         final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
378
379         final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
380
381         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
382
383         final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
384                 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
385         return Iterables.getFirst(instanceDataChildrenByName, null);
386     }
387
388     private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
389         @Override
390         public boolean apply(final GroupingDefinition g) {
391             return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
392         }
393     };
394
395     public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
396         Module restconfModule = inRestconfModule;
397         if (restconfModule == null) {
398             restconfModule = getRestconfModule();
399         }
400
401         if (restconfModule == null) {
402             return null;
403         }
404
405         final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
406         final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
407         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
408
409         final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
410                 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
411         final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
412
413         if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
414             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
415                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
416             return Iterables.getFirst(instances, null);
417         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
418             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
419                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
420             return Iterables.getFirst(instances, null);
421         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
422             List<DataSchemaNode> instances = findInstanceDataChildrenByName(
423                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
424             final DataSchemaNode modules = Iterables.getFirst(instances, null);
425             instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
426                     Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
427             return Iterables.getFirst(instances, null);
428         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
429             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
430                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
431             return Iterables.getFirst(instances, null);
432         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
433             List<DataSchemaNode> instances = findInstanceDataChildrenByName(
434                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
435             final DataSchemaNode modules = Iterables.getFirst(instances, null);
436             instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
437                     Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
438             return Iterables.getFirst(instances, null);
439         } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
440             final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
441                     ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
442             return Iterables.getFirst(instances, null);
443         }
444
445         return null;
446     }
447
448     private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
449         for (final ChoiceCaseNode caze : container.getCases()) {
450             final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
451             if (ret != null) {
452                 return ret;
453             }
454         }
455
456         return null;
457     }
458
459     private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
460         return container.getDataChildByName(name);
461     }
462
463     private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
464         return ControllerContext.dataNodeChildByQName(container, name);
465     }
466
467     private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
468         return ControllerContext.dataNodeChildByQName(container, name);
469     }
470
471     private static DataSchemaNode childByQName(final Module container, final QName name) {
472         return ControllerContext.dataNodeChildByQName(container, name);
473     }
474
475     private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
476         return null;
477     }
478
479     private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
480         final DataSchemaNode ret = container.getDataChildByName(name);
481         if (ret == null) {
482             for (final DataSchemaNode node : container.getChildNodes()) {
483                 if ((node instanceof ChoiceNode)) {
484                     final ChoiceNode choiceNode = ((ChoiceNode) node);
485                     final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
486                     if (childByQName != null) {
487                         return childByQName;
488                     }
489                 }
490             }
491         }
492         return ret;
493     }
494
495     private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
496         final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
497         return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
498     }
499
500     private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
501             final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
502             final boolean returnJustMountPoint) {
503         Preconditions.<List<String>> checkNotNull(strings);
504
505         if (parentNode == null) {
506             return null;
507         }
508
509         if (strings.isEmpty()) {
510             return createContext(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
511         }
512
513         final String head = strings.iterator().next();
514         final String nodeName = toNodeName(head);
515         final String moduleName = ControllerContext.toModuleName(head);
516
517         DataSchemaNode targetNode = null;
518         if (!Strings.isNullOrEmpty(moduleName)) {
519             if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
520                     && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
521                 if (mountPoint != null) {
522                     throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
523                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
524                 }
525
526                 if (mountService == null) {
527                     throw new RestconfDocumentedException(
528                             "MountService was not found. Finding behind mount points does not work.",
529                             ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
530                 }
531
532                 final YangInstanceIdentifier partialPath = builder.toInstance();
533                 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
534                 if (!mountOpt.isPresent()) {
535                     LOG.debug("Instance identifier to missing mount point: {}", partialPath);
536                     throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
537                             ErrorTag.UNKNOWN_ELEMENT);
538                 }
539                 final DOMMountPoint mount = mountOpt.get();
540
541                 final SchemaContext mountPointSchema = mount.getSchemaContext();
542                 if (mountPointSchema == null) {
543                     throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
544                             ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
545                 }
546
547                 if (returnJustMountPoint) {
548                     final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
549                     return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
550                 }
551
552                 if (strings.size() == 1) {
553                     final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
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 = ControllerContext.getInstance().getRpcDefinition(head);
600                 if (rpc != null) {
601                     return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
602                             mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
603                 }
604             }
605
606             if (targetNode == null) {
607                 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
608                         + "\" was not found in parent data node.\n" + " 2. \"" + head
609                         + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
610                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
611             }
612         } else {
613             final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
614             if (potentialSchemaNodes.size() > 1) {
615                 final StringBuilder strBuilder = new StringBuilder();
616                 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
617                     strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
618                 }
619
620                 throw new RestconfDocumentedException(
621                         "URI has bad format. Node \""
622                                 + nodeName
623                                 + "\" is added as augment from more than one module. "
624                                 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
625                                 + "\nThe node is added as augment from modules with namespaces:\n"
626                                 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
627             }
628
629             if (potentialSchemaNodes.isEmpty()) {
630                 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
631                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
632             }
633
634             targetNode = potentialSchemaNodes.iterator().next();
635         }
636
637         if (!ControllerContext.isListOrContainer(targetNode)) {
638             throw new RestconfDocumentedException("URI has bad format. Node \"" + head
639                     + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
640         }
641
642         int consumed = 1;
643         if ((targetNode instanceof ListSchemaNode)) {
644             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
645             final int keysSize = listNode.getKeyDefinition().size();
646             if ((strings.size() - consumed) < keysSize) {
647                 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
648                         + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
649             }
650
651             final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
652             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
653             int i = 0;
654             for (final QName key : listNode.getKeyDefinition()) {
655                 {
656                     final String uriKeyValue = uriKeyValues.get(i);
657                     if (uriKeyValue.equals(NULL_VALUE)) {
658                         throw new RestconfDocumentedException("URI has bad format. List \""
659                                 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
660                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
661                     }
662
663                     addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
664                     i++;
665                 }
666             }
667
668             consumed = consumed + i;
669             builder.nodeWithKey(targetNode.getQName(), keyValues);
670         } else {
671             builder.node(targetNode.getQName());
672         }
673
674         if ((targetNode instanceof DataNodeContainer)) {
675             final List<String> remaining = strings.subList(consumed, strings.size());
676             return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
677                     returnJustMountPoint);
678         }
679
680         return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
681     }
682
683     private InstanceIdentifierContext createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
684             final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
685
686         final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
687         return new InstanceIdentifierContext(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
688     }
689
690     public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
691             final URI namespace) {
692         Preconditions.<URI> checkNotNull(namespace);
693
694         final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
695
696         final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
697             @Override
698             public boolean apply(final DataSchemaNode node) {
699                 return Objects.equal(node.getQName().getNamespace(), namespace);
700             }
701         };
702
703         final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
704         return Iterables.getFirst(result, null);
705     }
706
707     public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
708         Preconditions.<DataNodeContainer> checkNotNull(container);
709         Preconditions.<String> checkNotNull(name);
710
711         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
712         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
713         return instantiatedDataNodeContainers;
714     }
715
716     private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
717         @Override
718         public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
719             return node.getCases();
720         }
721     };
722
723     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
724             final DataNodeContainer container, final String name) {
725
726         final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
727             @Override
728             public boolean apply(final DataSchemaNode node) {
729                 return Objects.equal(node.getQName().getLocalName(), name);
730             }
731         };
732
733         final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
734
735         // Can't combine this loop with the filter above because the filter is
736         // lazily-applied by Iterables.filter.
737         for (final DataSchemaNode potentialNode : nodes) {
738             if (isInstantiatedDataSchema(potentialNode)) {
739                 potentialSchemaNodes.add(potentialNode);
740             }
741         }
742
743         final Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
744         final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
745
746         final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
747         for (final ChoiceCaseNode caze : allCases) {
748             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
749         }
750     }
751
752     public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
753         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
754                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
755                 || node instanceof AnyXmlSchemaNode;
756     }
757
758     private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
759             final DOMMountPoint mountPoint) {
760         Preconditions.<String> checkNotNull(uriValue);
761         Preconditions.checkArgument((node instanceof LeafSchemaNode));
762
763         final String urlDecoded = urlPathArgDecode(uriValue);
764         final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
765         final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
766
767         Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
768         String additionalInfo = "";
769         if (decoded == null) {
770             final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
771             if ((baseType instanceof IdentityrefTypeDefinition)) {
772                 decoded = toQName(urlDecoded);
773                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
774             }
775         }
776
777         if (decoded == null) {
778             throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
779                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
780         }
781
782         map.put(node.getQName(), decoded);
783     }
784
785     private static String toModuleName(final String str) {
786         final int idx = str.indexOf(':');
787         if (idx == -1) {
788             return null;
789         }
790
791         // Make sure there is only one occurrence
792         if (str.indexOf(':', idx + 1) != -1) {
793             return null;
794         }
795
796         return str.substring(0, idx);
797     }
798
799     private static String toNodeName(final String str) {
800         final int idx = str.indexOf(':');
801         if (idx == -1) {
802             return str;
803         }
804
805         // Make sure there is only one occurrence
806         if (str.indexOf(':', idx + 1) != -1) {
807             return str;
808         }
809
810         return str.substring(idx + 1);
811     }
812
813     private QName toQName(final String name) {
814         checkPreconditions();
815         final String module = toModuleName(name);
816         final String node = toNodeName(name);
817         final Module m = globalSchema.findModuleByName(module, null);
818         return m == null ? null : QName.create(m.getQNameModule(), node);
819     }
820
821     private static boolean isListOrContainer(final DataSchemaNode node) {
822         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
823     }
824
825     public RpcDefinition getRpcDefinition(final String name) {
826         final QName validName = toQName(name);
827         return validName == null ? null : qnameToRpc.get().get(validName);
828     }
829
830     @Override
831     public void onGlobalContextUpdated(final SchemaContext context) {
832         if (context != null) {
833             final Collection<RpcDefinition> defs = context.getOperations();
834             final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
835
836             for (final RpcDefinition operation : defs) {
837                 newMap.put(operation.getQName(), operation);
838             }
839
840             // FIXME: still not completely atomic
841             qnameToRpc.set(ImmutableMap.copyOf(newMap));
842             setGlobalSchema(context);
843         }
844     }
845
846     public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
847         try {
848             final List<String> decodedPathArgs = new ArrayList<String>();
849             for (final String pathArg : strings) {
850                 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
851                 decodedPathArgs.add(_decode);
852             }
853             return decodedPathArgs;
854         } catch (final UnsupportedEncodingException e) {
855             throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
856                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
857         }
858     }
859
860     public String urlPathArgDecode(final String pathArg) {
861         if (pathArg != null) {
862             try {
863                 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
864             } catch (final UnsupportedEncodingException e) {
865                 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
866                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
867             }
868         }
869
870         return null;
871     }
872
873     private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node, final DOMMountPoint mount) {
874         if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
875             return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
876         } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
877             return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node, mount);
878         } else if (argument != null && node != null) {
879             throw new IllegalArgumentException("Conversion of generic path argument is not supported");
880         } else {
881             throw new IllegalArgumentException("Unhandled parameter types: "
882                     + Arrays.<Object> asList(argument, node).toString());
883         }
884     }
885
886     private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
887         return "/" + this.toRestconfIdentifier(argument.getNodeType(),node);
888     }
889
890     private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
891             final ListSchemaNode node, final DOMMountPoint mount) {
892         final QName nodeType = argument.getNodeType();
893         final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
894         final Map<QName, Object> keyValues = argument.getKeyValues();
895
896         final StringBuilder builder = new StringBuilder();
897         builder.append('/');
898         builder.append(nodeIdentifier);
899         builder.append('/');
900
901         final List<QName> keyDefinition = node.getKeyDefinition();
902         boolean hasElements = false;
903         for (final QName key : keyDefinition) {
904             for (final DataSchemaNode listChild : node.getChildNodes()) {
905                 if (listChild.getQName().equals(key)) {
906                     if (!hasElements) {
907                         hasElements = true;
908                     } else {
909                         builder.append('/');
910                     }
911
912                     try {
913                         Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
914                         builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
915                     } catch (final UnsupportedEncodingException e) {
916                         LOG.error("Error parsing URI: {}", keyValues.get(key), e);
917                         return null;
918                     }
919                     break;
920                 }
921             }
922         }
923
924         return builder.toString();
925     }
926
927     private static DataSchemaNode childByQName(final Object container, final QName name) {
928         if (container instanceof ChoiceCaseNode) {
929             return childByQName((ChoiceCaseNode) container, name);
930         } else if (container instanceof ChoiceNode) {
931             return childByQName((ChoiceNode) container, name);
932         } else if (container instanceof ContainerSchemaNode) {
933             return childByQName((ContainerSchemaNode) container, name);
934         } else if (container instanceof ListSchemaNode) {
935             return childByQName((ListSchemaNode) container, name);
936         } else if (container instanceof DataSchemaNode) {
937             return childByQName((DataSchemaNode) container, name);
938         } else if (container instanceof Module) {
939             return childByQName((Module) container, name);
940         } else {
941             throw new IllegalArgumentException("Unhandled parameter types: "
942                     + Arrays.<Object> asList(container, name).toString());
943         }
944     }
945
946     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
947             final CompositeNode compositeNode) {
948         try {
949             return dataNormalizer.toNormalized(legacy, compositeNode);
950         } catch (final NullPointerException e) {
951             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
952         }
953     }
954
955     public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
956         try {
957             return dataNormalizer.toNormalized(legacy);
958         } catch (final NullPointerException e) {
959             throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
960         }
961     }
962
963     public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
964             final NormalizedNode<?,?> normalizedNode) {
965         try {
966             return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
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 }