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