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