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 java.util.Objects.requireNonNull;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.Iterables;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.io.Closeable;
20 import java.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.net.URLEncoder;
23 import java.nio.charset.StandardCharsets;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Optional;
33 import java.util.concurrent.atomic.AtomicReference;
34 import javax.annotation.PreDestroy;
35 import javax.inject.Inject;
36 import javax.inject.Singleton;
37 import javax.ws.rs.core.Response.Status;
38 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
39 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
40 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
41 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
42 import org.opendaylight.netconf.sal.rest.api.Draft02;
43 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
44 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
45 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
46 import org.opendaylight.restconf.common.util.RestUtil;
47 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
48 import org.opendaylight.yangtools.concepts.ListenerRegistration;
49 import org.opendaylight.yangtools.yang.common.ErrorTag;
50 import org.opendaylight.yangtools.yang.common.ErrorType;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.Revision;
53 import org.opendaylight.yangtools.yang.common.XMLNamespace;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
60 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
68 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
69 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.Module;
73 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
74 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
76 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
77 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 public final class ControllerContext implements EffectiveModelContextListener, Closeable {
85 // FIXME: this should be in md-sal somewhere
86 public static final String MOUNT = "yang-ext:mount";
88 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
90 private static final String NULL_VALUE = "null";
92 private static final String MOUNT_MODULE = "yang-ext";
94 private static final String MOUNT_NODE = "mount";
96 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
98 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
100 private final DOMMountPointService mountService;
101 private final DOMYangTextSourceProvider yangTextSourceProvider;
102 private final ListenerRegistration<?> listenerRegistration;
103 private volatile EffectiveModelContext globalSchema;
104 private volatile DataNormalizer dataNormalizer;
107 public ControllerContext(final DOMSchemaService schemaService, final DOMMountPointService mountService,
108 final DOMSchemaService domSchemaService) {
109 this.mountService = mountService;
110 yangTextSourceProvider = domSchemaService.getExtensions().getInstance(DOMYangTextSourceProvider.class);
112 onModelContextUpdated(schemaService.getGlobalContext());
113 listenerRegistration = schemaService.registerSchemaContextListener(this);
119 * @deprecated Just use the
120 * {@link #ControllerContext(DOMSchemaService, DOMMountPointService, DOMSchemaService)}
121 * constructor instead.
124 public static ControllerContext newInstance(final DOMSchemaService schemaService,
125 final DOMMountPointService mountService, final DOMSchemaService domSchemaService) {
126 return new ControllerContext(schemaService, mountService, domSchemaService);
129 private void setGlobalSchema(final EffectiveModelContext globalSchema) {
130 this.globalSchema = globalSchema;
131 dataNormalizer = new DataNormalizer(globalSchema);
134 public DOMYangTextSourceProvider getYangTextSourceProvider() {
135 return yangTextSourceProvider;
138 private void checkPreconditions() {
139 if (globalSchema == null) {
140 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
146 public void close() {
147 listenerRegistration.close();
150 public void setSchemas(final EffectiveModelContext schemas) {
151 onModelContextUpdated(schemas);
154 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
155 return toIdentifier(restconfInstance, false);
158 public EffectiveModelContext getGlobalSchema() {
162 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
163 return toIdentifier(restconfInstance, true);
166 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
167 final boolean toMountPointIdentifier) {
168 checkPreconditions();
170 if (restconfInstance == null) {
171 return new InstanceIdentifierContext<>(YangInstanceIdentifier.empty(), null, globalSchema, null,
175 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
176 omitFirstAndLastEmptyString(pathArgs);
177 if (pathArgs.isEmpty()) {
181 final String first = pathArgs.iterator().next();
182 final String startModule = toModuleName(first);
183 if (startModule == null) {
184 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
185 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
188 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
189 final Collection<? extends Module> latestModule = globalSchema.findModules(startModule);
191 if (latestModule.isEmpty()) {
192 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
193 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
196 final InstanceIdentifierContext<?> iiWithSchemaNode =
197 collectPathArguments(builder, pathArgs, new ArrayList<>(), latestModule.iterator().next(), null,
198 toMountPointIdentifier);
200 if (iiWithSchemaNode == null) {
201 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
204 return iiWithSchemaNode;
207 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
208 if (list.isEmpty()) {
212 final String head = list.iterator().next();
213 if (head.isEmpty()) {
217 if (list.isEmpty()) {
221 final String last = list.get(list.size() - 1);
222 if (last.isEmpty()) {
223 list.remove(list.size() - 1);
229 public Module findModuleByName(final String moduleName) {
230 checkPreconditions();
231 checkArgument(moduleName != null && !moduleName.isEmpty());
232 return globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
235 public static Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
236 checkArgument(moduleName != null && mountPoint != null);
238 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
239 return mountPointSchema == null ? null
240 : mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
243 public Module findModuleByNamespace(final XMLNamespace namespace) {
244 checkPreconditions();
245 checkArgument(namespace != null);
246 return globalSchema.findModules(namespace).stream().findFirst().orElse(null);
249 public static Module findModuleByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
250 checkArgument(namespace != null && mountPoint != null);
252 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
253 return mountPointSchema == null ? null
254 : mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
257 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
258 checkPreconditions();
259 checkArgument(name != null && revision != null);
261 return globalSchema.findModule(name, revision).orElse(null);
264 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
265 final Revision revision) {
266 checkPreconditions();
267 checkArgument(name != null && revision != null && mountPoint != null);
269 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
270 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
273 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
274 checkPreconditions();
276 final Iterable<PathArgument> elements = path.getPathArguments();
277 final PathArgument head = elements.iterator().next();
278 final QName startQName = head.getNodeType();
279 final Module initialModule = globalSchema.findModule(startQName.getModule()).orElse(null);
280 DataNodeContainer node = initialModule;
281 for (final PathArgument element : elements) {
282 final QName _nodeType = element.getNodeType();
283 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
284 if (potentialNode == null || !isListOrContainer(potentialNode)) {
287 node = (DataNodeContainer) potentialNode;
293 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
294 checkPreconditions();
296 final Iterable<PathArgument> elements = path.getPathArguments();
297 final StringBuilder builder = new StringBuilder();
298 final PathArgument head = elements.iterator().next();
299 final QName startQName = head.getNodeType();
300 final EffectiveModelContext schemaContext;
302 schemaContext = getModelContext(mount);
304 schemaContext = globalSchema;
306 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
307 DataNodeContainer node = initialModule;
308 for (final PathArgument element : elements) {
309 if (!(element instanceof AugmentationIdentifier)) {
310 final QName _nodeType = element.getNodeType();
311 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
312 if ((!(element instanceof NodeIdentifier) || !(potentialNode instanceof ListSchemaNode))
313 && !(potentialNode instanceof ChoiceSchemaNode)) {
314 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
315 if (potentialNode instanceof DataNodeContainer) {
316 node = (DataNodeContainer) potentialNode;
322 return builder.toString();
325 public String findModuleNameByNamespace(final XMLNamespace namespace) {
326 checkPreconditions();
328 final Module module = this.findModuleByNamespace(namespace);
329 return module == null ? null : module.getName();
332 public static String findModuleNameByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
333 final Module module = findModuleByNamespace(mountPoint, namespace);
334 return module == null ? null : module.getName();
337 public XMLNamespace findNamespaceByModuleName(final String moduleName) {
338 final Module module = this.findModuleByName(moduleName);
339 return module == null ? null : module.getNamespace();
342 public static XMLNamespace findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
343 final Module module = findModuleByName(mountPoint, moduleName);
344 return module == null ? null : module.getNamespace();
347 public Collection<? extends Module> getAllModules(final DOMMountPoint mountPoint) {
348 checkPreconditions();
350 final EffectiveModelContext schemaContext = mountPoint == null ? null : getModelContext(mountPoint);
351 return schemaContext == null ? null : schemaContext.getModules();
354 public Collection<? extends Module> getAllModules() {
355 checkPreconditions();
356 return globalSchema.getModules();
359 private static String toRestconfIdentifier(final EffectiveModelContext context, final QName qname) {
360 final Module schema = context.findModule(qname.getModule()).orElse(null);
361 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
364 public String toRestconfIdentifier(final QName qname, final DOMMountPoint mountPoint) {
365 return mountPoint != null ? toRestconfIdentifier(getModelContext(mountPoint), qname)
366 : toRestconfIdentifier(qname);
369 public String toRestconfIdentifier(final QName qname) {
370 checkPreconditions();
372 return toRestconfIdentifier(globalSchema, qname);
375 public static String toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
376 return mountPoint == null ? null : toRestconfIdentifier(getModelContext(mountPoint), qname);
379 public Module getRestconfModule() {
380 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
383 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
384 final Module restconfModule = getRestconfModule();
385 if (restconfModule == null) {
389 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
391 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
392 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
394 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
396 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
397 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
398 return Iterables.getFirst(instanceDataChildrenByName, null);
401 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
402 final String schemaNodeName) {
403 Module restconfModule = inRestconfModule;
404 if (restconfModule == null) {
405 restconfModule = getRestconfModule();
408 if (restconfModule == null) {
412 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
413 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
414 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
415 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
417 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
418 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
419 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
421 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
422 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
423 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
424 return Iterables.getFirst(instances, null);
425 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
426 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
427 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
428 return Iterables.getFirst(instances, null);
429 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
430 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
431 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
432 final DataSchemaNode modules = Iterables.getFirst(instances, null);
433 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
434 RestConfModule.STREAM_LIST_SCHEMA_NODE);
435 return Iterables.getFirst(instances, null);
436 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
437 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
438 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
439 return Iterables.getFirst(instances, null);
440 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
441 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
442 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
443 final DataSchemaNode modules = Iterables.getFirst(instances, null);
444 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
445 RestConfModule.MODULE_LIST_SCHEMA_NODE);
446 return Iterables.getFirst(instances, null);
447 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
448 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
449 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
450 return Iterables.getFirst(instances, null);
456 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
457 for (final CaseSchemaNode caze : container.getCases()) {
458 final DataSchemaNode ret = childByQName(caze, name);
467 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
468 return container.dataChildByName(name);
471 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
472 return dataNodeChildByQName(container, name);
475 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
476 return dataNodeChildByQName(container, name);
479 private static DataSchemaNode childByQName(final Module container, final QName name) {
480 return dataNodeChildByQName(container, name);
483 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
488 private static DataSchemaNode childByQName(final Object container, final QName name) {
489 if (container instanceof CaseSchemaNode) {
490 return childByQName((CaseSchemaNode) container, name);
491 } else if (container instanceof ChoiceSchemaNode) {
492 return childByQName((ChoiceSchemaNode) container, name);
493 } else if (container instanceof ContainerSchemaNode) {
494 return childByQName((ContainerSchemaNode) container, name);
495 } else if (container instanceof ListSchemaNode) {
496 return childByQName((ListSchemaNode) container, name);
497 } else if (container instanceof DataSchemaNode) {
498 return childByQName((DataSchemaNode) container, name);
499 } else if (container instanceof Module) {
500 return childByQName((Module) container, name);
502 throw new IllegalArgumentException("Unhandled parameter types: "
503 + Arrays.asList(container, name).toString());
507 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
508 final DataSchemaNode ret = container.dataChildByName(name);
510 for (final DataSchemaNode node : container.getChildNodes()) {
511 if (node instanceof ChoiceSchemaNode) {
512 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
513 final DataSchemaNode childByQName = childByQName(choiceNode, name);
514 if (childByQName != null) {
523 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
524 throws UnsupportedEncodingException {
525 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
526 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), StandardCharsets.UTF_8);
529 private SchemaNodeIdentifier schemaNodeIdentifierFromPath(final List<QName> qnames) {
530 return qnames.isEmpty() ? null : Absolute.of(qnames);
533 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
534 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
535 final List<String> strings, final List<QName> qnames, final DataNodeContainer parentNode,
536 final DOMMountPoint mountPoint, final boolean returnJustMountPoint) {
537 requireNonNull(strings);
539 if (parentNode == null) {
543 final EffectiveModelContext modelContext = mountPoint != null ? getModelContext(mountPoint) : globalSchema;
545 if (strings.isEmpty()) {
546 return createContext(builder.build(), schemaNodeIdentifierFromPath(qnames), (DataSchemaNode) parentNode,
547 mountPoint, modelContext);
550 final String head = strings.iterator().next();
552 if (head.isEmpty()) {
553 final List<String> remaining = strings.subList(1, strings.size());
554 return collectPathArguments(builder, remaining, qnames, parentNode, mountPoint, returnJustMountPoint);
557 final String nodeName = toNodeName(head);
558 final String moduleName = toModuleName(head);
560 DataSchemaNode targetNode = null;
561 if (!Strings.isNullOrEmpty(moduleName)) {
562 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
563 if (mountPoint != null) {
564 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
565 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
568 if (mountService == null) {
569 throw new RestconfDocumentedException(
570 "MountService was not found. Finding behind mount points does not work.",
571 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
574 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
575 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
576 if (mountOpt.isEmpty()) {
577 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
578 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
579 ErrorTag.DATA_MISSING);
581 final DOMMountPoint mount = mountOpt.get();
583 final EffectiveModelContext mountPointSchema = getModelContext(mount);
584 if (mountPointSchema == null) {
585 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
586 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
589 if (returnJustMountPoint || strings.size() == 1) {
590 return new InstanceIdentifierContext<>(YangInstanceIdentifier.empty(), null,
591 mountPointSchema, mount,
595 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
596 if (moduleNameBehindMountPoint == null) {
597 throw new RestconfDocumentedException(
598 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
599 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
602 final Iterator<? extends Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint)
605 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
606 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
609 final List<String> subList = strings.subList(1, strings.size());
610 return collectPathArguments(YangInstanceIdentifier.builder(), subList, new ArrayList<>(), it.next(),
611 mount, returnJustMountPoint);
614 Module module = null;
615 if (mountPoint == null) {
616 checkPreconditions();
617 module = globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
618 if (module == null) {
619 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
620 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
623 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
624 if (schemaContext != null) {
625 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
629 if (module == null) {
630 throw new RestconfDocumentedException("\"" + moduleName
631 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
635 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
637 if (targetNode == null && parentNode instanceof Module) {
638 final RpcDefinition rpc;
639 if (mountPoint == null) {
640 rpc = getRpcDefinition(head, module.getRevision());
642 final String rpcName = toNodeName(head);
643 rpc = getRpcDefinition(module, rpcName);
646 return new InstanceIdentifierContext<>(builder.build(), null, rpc, mountPoint, modelContext);
650 if (targetNode == null) {
651 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
652 + "\" was not found in parent data node.\n" + " 2. \"" + head
653 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
654 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
657 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
658 if (potentialSchemaNodes.size() > 1) {
659 final StringBuilder strBuilder = new StringBuilder();
660 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
661 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
664 throw new RestconfDocumentedException(
665 "URI has bad format. Node \""
666 + nodeName + "\" is added as augment from more than one module. "
667 + "Therefore the node must have module name "
668 + "and it has to be in format \"moduleName:nodeName\"."
669 + "\nThe node is added as augment from modules with namespaces:\n"
670 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
673 if (potentialSchemaNodes.isEmpty()) {
674 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
675 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
678 targetNode = potentialSchemaNodes.iterator().next();
681 if (!isListOrContainer(targetNode)) {
682 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
683 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
687 if (targetNode instanceof ListSchemaNode) {
688 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
689 final int keysSize = listNode.getKeyDefinition().size();
690 if (strings.size() - consumed < keysSize) {
691 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
692 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
695 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
696 final HashMap<QName, Object> keyValues = new HashMap<>();
698 for (final QName key : listNode.getKeyDefinition()) {
700 final String uriKeyValue = uriKeyValues.get(index);
701 if (uriKeyValue.equals(NULL_VALUE)) {
702 throw new RestconfDocumentedException("URI has bad format. List \""
703 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
704 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
707 final SchemaInferenceStack stack = SchemaInferenceStack.of(modelContext);
708 final YangInstanceIdentifier identifier = builder.build();
709 identifier.getPathArguments().forEach(p -> stack.enterSchemaTree(p.getNodeType()));
710 stack.enterSchemaTree(targetNode.getQName());
711 stack.enterSchemaTree(key);
712 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint, stack);
717 consumed = consumed + index;
718 builder.nodeWithKey(targetNode.getQName(), keyValues);
720 builder.node(targetNode.getQName());
723 qnames.add(targetNode.getQName());
725 if (targetNode instanceof DataNodeContainer) {
726 final List<String> remaining = strings.subList(consumed, strings.size());
727 return collectPathArguments(builder, remaining, qnames, (DataNodeContainer) targetNode, mountPoint,
728 returnJustMountPoint);
731 return createContext(builder.build(), Absolute.of(qnames), targetNode, mountPoint, modelContext);
734 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
735 final SchemaNodeIdentifier schemaNodeIdentifier, final DataSchemaNode dataSchemaNode,
736 final DOMMountPoint mountPoint, final EffectiveModelContext schemaContext) {
737 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
738 return new InstanceIdentifierContext<>(instanceIdentifier, schemaNodeIdentifier, dataSchemaNode, mountPoint,
742 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
743 final String name, final XMLNamespace namespace) {
744 requireNonNull(namespace);
746 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
747 node -> namespace.equals(node.getQName().getNamespace()));
748 return Iterables.getFirst(result, null);
751 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
753 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
754 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
755 requireNonNull(name));
756 return instantiatedDataNodeContainers;
759 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
760 final DataNodeContainer container, final String name) {
762 final Iterable<? extends DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
763 node -> name.equals(node.getQName().getLocalName()));
765 // Can't combine this loop with the filter above because the filter is
766 // lazily-applied by Iterables.filter.
767 for (final DataSchemaNode potentialNode : nodes) {
768 if (isInstantiatedDataSchema(potentialNode)) {
769 potentialSchemaNodes.add(potentialNode);
773 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
774 ChoiceSchemaNode.class);
775 final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
776 ChoiceSchemaNode::getCases);
777 for (final CaseSchemaNode caze : Iterables.concat(map)) {
778 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
782 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
783 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
784 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
785 || node instanceof AnyxmlSchemaNode;
788 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
789 final DOMMountPoint mountPoint, final SchemaInferenceStack stack) {
790 checkArgument(node instanceof LeafSchemaNode);
792 final String urlDecoded = urlPathArgDecode(requireNonNull(uriValue));
793 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
794 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
795 if (baseType instanceof LeafrefTypeDefinition) {
796 typedef = stack.resolveLeafref((LeafrefTypeDefinition) baseType);
798 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
799 Object decoded = codec.deserialize(urlDecoded);
800 String additionalInfo = "";
801 if (decoded == null) {
802 if (typedef instanceof IdentityrefTypeDefinition) {
803 decoded = toQName(stack.getEffectiveModelContext(), urlDecoded);
805 "For key which is of type identityref it should be in format module_name:identity_name.";
809 if (decoded == null) {
810 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
811 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
814 map.put(node.getQName(), decoded);
817 private static String toModuleName(final String str) {
818 final int idx = str.indexOf(':');
823 // Make sure there is only one occurrence
824 if (str.indexOf(':', idx + 1) != -1) {
828 return str.substring(0, idx);
831 private static String toNodeName(final String str) {
832 final int idx = str.indexOf(':');
837 // Make sure there is only one occurrence
838 if (str.indexOf(':', idx + 1) != -1) {
842 return str.substring(idx + 1);
845 private QName toQName(final EffectiveModelContext schemaContext, final String name,
846 final Optional<Revision> revisionDate) {
847 checkPreconditions();
848 final String module = toModuleName(name);
849 final String node = toNodeName(name);
850 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
851 return m == null ? null : QName.create(m.getQNameModule(), node);
854 private QName toQName(final EffectiveModelContext schemaContext, final String name) {
855 checkPreconditions();
856 final String module = toModuleName(name);
857 final String node = toNodeName(name);
858 final Collection<? extends Module> modules = schemaContext.findModules(module);
859 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
862 private static boolean isListOrContainer(final DataSchemaNode node) {
863 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
866 public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
867 final QName validName = toQName(globalSchema, name, revisionDate);
868 return validName == null ? null : qnameToRpc.get().get(validName);
871 public RpcDefinition getRpcDefinition(final String name) {
872 final QName validName = toQName(globalSchema, name);
873 return validName == null ? null : qnameToRpc.get().get(validName);
876 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
877 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
878 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
879 if (rpcQName.equals(rpcDefinition.getQName())) {
880 return rpcDefinition;
887 public void onModelContextUpdated(final EffectiveModelContext context) {
888 if (context != null) {
889 final Collection<? extends RpcDefinition> defs = context.getOperations();
890 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
892 for (final RpcDefinition operation : defs) {
893 newMap.put(operation.getQName(), operation);
896 // FIXME: still not completely atomic
897 qnameToRpc.set(ImmutableMap.copyOf(newMap));
898 setGlobalSchema(context);
902 private static List<String> urlPathArgsDecode(final Iterable<String> strings) {
903 final List<String> decodedPathArgs = new ArrayList<>();
904 for (final String pathArg : strings) {
905 final String _decode = URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
906 decodedPathArgs.add(_decode);
908 return decodedPathArgs;
911 static String urlPathArgDecode(final String pathArg) {
912 if (pathArg == null) {
915 return URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
918 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
919 final DOMMountPoint mount) {
920 if (argument instanceof NodeIdentifier) {
921 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
922 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
923 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
924 (ListSchemaNode) node, mount);
925 } else if (argument != null && node != null) {
926 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
928 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
932 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
933 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
936 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
937 final ListSchemaNode node, final DOMMountPoint mount) {
938 final QName nodeType = argument.getNodeType();
939 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
941 final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
943 final List<QName> keyDefinition = node.getKeyDefinition();
944 boolean hasElements = false;
945 for (final QName key : keyDefinition) {
946 for (final DataSchemaNode listChild : node.getChildNodes()) {
947 if (listChild.getQName().equals(key)) {
954 checkState(listChild instanceof LeafSchemaNode,
955 "List key has to consist of leaves, not %s", listChild);
957 final Object value = argument.getValue(key);
959 builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
960 } catch (final UnsupportedEncodingException e) {
961 LOG.error("Error parsing URI: {}", value, e);
969 return builder.toString();
972 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
974 return dataNormalizer.toNormalized(legacy);
975 } catch (final NullPointerException e) {
976 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
980 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
982 return 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);
990 public boolean isNodeMixin(final YangInstanceIdentifier path) {
991 final DataNormalizationOperation<?> operation;
993 operation = dataNormalizer.getOperation(path);
994 } catch (final DataNormalizationException e) {
995 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
997 return operation.isMixin();
1000 private static EffectiveModelContext getModelContext(final DOMMountPoint mountPoint) {
1001 return mountPoint.getService(DOMSchemaService.class)
1002 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))