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, globalSchema);
172 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
173 omitFirstAndLastEmptyString(pathArgs);
174 if (pathArgs.isEmpty()) {
178 final String first = pathArgs.iterator().next();
179 final String startModule = toModuleName(first);
180 if (startModule == null) {
181 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
182 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
185 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
186 final Collection<? extends Module> latestModule = globalSchema.findModules(startModule);
188 if (latestModule.isEmpty()) {
189 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
190 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
193 final InstanceIdentifierContext iiWithSchemaNode =
194 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
196 if (iiWithSchemaNode == null) {
197 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
200 return iiWithSchemaNode;
203 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
204 if (list.isEmpty()) {
208 final String head = list.iterator().next();
209 if (head.isEmpty()) {
213 if (list.isEmpty()) {
217 final String last = list.get(list.size() - 1);
218 if (last.isEmpty()) {
219 list.remove(list.size() - 1);
225 public Module findModuleByName(final String moduleName) {
226 checkPreconditions();
227 checkArgument(moduleName != null && !moduleName.isEmpty());
228 return globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
231 public static Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
232 checkArgument(moduleName != null && mountPoint != null);
234 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
235 return mountPointSchema == null ? null
236 : mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
239 public Module findModuleByNamespace(final XMLNamespace namespace) {
240 checkPreconditions();
241 checkArgument(namespace != null);
242 return globalSchema.findModules(namespace).stream().findFirst().orElse(null);
245 public static Module findModuleByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
246 checkArgument(namespace != null && mountPoint != null);
248 final EffectiveModelContext mountPointSchema = getModelContext(mountPoint);
249 return mountPointSchema == null ? null
250 : mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
253 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
254 checkPreconditions();
255 checkArgument(name != null && revision != null);
257 return globalSchema.findModule(name, revision).orElse(null);
260 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
261 final Revision revision) {
262 checkPreconditions();
263 checkArgument(name != null && revision != null && mountPoint != null);
265 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
266 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
269 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
270 checkPreconditions();
272 final Iterable<PathArgument> elements = path.getPathArguments();
273 final PathArgument head = elements.iterator().next();
274 final QName startQName = head.getNodeType();
275 final Module initialModule = globalSchema.findModule(startQName.getModule()).orElse(null);
276 DataNodeContainer node = initialModule;
277 for (final PathArgument element : elements) {
278 final QName _nodeType = element.getNodeType();
279 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
280 if (potentialNode == null || !isListOrContainer(potentialNode)) {
283 node = (DataNodeContainer) potentialNode;
289 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
290 checkPreconditions();
292 final Iterable<PathArgument> elements = path.getPathArguments();
293 final StringBuilder builder = new StringBuilder();
294 final PathArgument head = elements.iterator().next();
295 final QName startQName = head.getNodeType();
296 final EffectiveModelContext schemaContext;
298 schemaContext = getModelContext(mount);
300 schemaContext = globalSchema;
302 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
303 DataNodeContainer node = initialModule;
304 for (final PathArgument element : elements) {
305 if (!(element instanceof AugmentationIdentifier)) {
306 final QName _nodeType = element.getNodeType();
307 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
308 if ((!(element instanceof NodeIdentifier) || !(potentialNode instanceof ListSchemaNode))
309 && !(potentialNode instanceof ChoiceSchemaNode)) {
310 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
311 if (potentialNode instanceof DataNodeContainer) {
312 node = (DataNodeContainer) potentialNode;
318 return builder.toString();
321 public String findModuleNameByNamespace(final XMLNamespace namespace) {
322 checkPreconditions();
324 final Module module = this.findModuleByNamespace(namespace);
325 return module == null ? null : module.getName();
328 public static String findModuleNameByNamespace(final DOMMountPoint mountPoint, final XMLNamespace namespace) {
329 final Module module = findModuleByNamespace(mountPoint, namespace);
330 return module == null ? null : module.getName();
333 public XMLNamespace findNamespaceByModuleName(final String moduleName) {
334 final Module module = this.findModuleByName(moduleName);
335 return module == null ? null : module.getNamespace();
338 public static XMLNamespace findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
339 final Module module = findModuleByName(mountPoint, moduleName);
340 return module == null ? null : module.getNamespace();
343 public Collection<? extends Module> getAllModules(final DOMMountPoint mountPoint) {
344 checkPreconditions();
346 final EffectiveModelContext schemaContext = mountPoint == null ? null : getModelContext(mountPoint);
347 return schemaContext == null ? null : schemaContext.getModules();
350 public Collection<? extends Module> getAllModules() {
351 checkPreconditions();
352 return globalSchema.getModules();
355 private static String toRestconfIdentifier(final EffectiveModelContext context, final QName qname) {
356 final Module schema = context.findModule(qname.getModule()).orElse(null);
357 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
360 public String toRestconfIdentifier(final QName qname, final DOMMountPoint mountPoint) {
361 return mountPoint != null ? toRestconfIdentifier(getModelContext(mountPoint), qname)
362 : toRestconfIdentifier(qname);
365 public String toRestconfIdentifier(final QName qname) {
366 checkPreconditions();
368 return toRestconfIdentifier(globalSchema, qname);
371 public static String toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
372 return mountPoint == null ? null : toRestconfIdentifier(getModelContext(mountPoint), qname);
375 public Module getRestconfModule() {
376 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
379 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
380 final Module restconfModule = getRestconfModule();
381 if (restconfModule == null) {
385 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
387 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
388 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
390 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
392 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
393 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
394 return Iterables.getFirst(instanceDataChildrenByName, null);
397 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
398 final String schemaNodeName) {
399 Module restconfModule = inRestconfModule;
400 if (restconfModule == null) {
401 restconfModule = getRestconfModule();
404 if (restconfModule == null) {
408 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
409 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
410 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
411 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
413 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
414 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
415 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
417 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
418 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
419 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
420 return Iterables.getFirst(instances, null);
421 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
422 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
423 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
424 return Iterables.getFirst(instances, null);
425 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
426 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
427 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
428 final DataSchemaNode modules = Iterables.getFirst(instances, null);
429 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
430 RestConfModule.STREAM_LIST_SCHEMA_NODE);
431 return Iterables.getFirst(instances, null);
432 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
433 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
434 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
435 return Iterables.getFirst(instances, null);
436 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
437 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
438 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
439 final DataSchemaNode modules = Iterables.getFirst(instances, null);
440 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
441 RestConfModule.MODULE_LIST_SCHEMA_NODE);
442 return Iterables.getFirst(instances, null);
443 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
444 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
445 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
446 return Iterables.getFirst(instances, null);
452 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
453 for (final CaseSchemaNode caze : container.getCases()) {
454 final DataSchemaNode ret = childByQName(caze, name);
463 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
464 return container.dataChildByName(name);
467 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
468 return dataNodeChildByQName(container, name);
471 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
472 return dataNodeChildByQName(container, name);
475 private static DataSchemaNode childByQName(final Module container, final QName name) {
476 return dataNodeChildByQName(container, name);
479 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
484 private static DataSchemaNode childByQName(final Object container, final QName name) {
485 if (container instanceof CaseSchemaNode) {
486 return childByQName((CaseSchemaNode) container, name);
487 } else if (container instanceof ChoiceSchemaNode) {
488 return childByQName((ChoiceSchemaNode) container, name);
489 } else if (container instanceof ContainerSchemaNode) {
490 return childByQName((ContainerSchemaNode) container, name);
491 } else if (container instanceof ListSchemaNode) {
492 return childByQName((ListSchemaNode) container, name);
493 } else if (container instanceof DataSchemaNode) {
494 return childByQName((DataSchemaNode) container, name);
495 } else if (container instanceof Module) {
496 return childByQName((Module) container, name);
498 throw new IllegalArgumentException("Unhandled parameter types: "
499 + Arrays.asList(container, name).toString());
503 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
504 final DataSchemaNode ret = container.dataChildByName(name);
506 for (final DataSchemaNode node : container.getChildNodes()) {
507 if (node instanceof ChoiceSchemaNode) {
508 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
509 final DataSchemaNode childByQName = childByQName(choiceNode, name);
510 if (childByQName != null) {
519 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
520 throws UnsupportedEncodingException {
521 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
522 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), StandardCharsets.UTF_8);
525 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
526 private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
527 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
528 final boolean returnJustMountPoint) {
529 requireNonNull(strings);
531 if (parentNode == null) {
535 if (strings.isEmpty()) {
536 return createContext(builder.build(), (DataSchemaNode) parentNode, mountPoint,
537 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
540 final String head = strings.iterator().next();
542 if (head.isEmpty()) {
543 final List<String> remaining = strings.subList(1, strings.size());
544 return collectPathArguments(builder, remaining, parentNode, mountPoint, returnJustMountPoint);
547 final String nodeName = toNodeName(head);
548 final String moduleName = toModuleName(head);
550 DataSchemaNode targetNode = null;
551 if (!Strings.isNullOrEmpty(moduleName)) {
552 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
553 if (mountPoint != null) {
554 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
555 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
558 if (mountService == null) {
559 throw new RestconfDocumentedException(
560 "MountService was not found. Finding behind mount points does not work.",
561 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
564 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
565 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
566 if (mountOpt.isEmpty()) {
567 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
568 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
569 ErrorTag.DATA_MISSING);
571 final DOMMountPoint mount = mountOpt.get();
573 final EffectiveModelContext mountPointSchema = getModelContext(mount);
574 if (mountPointSchema == null) {
575 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
576 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
579 if (returnJustMountPoint || strings.size() == 1) {
580 return new InstanceIdentifierContext(YangInstanceIdentifier.empty(), mountPointSchema, mount,
584 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
585 if (moduleNameBehindMountPoint == null) {
586 throw new RestconfDocumentedException(
587 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
588 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
591 final Iterator<? extends Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint)
594 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
595 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
598 final List<String> subList = strings.subList(1, strings.size());
599 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
600 returnJustMountPoint);
603 Module module = null;
604 if (mountPoint == null) {
605 checkPreconditions();
606 module = globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
607 if (module == null) {
608 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
609 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
612 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
613 if (schemaContext != null) {
614 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
618 if (module == null) {
619 throw new RestconfDocumentedException("\"" + moduleName
620 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
624 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
626 if (targetNode == null && parentNode instanceof Module) {
627 final RpcDefinition rpc;
628 if (mountPoint == null) {
629 rpc = getRpcDefinition(head, module.getRevision());
631 final String rpcName = toNodeName(head);
632 rpc = getRpcDefinition(module, rpcName);
635 return new InstanceIdentifierContext(builder.build(), rpc, mountPoint,
636 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
640 if (targetNode == null) {
641 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
642 + "\" was not found in parent data node.\n" + " 2. \"" + head
643 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
644 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
647 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
648 if (potentialSchemaNodes.size() > 1) {
649 final StringBuilder strBuilder = new StringBuilder();
650 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
651 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
654 throw new RestconfDocumentedException(
655 "URI has bad format. Node \""
656 + nodeName + "\" is added as augment from more than one module. "
657 + "Therefore the node must have module name "
658 + "and it has to be in format \"moduleName:nodeName\"."
659 + "\nThe node is added as augment from modules with namespaces:\n"
660 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
663 if (potentialSchemaNodes.isEmpty()) {
664 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
665 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
668 targetNode = potentialSchemaNodes.iterator().next();
671 if (!isListOrContainer(targetNode)) {
672 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
673 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
677 if (targetNode instanceof ListSchemaNode) {
678 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
679 final int keysSize = listNode.getKeyDefinition().size();
680 if (strings.size() - consumed < keysSize) {
681 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
682 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
685 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
686 final HashMap<QName, Object> keyValues = new HashMap<>();
688 for (final QName key : listNode.getKeyDefinition()) {
690 final String uriKeyValue = uriKeyValues.get(index);
691 if (uriKeyValue.equals(NULL_VALUE)) {
692 throw new RestconfDocumentedException("URI has bad format. List \""
693 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
694 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
697 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
702 consumed = consumed + index;
703 builder.nodeWithKey(targetNode.getQName(), keyValues);
705 builder.node(targetNode.getQName());
708 if (targetNode instanceof DataNodeContainer) {
709 final List<String> remaining = strings.subList(consumed, strings.size());
710 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
711 returnJustMountPoint);
714 return createContext(builder.build(), targetNode, mountPoint,
715 mountPoint != null ? getModelContext(mountPoint) : globalSchema);
718 private static InstanceIdentifierContext createContext(final YangInstanceIdentifier instance,
719 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint,
720 final EffectiveModelContext schemaContext) {
721 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
722 return new InstanceIdentifierContext(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
725 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
726 final String name, final XMLNamespace namespace) {
727 requireNonNull(namespace);
729 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
730 node -> namespace.equals(node.getQName().getNamespace()));
731 return Iterables.getFirst(result, null);
734 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
736 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
737 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
738 requireNonNull(name));
739 return instantiatedDataNodeContainers;
742 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
743 final DataNodeContainer container, final String name) {
745 final Iterable<? extends DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
746 node -> name.equals(node.getQName().getLocalName()));
748 // Can't combine this loop with the filter above because the filter is
749 // lazily-applied by Iterables.filter.
750 for (final DataSchemaNode potentialNode : nodes) {
751 if (isInstantiatedDataSchema(potentialNode)) {
752 potentialSchemaNodes.add(potentialNode);
756 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
757 ChoiceSchemaNode.class);
758 final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
759 ChoiceSchemaNode::getCases);
760 for (final CaseSchemaNode caze : Iterables.concat(map)) {
761 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
765 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
766 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
767 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
768 || node instanceof AnyxmlSchemaNode;
771 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
772 final DOMMountPoint mountPoint) {
773 checkArgument(node instanceof LeafSchemaNode);
775 final EffectiveModelContext schemaContext = mountPoint == null ? globalSchema : getModelContext(mountPoint);
776 final String urlDecoded = urlPathArgDecode(requireNonNull(uriValue));
777 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
778 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
779 if (baseType instanceof LeafrefTypeDefinition) {
780 typedef = SchemaInferenceStack.ofInstantiatedPath(schemaContext, node.getPath())
781 .resolveLeafref((LeafrefTypeDefinition) baseType);
783 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
784 Object decoded = codec.deserialize(urlDecoded);
785 String additionalInfo = "";
786 if (decoded == null) {
787 if (typedef instanceof IdentityrefTypeDefinition) {
788 decoded = toQName(schemaContext, urlDecoded);
790 "For key which is of type identityref it should be in format module_name:identity_name.";
794 if (decoded == null) {
795 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
796 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
799 map.put(node.getQName(), decoded);
802 private static String toModuleName(final String str) {
803 final int idx = str.indexOf(':');
808 // Make sure there is only one occurrence
809 if (str.indexOf(':', idx + 1) != -1) {
813 return str.substring(0, idx);
816 private static String toNodeName(final String str) {
817 final int idx = str.indexOf(':');
822 // Make sure there is only one occurrence
823 if (str.indexOf(':', idx + 1) != -1) {
827 return str.substring(idx + 1);
830 private QName toQName(final EffectiveModelContext schemaContext, final String name,
831 final Optional<Revision> revisionDate) {
832 checkPreconditions();
833 final String module = toModuleName(name);
834 final String node = toNodeName(name);
835 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
836 return m == null ? null : QName.create(m.getQNameModule(), node);
839 private QName toQName(final EffectiveModelContext schemaContext, final String name) {
840 checkPreconditions();
841 final String module = toModuleName(name);
842 final String node = toNodeName(name);
843 final Collection<? extends Module> modules = schemaContext.findModules(module);
844 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
847 private static boolean isListOrContainer(final DataSchemaNode node) {
848 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
851 public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
852 final QName validName = toQName(globalSchema, name, revisionDate);
853 return validName == null ? null : qnameToRpc.get().get(validName);
856 public RpcDefinition getRpcDefinition(final String name) {
857 final QName validName = toQName(globalSchema, name);
858 return validName == null ? null : qnameToRpc.get().get(validName);
861 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
862 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
863 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
864 if (rpcQName.equals(rpcDefinition.getQName())) {
865 return rpcDefinition;
872 public void onModelContextUpdated(final EffectiveModelContext context) {
873 if (context != null) {
874 final Collection<? extends RpcDefinition> defs = context.getOperations();
875 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
877 for (final RpcDefinition operation : defs) {
878 newMap.put(operation.getQName(), operation);
881 // FIXME: still not completely atomic
882 qnameToRpc.set(ImmutableMap.copyOf(newMap));
883 setGlobalSchema(context);
887 private static List<String> urlPathArgsDecode(final Iterable<String> strings) {
888 final List<String> decodedPathArgs = new ArrayList<>();
889 for (final String pathArg : strings) {
890 final String _decode = URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
891 decodedPathArgs.add(_decode);
893 return decodedPathArgs;
896 static String urlPathArgDecode(final String pathArg) {
897 if (pathArg == null) {
900 return URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
903 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
904 final DOMMountPoint mount) {
905 if (argument instanceof NodeIdentifier) {
906 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
907 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
908 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
909 (ListSchemaNode) node, mount);
910 } else if (argument != null && node != null) {
911 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
913 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
917 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
918 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
921 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
922 final ListSchemaNode node, final DOMMountPoint mount) {
923 final QName nodeType = argument.getNodeType();
924 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
926 final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
928 final List<QName> keyDefinition = node.getKeyDefinition();
929 boolean hasElements = false;
930 for (final QName key : keyDefinition) {
931 for (final DataSchemaNode listChild : node.getChildNodes()) {
932 if (listChild.getQName().equals(key)) {
939 checkState(listChild instanceof LeafSchemaNode,
940 "List key has to consist of leaves, not %s", listChild);
942 final Object value = argument.getValue(key);
944 builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
945 } catch (final UnsupportedEncodingException e) {
946 LOG.error("Error parsing URI: {}", value, e);
954 return builder.toString();
957 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
959 return dataNormalizer.toNormalized(legacy);
960 } catch (final NullPointerException e) {
961 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
965 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
967 return dataNormalizer.toLegacy(instanceIdentifier);
968 } catch (final NullPointerException e) {
969 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
970 } catch (final DataNormalizationException e) {
971 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
975 public boolean isNodeMixin(final YangInstanceIdentifier path) {
976 final DataNormalizationOperation<?> operation;
978 operation = dataNormalizer.getOperation(path);
979 } catch (final DataNormalizationException e) {
980 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
982 return operation.isMixin();
985 private static EffectiveModelContext getModelContext(final DOMMountPoint mountPoint) {
986 return mountPoint.getService(DOMSchemaService.class)
987 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))