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