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