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