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