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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Iterables;
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.io.Closeable;
22 import java.io.UnsupportedEncodingException;
23 import java.net.URLDecoder;
24 import java.net.URLEncoder;
25 import java.nio.charset.StandardCharsets;
26 import java.util.ArrayDeque;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Deque;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Optional;
38 import java.util.concurrent.atomic.AtomicReference;
39 import javax.annotation.PreDestroy;
40 import javax.inject.Inject;
41 import javax.inject.Singleton;
42 import javax.ws.rs.core.Response.Status;
43 import org.eclipse.jdt.annotation.NonNull;
44 import org.eclipse.jdt.annotation.Nullable;
45 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
46 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
47 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
48 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
49 import org.opendaylight.netconf.sal.rest.api.Draft02;
50 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
51 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
52 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
53 import org.opendaylight.restconf.common.util.RestUtil;
54 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
55 import org.opendaylight.yangtools.concepts.ListenerRegistration;
56 import org.opendaylight.yangtools.yang.common.ErrorTag;
57 import org.opendaylight.yangtools.yang.common.ErrorType;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.common.QNameModule;
60 import org.opendaylight.yangtools.yang.common.Revision;
61 import org.opendaylight.yangtools.yang.common.XMLNamespace;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
73 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
75 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
76 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
77 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.Module;
81 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
82 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
90 public final class ControllerContext implements EffectiveModelContextListener, Closeable {
91 // FIXME: this should be in md-sal somewhere
92 public static final String MOUNT = "yang-ext:mount";
94 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
96 private static final String NULL_VALUE = "null";
98 private static final String MOUNT_MODULE = "yang-ext";
100 private static final String MOUNT_NODE = "mount";
102 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
104 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
106 private final DOMMountPointService mountService;
107 private final DOMYangTextSourceProvider yangTextSourceProvider;
108 private final ListenerRegistration<?> listenerRegistration;
109 private volatile EffectiveModelContext globalSchema;
110 private volatile DataNormalizer dataNormalizer;
113 public ControllerContext(final DOMSchemaService schemaService, final DOMMountPointService mountService,
114 final DOMSchemaService domSchemaService) {
115 this.mountService = mountService;
116 yangTextSourceProvider = domSchemaService.getExtensions().getInstance(DOMYangTextSourceProvider.class);
118 onModelContextUpdated(schemaService.getGlobalContext());
119 listenerRegistration = schemaService.registerSchemaContextListener(this);
125 * @deprecated Just use the
126 * {@link #ControllerContext(DOMSchemaService, DOMMountPointService, DOMSchemaService)}
127 * constructor instead.
130 public static ControllerContext newInstance(final DOMSchemaService schemaService,
131 final DOMMountPointService mountService, final DOMSchemaService domSchemaService) {
132 return new ControllerContext(schemaService, mountService, domSchemaService);
135 private void setGlobalSchema(final EffectiveModelContext globalSchema) {
136 this.globalSchema = globalSchema;
137 dataNormalizer = new DataNormalizer(globalSchema);
140 public DOMYangTextSourceProvider getYangTextSourceProvider() {
141 return yangTextSourceProvider;
144 private void checkPreconditions() {
145 if (globalSchema == null) {
146 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
152 public void close() {
153 listenerRegistration.close();
156 public void setSchemas(final EffectiveModelContext schemas) {
157 onModelContextUpdated(schemas);
160 public InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
161 return toIdentifier(restconfInstance, false);
164 public EffectiveModelContext getGlobalSchema() {
168 public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
169 return toIdentifier(restconfInstance, true);
172 private InstanceIdentifierContext toIdentifier(final String restconfInstance,
173 final boolean toMountPointIdentifier) {
174 checkPreconditions();
176 if (restconfInstance == null) {
177 return InstanceIdentifierContext.ofLocalRoot(globalSchema);
180 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
181 omitFirstAndLastEmptyString(pathArgs);
182 if (pathArgs.isEmpty()) {
186 final String first = pathArgs.iterator().next();
187 final String startModule = toModuleName(first);
188 if (startModule == null) {
189 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
190 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
193 final Collection<? extends Module> latestModule = globalSchema.findModules(startModule);
194 if (latestModule.isEmpty()) {
195 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
196 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
199 final InstanceIdentifierContext iiWithSchemaNode = collectPathArguments(YangInstanceIdentifier.builder(),
200 new ArrayDeque<>(), pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
202 if (iiWithSchemaNode == null) {
203 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
206 return iiWithSchemaNode;
209 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
210 if (list.isEmpty()) {
214 final String head = list.iterator().next();
215 if (head.isEmpty()) {
219 if (list.isEmpty()) {
223 final String last = list.get(list.size() - 1);
224 if (last.isEmpty()) {
225 list.remove(list.size() - 1);
231 public Module findModuleByName(final String moduleName) {
232 checkPreconditions();
233 checkArgument(moduleName != null && !moduleName.isEmpty());
234 return globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
237 public static Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
238 checkArgument(moduleName != null && mountPoint != null);
240 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
241 return mountPointSchema == null ? null
242 : mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
245 public Module findModuleByNamespace(final XMLNamespace namespace) {
246 checkPreconditions();
247 checkArgument(namespace != null);
248 return globalSchema.findModules(namespace).stream().findFirst().orElse(null);
251 public static Module findModuleByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
252 checkArgument(namespace != null && mountPoint != null);
254 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
255 return mountPointSchema == null ? null
256 : mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
259 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
260 checkPreconditions();
261 checkArgument(name != null && revision != null);
263 return globalSchema.findModule(name, revision).orElse(null);
266 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
267 final Revision revision) {
268 checkPreconditions();
269 checkArgument(name != null && revision != null && mountPoint != null);
271 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
272 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
275 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
276 checkPreconditions();
278 final Iterable<PathArgument> elements = path.getPathArguments();
279 final PathArgument head = elements.iterator().next();
280 final QName startQName = head.getNodeType();
281 final Module initialModule = globalSchema.findModule(startQName.getModule()).orElse(null);
282 DataNodeContainer node = initialModule;
283 for (final PathArgument element : elements) {
284 final QName _nodeType = element.getNodeType();
285 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
286 if (potentialNode == null || !isListOrContainer(potentialNode)) {
289 node = (DataNodeContainer) potentialNode;
295 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
296 checkPreconditions();
298 final Iterable<PathArgument> elements = path.getPathArguments();
299 final StringBuilder builder = new StringBuilder();
300 final PathArgument head = elements.iterator().next();
301 final QName startQName = head.getNodeType();
302 final EffectiveModelContext schemaContext;
304 schemaContext = getModelContext(mount);
306 schemaContext = globalSchema;
308 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
309 DataNodeContainer node = initialModule;
310 for (final PathArgument element : elements) {
311 if (!(element instanceof AugmentationIdentifier)) {
312 final QName _nodeType = element.getNodeType();
313 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
314 if ((!(element instanceof NodeIdentifier) || !(potentialNode instanceof ListSchemaNode))
315 && !(potentialNode instanceof ChoiceSchemaNode)) {
316 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
317 if (potentialNode instanceof DataNodeContainer) {
318 node = (DataNodeContainer) potentialNode;
324 return builder.toString();
327 public String findModuleNameByNamespace(final XMLNamespace namespace) {
328 checkPreconditions();
330 final Module module = findModuleByNamespace(namespace);
331 return module == null ? null : module.getName();
334 public static String findModuleNameByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
335 final Module module = findModuleByNamespace(mountPoint, namespace);
336 return module == null ? null : module.getName();
339 public XMLNamespace findNamespaceByModuleName(final String moduleName) {
340 final Module module = findModuleByName(moduleName);
341 return module == null ? null : module.getNamespace();
344 public static XMLNamespace findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
345 final Module module = findModuleByName(mountPoint, moduleName);
346 return module == null ? null : module.getNamespace();
349 public Collection<? extends Module> getAllModules(final DOMMountPoint mountPoint) {
350 checkPreconditions();
352 final EffectiveModelContext schemaContext = mountPoint == null ? null : getModelContext(mountPoint);
353 return schemaContext == null ? null : schemaContext.getModules();
356 public Collection<? extends Module> getAllModules() {
357 checkPreconditions();
358 return globalSchema.getModules();
361 private static String toRestconfIdentifier(final EffectiveModelContext context, final QName qname) {
362 final Module schema = context.findModule(qname.getModule()).orElse(null);
363 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
366 public String toRestconfIdentifier(final QName qname, final DOMMountPoint mountPoint) {
367 return mountPoint != null ? toRestconfIdentifier(getModelContext(mountPoint), qname)
368 : toRestconfIdentifier(qname);
371 public String toRestconfIdentifier(final QName qname) {
372 checkPreconditions();
374 return toRestconfIdentifier(globalSchema, qname);
377 public static String toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
378 return mountPoint == null ? null : toRestconfIdentifier(getModelContext(mountPoint), qname);
381 public Module getRestconfModule() {
382 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
385 public Entry<SchemaInferenceStack, ContainerSchemaNode> getRestconfModuleErrorsSchemaNode() {
386 checkPreconditions();
388 final var schema = globalSchema;
389 final var namespace = QNameModule.create(XMLNamespace.of(Draft02.RestConfModule.NAMESPACE),
390 Revision.of(Draft02.RestConfModule.REVISION));
391 if (schema.findModule(namespace).isEmpty()) {
395 final var stack = SchemaInferenceStack.of(globalSchema);
396 stack.enterGrouping(RestConfModule.ERRORS_QNAME);
397 final var stmt = stack.enterSchemaTree(RestConfModule.ERRORS_QNAME);
398 verify(stmt instanceof ContainerSchemaNode, "Unexpected statement %s", stmt);
399 return Map.entry(stack, (ContainerSchemaNode) stmt);
402 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
403 final String schemaNodeName) {
404 Module restconfModule = inRestconfModule;
405 if (restconfModule == null) {
406 restconfModule = getRestconfModule();
409 if (restconfModule == null) {
413 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
414 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
415 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
416 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
418 final var instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
419 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
420 final DataSchemaNode restconfContainer = getFirst(instanceDataChildrenByName);
422 if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
423 final var instances = findInstanceDataChildrenByName(
424 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
425 return getFirst(instances);
426 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
427 var instances = findInstanceDataChildrenByName(
428 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
429 final DataSchemaNode modules = getFirst(instances);
430 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
431 RestConfModule.STREAM_LIST_SCHEMA_NODE);
432 return getFirst(instances);
433 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
434 final var instances = findInstanceDataChildrenByName(
435 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
436 return getFirst(instances);
437 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
438 var instances = findInstanceDataChildrenByName(
439 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
440 final DataSchemaNode modules = getFirst(instances);
441 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
442 RestConfModule.MODULE_LIST_SCHEMA_NODE);
443 return getFirst(instances);
444 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
445 final var instances = findInstanceDataChildrenByName(
446 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447 return getFirst(instances);
453 public static @Nullable DataSchemaNode getFirst(final List<FoundChild> children) {
454 return children.isEmpty() ? null : children.get(0).child;
457 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
458 for (final CaseSchemaNode caze : container.getCases()) {
459 final DataSchemaNode ret = childByQName(caze, name);
468 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
469 return container.dataChildByName(name);
472 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
473 return dataNodeChildByQName(container, name);
476 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
477 return dataNodeChildByQName(container, name);
480 private static DataSchemaNode childByQName(final Module container, final QName name) {
481 return dataNodeChildByQName(container, name);
484 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
489 private static DataSchemaNode childByQName(final Object container, final QName name) {
490 if (container instanceof CaseSchemaNode) {
491 return childByQName((CaseSchemaNode) container, name);
492 } else if (container instanceof ChoiceSchemaNode) {
493 return childByQName((ChoiceSchemaNode) container, name);
494 } else if (container instanceof ContainerSchemaNode) {
495 return childByQName((ContainerSchemaNode) container, name);
496 } else if (container instanceof ListSchemaNode) {
497 return childByQName((ListSchemaNode) container, name);
498 } else if (container instanceof DataSchemaNode) {
499 return childByQName((DataSchemaNode) container, name);
500 } else if (container instanceof Module) {
501 return childByQName((Module) container, name);
503 throw new IllegalArgumentException("Unhandled parameter types: "
504 + Arrays.asList(container, name).toString());
508 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
509 final DataSchemaNode ret = container.dataChildByName(name);
511 for (final DataSchemaNode node : container.getChildNodes()) {
512 if (node instanceof ChoiceSchemaNode) {
513 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
514 final DataSchemaNode childByQName = childByQName(choiceNode, name);
515 if (childByQName != null) {
524 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
525 throws UnsupportedEncodingException {
526 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
527 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), StandardCharsets.UTF_8);
530 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
531 private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
532 final Deque<QName> schemaPath, final List<String> strings, final DataNodeContainer parentNode,
533 final DOMMountPoint mountPoint, final boolean returnJustMountPoint) {
534 requireNonNull(strings);
536 if (parentNode == null) {
540 if (strings.isEmpty()) {
541 return createContext(builder.build(), (DataSchemaNode) parentNode, mountPoint,
542 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
545 final String head = strings.iterator().next();
547 if (head.isEmpty()) {
548 final List<String> remaining = strings.subList(1, strings.size());
549 return collectPathArguments(builder, schemaPath, remaining, parentNode, mountPoint, returnJustMountPoint);
552 final String nodeName = toNodeName(head);
553 final String moduleName = toModuleName(head);
555 DataSchemaNode targetNode = null;
556 if (!Strings.isNullOrEmpty(moduleName)) {
557 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
558 if (mountPoint != null) {
559 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
560 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
563 if (mountService == null) {
564 throw new RestconfDocumentedException(
565 "MountService was not found. Finding behind mount points does not work.",
566 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
569 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build()).getKey();
570 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
571 if (mountOpt.isEmpty()) {
572 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
573 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
574 ErrorTag.DATA_MISSING);
576 final DOMMountPoint mount = mountOpt.get();
578 final EffectiveModelContext mountPointSchema = getModelContext(mount);
579 if (mountPointSchema == null) {
580 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
581 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
584 if (returnJustMountPoint || strings.size() == 1) {
585 return InstanceIdentifierContext.ofMountPointRoot(mount, mountPointSchema);
588 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
589 if (moduleNameBehindMountPoint == null) {
590 throw new RestconfDocumentedException(
591 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
592 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
595 final Iterator<? extends Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint)
598 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
599 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
602 final List<String> subList = strings.subList(1, strings.size());
603 return collectPathArguments(YangInstanceIdentifier.builder(), new ArrayDeque<>(), subList, it.next(),
604 mount, returnJustMountPoint);
607 Module module = null;
608 if (mountPoint == null) {
609 checkPreconditions();
610 module = globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
611 if (module == null) {
612 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
613 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
616 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
617 if (schemaContext != null) {
618 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
622 if (module == null) {
623 throw new RestconfDocumentedException("\"" + moduleName
624 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
628 final var found = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
630 if (parentNode instanceof Module) {
631 final RpcDefinition rpc;
632 if (mountPoint == null) {
633 rpc = getRpcDefinition(head, module.getRevision());
635 rpc = getRpcDefinition(module, toNodeName(head));
638 final var ctx = mountPoint == null ? globalSchema : getModelContext(mountPoint);
639 return InstanceIdentifierContext.ofRpcInput(ctx, rpc, mountPoint);
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);
648 targetNode = found.child;
649 schemaPath.addAll(found.intermediate);
650 schemaPath.add(targetNode.getQName());
652 final var potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
653 if (potentialSchemaNodes.size() > 1) {
654 final StringBuilder strBuilder = new StringBuilder();
655 for (var potentialNodeSchema : potentialSchemaNodes) {
656 strBuilder.append(" ").append(potentialNodeSchema.child.getQName().getNamespace()).append("\n");
659 throw new RestconfDocumentedException(
660 "URI has bad format. Node \""
661 + nodeName + "\" is added as augment from more than one module. "
662 + "Therefore the node must have module name "
663 + "and it has to be in format \"moduleName:nodeName\"."
664 + "\nThe node is added as augment from modules with namespaces:\n"
665 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
668 if (potentialSchemaNodes.isEmpty()) {
669 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
670 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
673 final var found = potentialSchemaNodes.get(0);
674 targetNode = found.child;
675 schemaPath.addAll(found.intermediate);
676 schemaPath.add(targetNode.getQName());
679 if (!isListOrContainer(targetNode)) {
680 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
681 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
685 if (targetNode instanceof ListSchemaNode) {
686 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
687 final int keysSize = listNode.getKeyDefinition().size();
688 if (strings.size() - consumed < keysSize) {
689 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
690 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
693 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
694 final HashMap<QName, Object> keyValues = new HashMap<>();
696 for (final QName key : listNode.getKeyDefinition()) {
697 final String uriKeyValue = uriKeyValues.get(index);
698 if (uriKeyValue.equals(NULL_VALUE)) {
699 throw new RestconfDocumentedException("URI has bad format. List \""
700 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
701 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
704 final var keyChild = listNode.getDataChildByName(key);
705 schemaPath.addLast(keyChild.getQName());
706 addKeyValue(keyValues, schemaPath, keyChild, uriKeyValue, mountPoint);
707 schemaPath.removeLast();
711 consumed = consumed + index;
712 builder.nodeWithKey(targetNode.getQName(), keyValues);
714 builder.node(targetNode.getQName());
717 if (targetNode instanceof DataNodeContainer) {
718 final List<String> remaining = strings.subList(consumed, strings.size());
719 return collectPathArguments(builder, schemaPath, remaining, (DataNodeContainer) targetNode, mountPoint,
720 returnJustMountPoint);
723 return createContext(builder.build(), targetNode, mountPoint,
724 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
727 private static InstanceIdentifierContext createContext(final YangInstanceIdentifier instance,
728 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint,
729 final EffectiveModelContext schemaContext) {
730 final var normalized = new DataNormalizer(schemaContext).toNormalized(instance);
731 return InstanceIdentifierContext.ofPath(normalized.getValue(), dataSchemaNode, normalized.getKey(), mountPoint);
734 public static @Nullable FoundChild findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
735 final String name, final XMLNamespace namespace) {
736 requireNonNull(namespace);
738 for (var node : findInstanceDataChildrenByName(container, name)) {
739 if (namespace.equals(node.child.getQName().getNamespace())) {
746 public static List<FoundChild> findInstanceDataChildrenByName(final DataNodeContainer container,
748 final List<FoundChild> instantiatedDataNodeContainers = new ArrayList<>();
749 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
750 requireNonNull(name), List.of());
751 return instantiatedDataNodeContainers;
754 private static void collectInstanceDataNodeContainers(final List<FoundChild> potentialSchemaNodes,
755 final DataNodeContainer container, final String name, final List<QName> intermediate) {
756 // We perform two iterations to retain breadth-first ordering
757 for (var child : container.getChildNodes()) {
758 if (name.equals(child.getQName().getLocalName()) && isInstantiatedDataSchema(child)) {
759 potentialSchemaNodes.add(new FoundChild(child, intermediate));
763 for (var child : container.getChildNodes()) {
764 if (child instanceof ChoiceSchemaNode) {
765 for (var caze : ((ChoiceSchemaNode) child).getCases()) {
766 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name,
767 ImmutableList.<QName>builderWithExpectedSize(intermediate.size() + 2)
768 .addAll(intermediate).add(child.getQName()).add(caze.getQName())
775 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
776 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
777 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
778 || node instanceof AnyxmlSchemaNode;
781 private void addKeyValue(final HashMap<QName, Object> map, final Deque<QName> schemaPath, final DataSchemaNode node,
782 final String uriValue, final DOMMountPoint mountPoint) {
783 checkArgument(node instanceof LeafSchemaNode);
785 final EffectiveModelContext schemaContext = mountPoint == null ? globalSchema : getModelContext(mountPoint);
786 final String urlDecoded = urlPathArgDecode(requireNonNull(uriValue));
787 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
788 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
789 if (baseType instanceof LeafrefTypeDefinition) {
790 final var stack = SchemaInferenceStack.of(schemaContext);
791 schemaPath.forEach(stack::enterSchemaTree);
792 typedef = stack.resolveLeafref((LeafrefTypeDefinition) baseType);
794 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
795 Object decoded = codec.deserialize(urlDecoded);
796 String additionalInfo = "";
797 if (decoded == null) {
798 if (typedef instanceof IdentityrefTypeDefinition) {
799 decoded = toQName(schemaContext, urlDecoded);
801 "For key which is of type identityref it should be in format module_name:identity_name.";
805 if (decoded == null) {
806 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
807 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
810 map.put(node.getQName(), decoded);
813 private static String toModuleName(final String str) {
814 final int idx = str.indexOf(':');
819 // Make sure there is only one occurrence
820 if (str.indexOf(':', idx + 1) != -1) {
824 return str.substring(0, idx);
827 private static String toNodeName(final String str) {
828 final int idx = str.indexOf(':');
833 // Make sure there is only one occurrence
834 if (str.indexOf(':', idx + 1) != -1) {
838 return str.substring(idx + 1);
841 private QName toQName(final EffectiveModelContext schemaContext, final String name,
842 final Optional<Revision> revisionDate) {
843 checkPreconditions();
844 final String module = toModuleName(name);
845 final String node = toNodeName(name);
846 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
847 return m == null ? null : QName.create(m.getQNameModule(), node);
850 private QName toQName(final EffectiveModelContext schemaContext, final String name) {
851 checkPreconditions();
852 final String module = toModuleName(name);
853 final String node = toNodeName(name);
854 final Collection<? extends Module> modules = schemaContext.findModules(module);
855 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
858 private static boolean isListOrContainer(final DataSchemaNode node) {
859 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
862 public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
863 final QName validName = toQName(globalSchema, name, revisionDate);
864 return validName == null ? null : qnameToRpc.get().get(validName);
867 public RpcDefinition getRpcDefinition(final String name) {
868 final QName validName = toQName(globalSchema, name);
869 return validName == null ? null : qnameToRpc.get().get(validName);
872 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
873 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
874 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
875 if (rpcQName.equals(rpcDefinition.getQName())) {
876 return rpcDefinition;
883 public void onModelContextUpdated(final EffectiveModelContext context) {
884 if (context != null) {
885 final Collection<? extends RpcDefinition> defs = context.getOperations();
886 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
888 for (final RpcDefinition operation : defs) {
889 newMap.put(operation.getQName(), operation);
892 // FIXME: still not completely atomic
893 qnameToRpc.set(ImmutableMap.copyOf(newMap));
894 setGlobalSchema(context);
898 private static List<String> urlPathArgsDecode(final Iterable<String> strings) {
899 final List<String> decodedPathArgs = new ArrayList<>();
900 for (final String pathArg : strings) {
901 final String _decode = URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
902 decodedPathArgs.add(_decode);
904 return decodedPathArgs;
907 static String urlPathArgDecode(final String pathArg) {
908 if (pathArg == null) {
911 return URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
914 private String convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
915 final DOMMountPoint mount) {
916 if (argument instanceof NodeIdentifier) {
917 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
918 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
919 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
920 (ListSchemaNode) node, mount);
921 } else if (argument != null && node != null) {
922 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
924 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
928 private String convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
929 return "/" + toRestconfIdentifier(argument.getNodeType(), node);
932 private String convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
933 final ListSchemaNode node, final DOMMountPoint mount) {
934 final QName nodeType = argument.getNodeType();
935 final String nodeIdentifier = toRestconfIdentifier(nodeType, mount);
937 final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
939 final List<QName> keyDefinition = node.getKeyDefinition();
940 boolean hasElements = false;
941 for (final QName key : keyDefinition) {
942 for (final DataSchemaNode listChild : node.getChildNodes()) {
943 if (listChild.getQName().equals(key)) {
950 checkState(listChild instanceof LeafSchemaNode,
951 "List key has to consist of leaves, not %s", listChild);
953 final Object value = argument.getValue(key);
955 builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
956 } catch (final UnsupportedEncodingException e) {
957 LOG.error("Error parsing URI: {}", value, e);
965 return builder.toString();
968 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
969 if (dataNormalizer == null) {
970 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible");
974 return dataNormalizer.toLegacy(instanceIdentifier);
975 } catch (final DataNormalizationException e) {
976 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
980 public boolean isNodeMixin(final YangInstanceIdentifier path) {
981 final DataNormalizationOperation<?> operation;
983 operation = dataNormalizer.getOperation(path);
984 } catch (final DataNormalizationException e) {
985 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
987 return operation.isMixin();
990 private static EffectiveModelContext getModelContext(final DOMMountPoint mountPoint) {
991 return mountPoint.getService(DOMSchemaService.class)
992 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
996 public static final class FoundChild {
997 // Intermediate schema tree children, usually empty
998 public final @NonNull List<QName> intermediate;
999 public final @NonNull DataSchemaNode child;
1001 private FoundChild(final DataSchemaNode child, final List<QName> intermediate) {
1002 this.child = requireNonNull(child);
1003 this.intermediate = requireNonNull(intermediate);