2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.restconf.impl;
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;
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;
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.netconf.sal.restconf.impl.RestconfError.ErrorTag;
41 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
42 import org.opendaylight.yangtools.concepts.Codec;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class ControllerContext implements SchemaContextListener {
72 // FIXME: this should be in md-sal somewhere
73 public static final String MOUNT = "yang-ext:mount";
75 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
77 // FIXME: this should be the current instance which is mutated
78 private static final ControllerContext INSTANCE = new ControllerContext();
80 private static final String NULL_VALUE = "null";
82 private static final String MOUNT_MODULE = "yang-ext";
84 private static final String MOUNT_NODE = "mount";
86 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
88 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
90 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
92 // FIXME; these three should be final
93 private volatile SchemaContext globalSchema;
94 private volatile DOMMountPointService mountService;
95 private DataNormalizer dataNormalizer;
98 public void setGlobalSchema(final SchemaContext globalSchema) {
99 this.globalSchema = globalSchema;
100 this.dataNormalizer = new DataNormalizer(globalSchema);
103 public void setMountService(final DOMMountPointService mountService) {
104 this.mountService = mountService;
107 private ControllerContext() {
110 public static ControllerContext getInstance() {
114 private void checkPreconditions() {
115 if (this.globalSchema == null) {
116 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
120 public void setSchemas(final SchemaContext schemas) {
121 onGlobalContextUpdated(schemas);
124 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
125 return toIdentifier(restconfInstance, false);
128 public SchemaContext getGlobalSchema() {
129 return this.globalSchema;
132 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
133 return toIdentifier(restconfInstance, true);
136 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
137 final boolean toMountPointIdentifier) {
138 checkPreconditions();
140 if (restconfInstance == null) {
141 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
145 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
146 omitFirstAndLastEmptyString(pathArgs);
147 if (pathArgs.isEmpty()) {
151 final String first = pathArgs.iterator().next();
152 final String startModule = toModuleName(first);
153 if (startModule == null) {
154 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
155 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
158 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
159 final Module latestModule = this.globalSchema.findModuleByName(startModule, null);
161 if (latestModule == null) {
162 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
163 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
166 final InstanceIdentifierContext<?> iiWithSchemaNode =
167 collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier);
169 if (iiWithSchemaNode == null) {
170 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
173 return iiWithSchemaNode;
176 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
177 if (list.isEmpty()) {
181 final String head = list.iterator().next();
182 if (head.isEmpty()) {
186 if (list.isEmpty()) {
190 final String last = list.get(list.size() - 1);
191 if (last.isEmpty()) {
192 list.remove(list.size() - 1);
198 public Module findModuleByName(final String moduleName) {
199 checkPreconditions();
200 Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty());
201 return this.globalSchema.findModuleByName(moduleName, null);
204 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
205 Preconditions.checkArgument((moduleName != null) && (mountPoint != null));
207 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
208 if (mountPointSchema == null) {
212 return mountPointSchema.findModuleByName(moduleName, null);
215 public Module findModuleByNamespace(final URI namespace) {
216 checkPreconditions();
217 Preconditions.checkArgument(namespace != null);
218 return this.globalSchema.findModuleByNamespaceAndRevision(namespace, null);
221 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
222 Preconditions.checkArgument((namespace != null) && (mountPoint != null));
224 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
225 if (mountPointSchema == null) {
229 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
232 public Module findModuleByNameAndRevision(final QName module) {
233 checkPreconditions();
235 .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
237 return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
240 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
241 checkPreconditions();
243 .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
244 && (mountPoint != null));
246 final SchemaContext schemaContext = mountPoint.getSchemaContext();
247 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
248 module.getRevision());
251 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
252 checkPreconditions();
254 final Iterable<PathArgument> elements = path.getPathArguments();
255 final PathArgument head = elements.iterator().next();
256 final QName startQName = head.getNodeType();
257 final Module initialModule = this.globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
258 startQName.getRevision());
259 DataNodeContainer node = initialModule;
260 for (final PathArgument element : elements) {
261 final QName _nodeType = element.getNodeType();
262 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
263 if ((potentialNode == null) || !isListOrContainer(potentialNode)) {
266 node = (DataNodeContainer) potentialNode;
272 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
273 checkPreconditions();
275 final Iterable<PathArgument> elements = path.getPathArguments();
276 final StringBuilder builder = new StringBuilder();
277 final PathArgument head = elements.iterator().next();
278 final QName startQName = head.getNodeType();
279 final SchemaContext schemaContext;
281 schemaContext = mount.getSchemaContext();
283 schemaContext = this.globalSchema;
285 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
286 startQName.getRevision());
287 DataNodeContainer node = initialModule;
288 for (final PathArgument element : elements) {
289 if (!(element instanceof AugmentationIdentifier)) {
290 final QName _nodeType = element.getNodeType();
291 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
292 if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode))
293 && !(potentialNode instanceof ChoiceSchemaNode)) {
294 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
295 if (potentialNode instanceof DataNodeContainer) {
296 node = (DataNodeContainer) potentialNode;
302 return builder.toString();
305 public String findModuleNameByNamespace(final URI namespace) {
306 checkPreconditions();
308 final Module module = this.findModuleByNamespace(namespace);
309 return module == null ? null : module.getName();
312 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
313 final Module module = this.findModuleByNamespace(mountPoint, namespace);
314 return module == null ? null : module.getName();
317 public URI findNamespaceByModuleName(final String moduleName) {
318 final Module module = this.findModuleByName(moduleName);
319 return module == null ? null : module.getNamespace();
322 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
323 final Module module = this.findModuleByName(mountPoint, moduleName);
324 return module == null ? null : module.getNamespace();
327 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
328 checkPreconditions();
330 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
331 return schemaContext == null ? null : schemaContext.getModules();
334 public Set<Module> getAllModules() {
335 checkPreconditions();
336 return this.globalSchema.getModules();
339 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
340 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
341 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
344 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
345 final SchemaContext schema;
347 schema = mount.getSchemaContext();
349 checkPreconditions();
350 schema = this.globalSchema;
353 return toRestconfIdentifier(schema, qname);
356 public CharSequence toRestconfIdentifier(final QName qname) {
357 checkPreconditions();
359 return toRestconfIdentifier(this.globalSchema, qname);
362 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
363 if (mountPoint == null) {
367 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
370 public Module getRestconfModule() {
371 return findModuleByNameAndRevision(RestConfModule.IETF_RESTCONF_QNAME);
374 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
375 final Module restconfModule = getRestconfModule();
376 if (restconfModule == null) {
380 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
382 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
383 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
385 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
387 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
388 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
389 return Iterables.getFirst(instanceDataChildrenByName, null);
392 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
393 final String schemaNodeName) {
394 Module restconfModule = inRestconfModule;
395 if (restconfModule == null) {
396 restconfModule = getRestconfModule();
399 if (restconfModule == null) {
403 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
404 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
405 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
406 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
408 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
409 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
410 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
412 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
413 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
414 ((DataNodeContainer) restconfContainer), RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
415 return Iterables.getFirst(instances, null);
416 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
417 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
418 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
419 return Iterables.getFirst(instances, null);
420 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
421 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
422 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
423 final DataSchemaNode modules = Iterables.getFirst(instances, null);
424 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
425 RestConfModule.STREAM_LIST_SCHEMA_NODE);
426 return Iterables.getFirst(instances, null);
427 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
428 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
429 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
430 return Iterables.getFirst(instances, null);
431 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
432 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
433 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
434 final DataSchemaNode modules = Iterables.getFirst(instances, null);
435 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
436 RestConfModule.MODULE_LIST_SCHEMA_NODE);
437 return Iterables.getFirst(instances, null);
438 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
439 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
440 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
441 return Iterables.getFirst(instances, null);
447 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
448 for (final ChoiceCaseNode caze : container.getCases()) {
449 final DataSchemaNode ret = childByQName(caze, name);
458 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
459 return container.getDataChildByName(name);
462 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
463 return dataNodeChildByQName(container, name);
466 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
467 return dataNodeChildByQName(container, name);
470 private static DataSchemaNode childByQName(final Module container, final QName name) {
471 return dataNodeChildByQName(container, name);
474 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
479 private static DataSchemaNode childByQName(final Object container, final QName name) {
480 if (container instanceof ChoiceCaseNode) {
481 return childByQName((ChoiceCaseNode) container, name);
482 } else if (container instanceof ChoiceSchemaNode) {
483 return childByQName((ChoiceSchemaNode) container, name);
484 } else if (container instanceof ContainerSchemaNode) {
485 return childByQName((ContainerSchemaNode) container, name);
486 } else if (container instanceof ListSchemaNode) {
487 return childByQName((ListSchemaNode) container, name);
488 } else if (container instanceof DataSchemaNode) {
489 return childByQName((DataSchemaNode) container, name);
490 } else if (container instanceof Module) {
491 return childByQName((Module) container, name);
493 throw new IllegalArgumentException("Unhandled parameter types: "
494 + Arrays.<Object>asList(container, name).toString());
498 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
499 final DataSchemaNode ret = container.getDataChildByName(name);
501 for (final DataSchemaNode node : container.getChildNodes()) {
502 if ((node instanceof ChoiceSchemaNode)) {
503 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
504 final DataSchemaNode childByQName = childByQName(choiceNode, name);
505 if (childByQName != null) {
514 private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
515 throws UnsupportedEncodingException {
516 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
517 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
518 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
521 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
522 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
523 final boolean returnJustMountPoint) {
524 Preconditions.<List<String>>checkNotNull(strings);
526 if (parentNode == null) {
530 if (strings.isEmpty()) {
531 return createContext(builder.build(), ((DataSchemaNode) parentNode),
532 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
535 final String head = strings.iterator().next();
536 final String nodeName = toNodeName(head);
537 final String moduleName = toModuleName(head);
539 DataSchemaNode targetNode = null;
540 if (!Strings.isNullOrEmpty(moduleName)) {
541 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
542 if (mountPoint != null) {
543 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
544 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
547 if (this.mountService == null) {
548 throw new RestconfDocumentedException(
549 "MountService was not found. Finding behind mount points does not work.",
550 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
553 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
554 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
555 if (!mountOpt.isPresent()) {
556 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
557 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
558 ErrorTag.DATA_MISSING);
560 final DOMMountPoint mount = mountOpt.get();
562 final SchemaContext mountPointSchema = mount.getSchemaContext();
563 if (mountPointSchema == null) {
564 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
565 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
568 if (returnJustMountPoint || (strings.size() == 1)) {
569 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
570 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
573 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
574 if (moduleNameBehindMountPoint == null) {
575 throw new RestconfDocumentedException(
576 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
577 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
580 final Module moduleBehindMountPoint =
581 mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
582 if (moduleBehindMountPoint == null) {
583 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
584 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
587 final List<String> subList = strings.subList(1, strings.size());
588 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
589 returnJustMountPoint);
592 Module module = null;
593 if (mountPoint == null) {
594 checkPreconditions();
595 module = this.globalSchema.findModuleByName(moduleName, null);
596 if (module == null) {
597 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
598 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
601 final SchemaContext schemaContext = mountPoint.getSchemaContext();
602 if (schemaContext != null) {
603 module = schemaContext.findModuleByName(moduleName, null);
607 if (module == null) {
608 throw new RestconfDocumentedException("\"" + moduleName
609 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
613 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
615 if ((targetNode == null) && (parentNode instanceof Module)) {
616 final RpcDefinition rpc;
617 if (mountPoint == null) {
618 rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
620 final String rpcName = toNodeName(head);
621 ControllerContext.getInstance();
622 rpc = ControllerContext.getRpcDefinition(module, rpcName);
625 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
626 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
630 if (targetNode == null) {
631 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
632 + "\" was not found in parent data node.\n" + " 2. \"" + head
633 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
634 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
637 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
638 if (potentialSchemaNodes.size() > 1) {
639 final StringBuilder strBuilder = new StringBuilder();
640 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
641 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
644 throw new RestconfDocumentedException(
645 "URI has bad format. Node \""
646 + nodeName + "\" is added as augment from more than one module. "
647 + "Therefore the node must have module name "
648 + "and it has to be in format \"moduleName:nodeName\"."
649 + "\nThe node is added as augment from modules with namespaces:\n"
650 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
653 if (potentialSchemaNodes.isEmpty()) {
654 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
655 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
658 targetNode = potentialSchemaNodes.iterator().next();
661 if (!isListOrContainer(targetNode)) {
662 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
663 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
667 if ((targetNode instanceof ListSchemaNode)) {
668 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
669 final int keysSize = listNode.getKeyDefinition().size();
670 if ((strings.size() - consumed) < keysSize) {
671 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
672 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
675 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
676 final HashMap<QName, Object> keyValues = new HashMap<>();
678 for (final QName key : listNode.getKeyDefinition()) {
680 final String uriKeyValue = uriKeyValues.get(index);
681 if (uriKeyValue.equals(NULL_VALUE)) {
682 throw new RestconfDocumentedException("URI has bad format. List \""
683 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
684 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
687 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
692 consumed = consumed + index;
693 builder.nodeWithKey(targetNode.getQName(), keyValues);
695 builder.node(targetNode.getQName());
698 if ((targetNode instanceof DataNodeContainer)) {
699 final List<String> remaining = strings.subList(consumed, strings.size());
700 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
701 returnJustMountPoint);
704 return createContext(builder.build(), targetNode, mountPoint,
705 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
708 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
709 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
710 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
711 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
714 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
715 final String name, final URI namespace) {
716 Preconditions.checkNotNull(namespace);
718 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
719 node -> namespace.equals(node.getQName().getNamespace()));
720 return Iterables.getFirst(result, null);
723 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
725 Preconditions.checkNotNull(container);
726 Preconditions.checkNotNull(name);
728 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
729 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
730 return instantiatedDataNodeContainers;
733 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
734 final DataNodeContainer container, final String name) {
736 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
737 node -> name.equals(node.getQName().getLocalName()));
739 // Can't combine this loop with the filter above because the filter is
740 // lazily-applied by Iterables.filter.
741 for (final DataSchemaNode potentialNode : nodes) {
742 if (isInstantiatedDataSchema(potentialNode)) {
743 potentialSchemaNodes.add(potentialNode);
747 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
748 ChoiceSchemaNode.class);
749 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
750 for (final ChoiceCaseNode caze : Iterables.concat(map)) {
751 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
755 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
756 return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode)
757 || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode)
758 || (node instanceof AnyXmlSchemaNode);
761 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
762 final DOMMountPoint mountPoint) {
763 Preconditions.checkNotNull(uriValue);
764 Preconditions.checkArgument((node instanceof LeafSchemaNode));
766 final String urlDecoded = urlPathArgDecode(uriValue);
767 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
768 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
769 if (baseType instanceof LeafrefTypeDefinition) {
770 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, this.globalSchema,
773 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
774 Object decoded = codec.deserialize(urlDecoded);
775 String additionalInfo = "";
776 if (decoded == null) {
777 if ((typedef instanceof IdentityrefTypeDefinition)) {
778 final SchemaContext schemaContext =
779 mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
780 decoded = toQName(schemaContext, urlDecoded, null);
782 "For key which is of type identityref it should be in format module_name:identity_name.";
786 if (decoded == null) {
787 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
788 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
791 map.put(node.getQName(), decoded);
794 private static String toModuleName(final String str) {
795 final int idx = str.indexOf(':');
800 // Make sure there is only one occurrence
801 if (str.indexOf(':', idx + 1) != -1) {
805 return str.substring(0, idx);
808 private static String toNodeName(final String str) {
809 final int idx = str.indexOf(':');
814 // Make sure there is only one occurrence
815 if (str.indexOf(':', idx + 1) != -1) {
819 return str.substring(idx + 1);
822 private QName toQName(final SchemaContext schemaContext, final String name, final Date revisionDate) {
823 checkPreconditions();
824 final String module = toModuleName(name);
825 final String node = toNodeName(name);
826 final Module m = schemaContext.findModuleByName(module, revisionDate);
827 return m == null ? null : QName.create(m.getQNameModule(), node);
830 private static boolean isListOrContainer(final DataSchemaNode node) {
831 return (node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode);
834 public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) {
835 final QName validName = toQName(this.globalSchema, name, revisionDate);
836 return validName == null ? null : this.qnameToRpc.get().get(validName);
839 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
840 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
841 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
842 if (rpcQName.equals(rpcDefinition.getQName())) {
843 return rpcDefinition;
850 public void onGlobalContextUpdated(final SchemaContext context) {
851 if (context != null) {
852 final Collection<RpcDefinition> defs = context.getOperations();
853 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
855 for (final RpcDefinition operation : defs) {
856 newMap.put(operation.getQName(), operation);
859 // FIXME: still not completely atomic
860 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
861 setGlobalSchema(context);
865 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
867 final List<String> decodedPathArgs = new ArrayList<>();
868 for (final String pathArg : strings) {
869 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
870 decodedPathArgs.add(_decode);
872 return decodedPathArgs;
873 } catch (final UnsupportedEncodingException e) {
874 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
875 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
879 public String urlPathArgDecode(final String pathArg) {
880 if (pathArg != null) {
882 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
883 } catch (final UnsupportedEncodingException e) {
884 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
885 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
892 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
893 final DOMMountPoint mount) {
894 if (argument instanceof NodeIdentifier) {
895 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
896 } else if ((argument instanceof NodeIdentifierWithPredicates) && (node instanceof ListSchemaNode)) {
897 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
898 (ListSchemaNode) node, mount);
899 } else if ((argument != null) && (node != null)) {
900 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
902 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
906 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
907 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
910 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
911 final ListSchemaNode node, final DOMMountPoint mount) {
912 final QName nodeType = argument.getNodeType();
913 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
914 final Map<QName, Object> keyValues = argument.getKeyValues();
916 final StringBuilder builder = new StringBuilder();
918 builder.append(nodeIdentifier);
921 final List<QName> keyDefinition = node.getKeyDefinition();
922 boolean hasElements = false;
923 for (final QName key : keyDefinition) {
924 for (final DataSchemaNode listChild : node.getChildNodes()) {
925 if (listChild.getQName().equals(key)) {
933 Preconditions.checkState(listChild instanceof LeafSchemaNode,
934 "List key has to consist of leaves, not %s", listChild);
935 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
936 } catch (final UnsupportedEncodingException e) {
937 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
945 return builder.toString();
948 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
950 return this.dataNormalizer.toNormalized(legacy);
951 } catch (final NullPointerException e) {
952 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
956 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
958 return this.dataNormalizer.toLegacy(instanceIdentifier);
959 } catch (final NullPointerException e) {
960 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
961 } catch (final DataNormalizationException e) {
962 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
966 public boolean isNodeMixin(final YangInstanceIdentifier path) {
967 final DataNormalizationOperation<?> operation;
969 operation = this.dataNormalizer.getOperation(path);
970 } catch (final DataNormalizationException e) {
971 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
973 return operation.isMixin();
976 public DataNormalizationOperation<?> getRootOperation() {
977 return this.dataNormalizer.getRootOperation();