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.type.IdentityrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 public final class ControllerContext implements EffectiveModelContextListener, Closeable {
83 // FIXME: this should be in md-sal somewhere
84 public static final String MOUNT = "yang-ext:mount";
86 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
88 private static final String NULL_VALUE = "null";
90 private static final String MOUNT_MODULE = "yang-ext";
92 private static final String MOUNT_NODE = "mount";
94 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
96 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
98 private final DOMMountPointService mountService;
99 private final DOMYangTextSourceProvider yangTextSourceProvider;
100 private final ListenerRegistration<?> listenerRegistration;
101 private volatile EffectiveModelContext globalSchema;
102 private volatile DataNormalizer dataNormalizer;
105 public ControllerContext(final DOMSchemaService schemaService, final DOMMountPointService mountService,
106 final DOMSchemaService domSchemaService) {
107 this.mountService = mountService;
108 yangTextSourceProvider = domSchemaService.getExtensions().getInstance(DOMYangTextSourceProvider.class);
110 onModelContextUpdated(schemaService.getGlobalContext());
111 listenerRegistration = schemaService.registerSchemaContextListener(this);
117 * @deprecated Just use the
118 * {@link #ControllerContext(DOMSchemaService, DOMMountPointService, DOMSchemaService)}
119 * constructor instead.
122 public static ControllerContext newInstance(final DOMSchemaService schemaService,
123 final DOMMountPointService mountService, final DOMSchemaService domSchemaService) {
124 return new ControllerContext(schemaService, mountService, domSchemaService);
127 private void setGlobalSchema(final EffectiveModelContext globalSchema) {
128 this.globalSchema = globalSchema;
129 dataNormalizer = new DataNormalizer(globalSchema);
132 public DOMYangTextSourceProvider getYangTextSourceProvider() {
133 return yangTextSourceProvider;
136 private void checkPreconditions() {
137 if (globalSchema == null) {
138 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
144 public void close() {
145 listenerRegistration.close();
148 public void setSchemas(final EffectiveModelContext schemas) {
149 onModelContextUpdated(schemas);
152 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
153 return toIdentifier(restconfInstance, false);
156 public EffectiveModelContext getGlobalSchema() {
160 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
161 return toIdentifier(restconfInstance, true);
164 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
165 final boolean toMountPointIdentifier) {
166 checkPreconditions();
168 if (restconfInstance == null) {
169 return new InstanceIdentifierContext<>(YangInstanceIdentifier.empty(), globalSchema, null,
173 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
174 omitFirstAndLastEmptyString(pathArgs);
175 if (pathArgs.isEmpty()) {
179 final String first = pathArgs.iterator().next();
180 final String startModule = toModuleName(first);
181 if (startModule == null) {
182 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
183 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
186 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
187 final Collection<? extends Module> latestModule = globalSchema.findModules(startModule);
189 if (latestModule.isEmpty()) {
190 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
191 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
194 final InstanceIdentifierContext<?> iiWithSchemaNode =
195 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
197 if (iiWithSchemaNode == null) {
198 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
201 return iiWithSchemaNode;
204 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
205 if (list.isEmpty()) {
209 final String head = list.iterator().next();
210 if (head.isEmpty()) {
214 if (list.isEmpty()) {
218 final String last = list.get(list.size() - 1);
219 if (last.isEmpty()) {
220 list.remove(list.size() - 1);
226 public Module findModuleByName(final String moduleName) {
227 checkPreconditions();
228 checkArgument(moduleName != null && !moduleName.isEmpty());
229 return globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
232 public static Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
233 checkArgument(moduleName != null && mountPoint != null);
235 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
236 return mountPointSchema == null ? null
237 : mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
240 public Module findModuleByNamespace(final XMLNamespace namespace) {
241 checkPreconditions();
242 checkArgument(namespace != null);
243 return globalSchema.findModules(namespace).stream().findFirst().orElse(null);
246 public static Module findModuleByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
247 checkArgument(namespace != null && mountPoint != null);
249 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
250 return mountPointSchema == null ? null
251 : mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
254 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
255 checkPreconditions();
256 checkArgument(name != null && revision != null);
258 return globalSchema.findModule(name, revision).orElse(null);
261 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
262 final Revision revision) {
263 checkPreconditions();
264 checkArgument(name != null && revision != null && mountPoint != null);
266 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
267 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
270 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
271 checkPreconditions();
273 final Iterable<PathArgument> elements = path.getPathArguments();
274 final PathArgument head = elements.iterator().next();
275 final QName startQName = head.getNodeType();
276 final Module initialModule = globalSchema.findModule(startQName.getModule()).orElse(null);
277 DataNodeContainer node = initialModule;
278 for (final PathArgument element : elements) {
279 final QName _nodeType = element.getNodeType();
280 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
281 if (potentialNode == null || !isListOrContainer(potentialNode)) {
284 node = (DataNodeContainer) potentialNode;
290 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
291 checkPreconditions();
293 final Iterable<PathArgument> elements = path.getPathArguments();
294 final StringBuilder builder = new StringBuilder();
295 final PathArgument head = elements.iterator().next();
296 final QName startQName = head.getNodeType();
297 final EffectiveModelContext schemaContext;
299 schemaContext = getModelContext(mount);
301 schemaContext = globalSchema;
303 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
304 DataNodeContainer node = initialModule;
305 for (final PathArgument element : elements) {
306 if (!(element instanceof AugmentationIdentifier)) {
307 final QName _nodeType = element.getNodeType();
308 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
309 if ((!(element instanceof NodeIdentifier) || !(potentialNode instanceof ListSchemaNode))
310 && !(potentialNode instanceof ChoiceSchemaNode)) {
311 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
312 if (potentialNode instanceof DataNodeContainer) {
313 node = (DataNodeContainer) potentialNode;
319 return builder.toString();
322 public String findModuleNameByNamespace(final XMLNamespace namespace) {
323 checkPreconditions();
325 final Module module = this.findModuleByNamespace(namespace);
326 return module == null ? null : module.getName();
329 public static String findModuleNameByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
330 final Module module = findModuleByNamespace(mountPoint, namespace);
331 return module == null ? null : module.getName();
334 public XMLNamespace findNamespaceByModuleName(final String moduleName) {
335 final Module module = this.findModuleByName(moduleName);
336 return module == null ? null : module.getNamespace();
339 public static XMLNamespace findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
340 final Module module = findModuleByName(mountPoint, moduleName);
341 return module == null ? null : module.getNamespace();
344 public Collection<? extends Module> getAllModules(final DOMMountPoint mountPoint) {
345 checkPreconditions();
347 final EffectiveModelContext schemaContext = mountPoint == null ? null : getModelContext(mountPoint);
348 return schemaContext == null ? null : schemaContext.getModules();
351 public Collection<? extends Module> getAllModules() {
352 checkPreconditions();
353 return globalSchema.getModules();
356 private static String toRestconfIdentifier(final EffectiveModelContext context, final QName qname) {
357 final Module schema = context.findModule(qname.getModule()).orElse(null);
358 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
361 public String toRestconfIdentifier(final QName qname, final DOMMountPoint mountPoint) {
362 return mountPoint != null ? toRestconfIdentifier(getModelContext(mountPoint), qname)
363 : toRestconfIdentifier(qname);
366 public String toRestconfIdentifier(final QName qname) {
367 checkPreconditions();
369 return toRestconfIdentifier(globalSchema, qname);
372 public static String toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
373 return mountPoint == null ? null : toRestconfIdentifier(getModelContext(mountPoint), qname);
376 public Module getRestconfModule() {
377 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
380 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
381 final Module restconfModule = getRestconfModule();
382 if (restconfModule == null) {
386 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
388 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
389 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
391 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
393 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
394 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
395 return Iterables.getFirst(instanceDataChildrenByName, null);
398 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
399 final String schemaNodeName) {
400 Module restconfModule = inRestconfModule;
401 if (restconfModule == null) {
402 restconfModule = getRestconfModule();
405 if (restconfModule == null) {
409 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
410 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
411 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
412 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
414 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
415 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
416 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
418 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
419 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
420 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
421 return Iterables.getFirst(instances, null);
422 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
423 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
424 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
425 return Iterables.getFirst(instances, null);
426 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
427 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
428 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
429 final DataSchemaNode modules = Iterables.getFirst(instances, null);
430 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
431 RestConfModule.STREAM_LIST_SCHEMA_NODE);
432 return Iterables.getFirst(instances, null);
433 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
434 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
435 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
436 return Iterables.getFirst(instances, null);
437 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
438 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
439 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
440 final DataSchemaNode modules = Iterables.getFirst(instances, null);
441 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
442 RestConfModule.MODULE_LIST_SCHEMA_NODE);
443 return Iterables.getFirst(instances, null);
444 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
445 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
446 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
453 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
454 for (final CaseSchemaNode caze : container.getCases()) {
455 final DataSchemaNode ret = childByQName(caze, name);
464 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
465 return container.dataChildByName(name);
468 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
469 return dataNodeChildByQName(container, name);
472 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
473 return dataNodeChildByQName(container, name);
476 private static DataSchemaNode childByQName(final Module container, final QName name) {
477 return dataNodeChildByQName(container, name);
480 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
485 private static DataSchemaNode childByQName(final Object container, final QName name) {
486 if (container instanceof CaseSchemaNode) {
487 return childByQName((CaseSchemaNode) container, name);
488 } else if (container instanceof ChoiceSchemaNode) {
489 return childByQName((ChoiceSchemaNode) container, name);
490 } else if (container instanceof ContainerSchemaNode) {
491 return childByQName((ContainerSchemaNode) container, name);
492 } else if (container instanceof ListSchemaNode) {
493 return childByQName((ListSchemaNode) container, name);
494 } else if (container instanceof DataSchemaNode) {
495 return childByQName((DataSchemaNode) container, name);
496 } else if (container instanceof Module) {
497 return childByQName((Module) container, name);
499 throw new IllegalArgumentException("Unhandled parameter types: "
500 + Arrays.asList(container, name).toString());
504 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
505 final DataSchemaNode ret = container.dataChildByName(name);
507 for (final DataSchemaNode node : container.getChildNodes()) {
508 if (node instanceof ChoiceSchemaNode) {
509 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
510 final DataSchemaNode childByQName = childByQName(choiceNode, name);
511 if (childByQName != null) {
520 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
521 throws UnsupportedEncodingException {
522 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
523 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), StandardCharsets.UTF_8);
526 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
527 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
528 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
529 final boolean returnJustMountPoint) {
530 requireNonNull(strings);
532 if (parentNode == null) {
536 if (strings.isEmpty()) {
537 return createContext(builder.build(), (DataSchemaNode) parentNode, mountPoint,
538 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
541 final String head = strings.iterator().next();
543 if (head.isEmpty()) {
544 final List<String> remaining = strings.subList(1, strings.size());
545 return collectPathArguments(builder, remaining, parentNode, mountPoint, returnJustMountPoint);
548 final String nodeName = toNodeName(head);
549 final String moduleName = toModuleName(head);
551 DataSchemaNode targetNode = null;
552 if (!Strings.isNullOrEmpty(moduleName)) {
553 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
554 if (mountPoint != null) {
555 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
556 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
559 if (mountService == null) {
560 throw new RestconfDocumentedException(
561 "MountService was not found. Finding behind mount points does not work.",
562 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
565 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
566 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
567 if (mountOpt.isEmpty()) {
568 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
569 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
570 ErrorTag.DATA_MISSING);
572 final DOMMountPoint mount = mountOpt.get();
574 final EffectiveModelContext mountPointSchema = getModelContext(mount);
575 if (mountPointSchema == null) {
576 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
577 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
580 if (returnJustMountPoint || strings.size() == 1) {
581 return new InstanceIdentifierContext<>(YangInstanceIdentifier.empty(), mountPointSchema, mount,
585 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
586 if (moduleNameBehindMountPoint == null) {
587 throw new RestconfDocumentedException(
588 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
589 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
592 final Iterator<? extends Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint)
595 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
596 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
599 final List<String> subList = strings.subList(1, strings.size());
600 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
601 returnJustMountPoint);
604 Module module = null;
605 if (mountPoint == null) {
606 checkPreconditions();
607 module = globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
608 if (module == null) {
609 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
610 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
613 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
614 if (schemaContext != null) {
615 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
619 if (module == null) {
620 throw new RestconfDocumentedException("\"" + moduleName
621 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
625 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
627 if (targetNode == null && parentNode instanceof Module) {
628 final RpcDefinition rpc;
629 if (mountPoint == null) {
630 rpc = getRpcDefinition(head, module.getRevision());
632 final String rpcName = toNodeName(head);
633 rpc = getRpcDefinition(module, rpcName);
636 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
637 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
641 if (targetNode == null) {
642 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
643 + "\" was not found in parent data node.\n" + " 2. \"" + head
644 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
645 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
648 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
649 if (potentialSchemaNodes.size() > 1) {
650 final StringBuilder strBuilder = new StringBuilder();
651 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
652 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
655 throw new RestconfDocumentedException(
656 "URI has bad format. Node \""
657 + nodeName + "\" is added as augment from more than one module. "
658 + "Therefore the node must have module name "
659 + "and it has to be in format \"moduleName:nodeName\"."
660 + "\nThe node is added as augment from modules with namespaces:\n"
661 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
664 if (potentialSchemaNodes.isEmpty()) {
665 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
666 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
669 targetNode = potentialSchemaNodes.iterator().next();
672 if (!isListOrContainer(targetNode)) {
673 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
674 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
678 if (targetNode instanceof ListSchemaNode) {
679 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
680 final int keysSize = listNode.getKeyDefinition().size();
681 if (strings.size() - consumed < keysSize) {
682 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
683 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
686 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
687 final HashMap<QName, Object> keyValues = new HashMap<>();
689 for (final QName key : listNode.getKeyDefinition()) {
691 final String uriKeyValue = uriKeyValues.get(index);
692 if (uriKeyValue.equals(NULL_VALUE)) {
693 throw new RestconfDocumentedException("URI has bad format. List \""
694 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
695 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
698 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
703 consumed = consumed + index;
704 builder.nodeWithKey(targetNode.getQName(), keyValues);
706 builder.node(targetNode.getQName());
709 if (targetNode instanceof DataNodeContainer) {
710 final List<String> remaining = strings.subList(consumed, strings.size());
711 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
712 returnJustMountPoint);
715 return createContext(builder.build(), targetNode, mountPoint,
716 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
719 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
720 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint,
721 final EffectiveModelContext schemaContext) {
722 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
723 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
726 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
727 final String name, final XMLNamespace namespace) {
728 requireNonNull(namespace);
730 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
731 node -> namespace.equals(node.getQName().getNamespace()));
732 return Iterables.getFirst(result, null);
735 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
737 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
738 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
739 requireNonNull(name));
740 return instantiatedDataNodeContainers;
743 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
744 final DataNodeContainer container, final String name) {
746 final Iterable<? extends DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
747 node -> name.equals(node.getQName().getLocalName()));
749 // Can't combine this loop with the filter above because the filter is
750 // lazily-applied by Iterables.filter.
751 for (final DataSchemaNode potentialNode : nodes) {
752 if (isInstantiatedDataSchema(potentialNode)) {
753 potentialSchemaNodes.add(potentialNode);
757 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
758 ChoiceSchemaNode.class);
759 final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
760 ChoiceSchemaNode::getCases);
761 for (final CaseSchemaNode caze : Iterables.concat(map)) {
762 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
766 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
767 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
768 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
769 || node instanceof AnyxmlSchemaNode;
772 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
773 final DOMMountPoint mountPoint) {
774 checkArgument(node instanceof LeafSchemaNode);
776 final EffectiveModelContext schemaContext = mountPoint == null ? globalSchema : getModelContext(mountPoint);
777 final String urlDecoded = urlPathArgDecode(requireNonNull(uriValue));
778 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
779 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
780 if (baseType instanceof LeafrefTypeDefinition) {
781 typedef = SchemaInferenceStack.ofInstantiatedPath(schemaContext, node.getPath())
782 .resolveLeafref((LeafrefTypeDefinition) baseType);
784 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
785 Object decoded = codec.deserialize(urlDecoded);
786 String additionalInfo = "";
787 if (decoded == null) {
788 if (typedef instanceof IdentityrefTypeDefinition) {
789 decoded = toQName(schemaContext, urlDecoded);
791 "For key which is of type identityref it should be in format module_name:identity_name.";
795 if (decoded == null) {
796 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
797 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
800 map.put(node.getQName(), decoded);
803 private static String toModuleName(final String str) {
804 final int idx = str.indexOf(':');
809 // Make sure there is only one occurrence
810 if (str.indexOf(':', idx + 1) != -1) {
814 return str.substring(0, idx);
817 private static String toNodeName(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(idx + 1);
831 private QName toQName(final EffectiveModelContext schemaContext, final String name,
832 final Optional<Revision> revisionDate) {
833 checkPreconditions();
834 final String module = toModuleName(name);
835 final String node = toNodeName(name);
836 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
837 return m == null ? null : QName.create(m.getQNameModule(), node);
840 private QName toQName(final EffectiveModelContext schemaContext, final String name) {
841 checkPreconditions();
842 final String module = toModuleName(name);
843 final String node = toNodeName(name);
844 final Collection<? extends Module> modules = schemaContext.findModules(module);
845 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
848 private static boolean isListOrContainer(final DataSchemaNode node) {
849 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
852 public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
853 final QName validName = toQName(globalSchema, name, revisionDate);
854 return validName == null ? null : qnameToRpc.get().get(validName);
857 public RpcDefinition getRpcDefinition(final String name) {
858 final QName validName = toQName(globalSchema, name);
859 return validName == null ? null : qnameToRpc.get().get(validName);
862 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
863 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
864 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
865 if (rpcQName.equals(rpcDefinition.getQName())) {
866 return rpcDefinition;
873 public void onModelContextUpdated(final EffectiveModelContext context) {
874 if (context != null) {
875 final Collection<? extends RpcDefinition> defs = context.getOperations();
876 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
878 for (final RpcDefinition operation : defs) {
879 newMap.put(operation.getQName(), operation);
882 // FIXME: still not completely atomic
883 qnameToRpc.set(ImmutableMap.copyOf(newMap));
884 setGlobalSchema(context);
888 private static List<String> urlPathArgsDecode(final Iterable<String> strings) {
889 final List<String> decodedPathArgs = new ArrayList<>();
890 for (final String pathArg : strings) {
891 final String _decode = URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
892 decodedPathArgs.add(_decode);
894 return decodedPathArgs;
897 static String urlPathArgDecode(final String pathArg) {
898 if (pathArg == null) {
901 return URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
904 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
905 final DOMMountPoint mount) {
906 if (argument instanceof NodeIdentifier) {
907 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
908 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
909 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
910 (ListSchemaNode) node, mount);
911 } else if (argument != null && node != null) {
912 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
914 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
918 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
919 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
922 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
923 final ListSchemaNode node, final DOMMountPoint mount) {
924 final QName nodeType = argument.getNodeType();
925 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
927 final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
929 final List<QName> keyDefinition = node.getKeyDefinition();
930 boolean hasElements = false;
931 for (final QName key : keyDefinition) {
932 for (final DataSchemaNode listChild : node.getChildNodes()) {
933 if (listChild.getQName().equals(key)) {
940 checkState(listChild instanceof LeafSchemaNode,
941 "List key has to consist of leaves, not %s", listChild);
943 final Object value = argument.getValue(key);
945 builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
946 } catch (final UnsupportedEncodingException e) {
947 LOG.error("Error parsing URI: {}", value, e);
955 return builder.toString();
958 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
960 return dataNormalizer.toNormalized(legacy);
961 } catch (final NullPointerException e) {
962 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
966 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
968 return dataNormalizer.toLegacy(instanceIdentifier);
969 } catch (final NullPointerException e) {
970 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
971 } catch (final DataNormalizationException e) {
972 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
976 public boolean isNodeMixin(final YangInstanceIdentifier path) {
977 final DataNormalizationOperation<?> operation;
979 operation = dataNormalizer.getOperation(path);
980 } catch (final DataNormalizationException e) {
981 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
983 return operation.isMixin();
986 private static EffectiveModelContext getModelContext(final DOMMountPoint mountPoint) {
987 return mountPoint.getService(DOMSchemaService.class)
988 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))