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