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