2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Splitter;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.Iterables;
16 import java.io.UnsupportedEncodingException;
18 import java.net.URLDecoder;
19 import java.net.URLEncoder;
20 import java.nio.charset.Charset;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
31 import java.util.concurrent.atomic.AtomicReference;
32 import javax.ws.rs.core.Response.Status;
33 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
34 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
36 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
38 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
39 import org.opendaylight.netconf.sal.rest.api.Draft02;
40 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
41 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
42 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
43 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
44 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
45 import org.opendaylight.restconf.common.util.RestUtil;
46 import org.opendaylight.yangtools.concepts.Codec;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.Revision;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
69 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
76 public class ControllerContext implements SchemaContextListener {
77 // FIXME: this should be in md-sal somewhere
78 public static final String MOUNT = "yang-ext:mount";
80 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
82 // FIXME: this should be the current instance which is mutated
83 private static final ControllerContext INSTANCE = new ControllerContext();
85 private static final String NULL_VALUE = "null";
87 private static final String MOUNT_MODULE = "yang-ext";
89 private static final String MOUNT_NODE = "mount";
91 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
93 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
95 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
97 // FIXME; these three should be final
98 private volatile SchemaContext globalSchema;
99 private volatile DOMMountPointService mountService;
100 private volatile DOMYangTextSourceProvider yangTextSourceProvider;
101 private DataNormalizer dataNormalizer;
104 public void setGlobalSchema(final SchemaContext globalSchema) {
105 this.globalSchema = globalSchema;
106 this.dataNormalizer = new DataNormalizer(globalSchema);
109 public void setMountService(final DOMMountPointService mountService) {
110 this.mountService = mountService;
113 public DOMYangTextSourceProvider getYangTextSourceProvider() {
114 return yangTextSourceProvider;
117 public void setYangTextSourceProvider(DOMYangTextSourceProvider yangTextSourceProvider) {
118 this.yangTextSourceProvider = yangTextSourceProvider;
121 ControllerContext() {
125 public static ControllerContext getInstance() {
129 private void checkPreconditions() {
130 if (this.globalSchema == null) {
131 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
135 public void setSchemas(final SchemaContext schemas) {
136 onGlobalContextUpdated(schemas);
139 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
140 return toIdentifier(restconfInstance, false);
143 public SchemaContext getGlobalSchema() {
144 return this.globalSchema;
147 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
148 return toIdentifier(restconfInstance, true);
151 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
152 final boolean toMountPointIdentifier) {
153 checkPreconditions();
155 if (restconfInstance == null) {
156 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
160 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
161 omitFirstAndLastEmptyString(pathArgs);
162 if (pathArgs.isEmpty()) {
166 final String first = pathArgs.iterator().next();
167 final String startModule = toModuleName(first);
168 if (startModule == null) {
169 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
170 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
173 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
174 final Set<Module> latestModule = this.globalSchema.findModules(startModule);
176 if (latestModule.isEmpty()) {
177 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
178 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
181 final InstanceIdentifierContext<?> iiWithSchemaNode =
182 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
184 if (iiWithSchemaNode == null) {
185 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
188 return iiWithSchemaNode;
191 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
192 if (list.isEmpty()) {
196 final String head = list.iterator().next();
197 if (head.isEmpty()) {
201 if (list.isEmpty()) {
205 final String last = list.get(list.size() - 1);
206 if (last.isEmpty()) {
207 list.remove(list.size() - 1);
213 public Module findModuleByName(final String moduleName) {
214 checkPreconditions();
215 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
216 return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
219 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
220 Preconditions.checkArgument(moduleName != null && mountPoint != null);
222 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
223 if (mountPointSchema == null) {
227 return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
230 public Module findModuleByNamespace(final URI namespace) {
231 checkPreconditions();
232 Preconditions.checkArgument(namespace != null);
233 return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
236 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
237 Preconditions.checkArgument(namespace != null && mountPoint != null);
239 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
240 if (mountPointSchema == null) {
244 return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
247 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
248 checkPreconditions();
249 Preconditions.checkArgument(name != null && revision != null);
251 return this.globalSchema.findModule(name, revision).orElse(null);
254 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
255 final Revision revision) {
256 checkPreconditions();
257 Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
259 final SchemaContext schemaContext = mountPoint.getSchemaContext();
260 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
263 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
264 checkPreconditions();
266 final Iterable<PathArgument> elements = path.getPathArguments();
267 final PathArgument head = elements.iterator().next();
268 final QName startQName = head.getNodeType();
269 final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
270 DataNodeContainer node = initialModule;
271 for (final PathArgument element : elements) {
272 final QName _nodeType = element.getNodeType();
273 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
274 if (potentialNode == null || !isListOrContainer(potentialNode)) {
277 node = (DataNodeContainer) potentialNode;
283 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
284 checkPreconditions();
286 final Iterable<PathArgument> elements = path.getPathArguments();
287 final StringBuilder builder = new StringBuilder();
288 final PathArgument head = elements.iterator().next();
289 final QName startQName = head.getNodeType();
290 final SchemaContext schemaContext;
292 schemaContext = mount.getSchemaContext();
294 schemaContext = this.globalSchema;
296 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
297 DataNodeContainer node = initialModule;
298 for (final PathArgument element : elements) {
299 if (!(element instanceof AugmentationIdentifier)) {
300 final QName _nodeType = element.getNodeType();
301 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
302 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)
303 && !(potentialNode instanceof ChoiceSchemaNode)) {
304 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
305 if (potentialNode instanceof DataNodeContainer) {
306 node = (DataNodeContainer) potentialNode;
312 return builder.toString();
315 public String findModuleNameByNamespace(final URI namespace) {
316 checkPreconditions();
318 final Module module = this.findModuleByNamespace(namespace);
319 return module == null ? null : module.getName();
322 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
323 final Module module = this.findModuleByNamespace(mountPoint, namespace);
324 return module == null ? null : module.getName();
327 public URI findNamespaceByModuleName(final String moduleName) {
328 final Module module = this.findModuleByName(moduleName);
329 return module == null ? null : module.getNamespace();
332 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
333 final Module module = this.findModuleByName(mountPoint, moduleName);
334 return module == null ? null : module.getNamespace();
337 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
338 checkPreconditions();
340 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
341 return schemaContext == null ? null : schemaContext.getModules();
344 public Set<Module> getAllModules() {
345 checkPreconditions();
346 return this.globalSchema.getModules();
349 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
350 final Module schema = context.findModule(qname.getModule()).orElse(null);
351 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
354 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
355 final SchemaContext schema;
357 schema = mount.getSchemaContext();
359 checkPreconditions();
360 schema = this.globalSchema;
363 return toRestconfIdentifier(schema, qname);
366 public CharSequence toRestconfIdentifier(final QName qname) {
367 checkPreconditions();
369 return toRestconfIdentifier(this.globalSchema, qname);
372 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
373 if (mountPoint == null) {
377 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
380 public Module getRestconfModule() {
381 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
384 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
385 final Module restconfModule = getRestconfModule();
386 if (restconfModule == null) {
390 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
392 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
393 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
395 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
397 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
398 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
399 return Iterables.getFirst(instanceDataChildrenByName, null);
402 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
403 final String schemaNodeName) {
404 Module restconfModule = inRestconfModule;
405 if (restconfModule == null) {
406 restconfModule = getRestconfModule();
409 if (restconfModule == null) {
413 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
414 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
415 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
416 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
418 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
419 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
420 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
422 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
423 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
424 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
425 return Iterables.getFirst(instances, null);
426 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
427 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
428 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
429 return Iterables.getFirst(instances, null);
430 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
431 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
432 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
433 final DataSchemaNode modules = Iterables.getFirst(instances, null);
434 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
435 RestConfModule.STREAM_LIST_SCHEMA_NODE);
436 return Iterables.getFirst(instances, null);
437 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
438 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
439 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
440 return Iterables.getFirst(instances, null);
441 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
442 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
443 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
444 final DataSchemaNode modules = Iterables.getFirst(instances, null);
445 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
446 RestConfModule.MODULE_LIST_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
448 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
449 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
450 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
451 return Iterables.getFirst(instances, null);
457 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
458 for (final CaseSchemaNode caze : container.getCases().values()) {
459 final DataSchemaNode ret = childByQName(caze, name);
468 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
469 return container.getDataChildByName(name);
472 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
473 return dataNodeChildByQName(container, name);
476 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
477 return dataNodeChildByQName(container, name);
480 private static DataSchemaNode childByQName(final Module container, final QName name) {
481 return dataNodeChildByQName(container, name);
484 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
489 private static DataSchemaNode childByQName(final Object container, final QName name) {
490 if (container instanceof CaseSchemaNode) {
491 return childByQName((CaseSchemaNode) container, name);
492 } else if (container instanceof ChoiceSchemaNode) {
493 return childByQName((ChoiceSchemaNode) container, name);
494 } else if (container instanceof ContainerSchemaNode) {
495 return childByQName((ContainerSchemaNode) container, name);
496 } else if (container instanceof ListSchemaNode) {
497 return childByQName((ListSchemaNode) container, name);
498 } else if (container instanceof DataSchemaNode) {
499 return childByQName((DataSchemaNode) container, name);
500 } else if (container instanceof Module) {
501 return childByQName((Module) container, name);
503 throw new IllegalArgumentException("Unhandled parameter types: "
504 + Arrays.<Object>asList(container, name).toString());
508 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
509 final DataSchemaNode ret = container.getDataChildByName(name);
511 for (final DataSchemaNode node : container.getChildNodes()) {
512 if (node instanceof ChoiceSchemaNode) {
513 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
514 final DataSchemaNode childByQName = childByQName(choiceNode, name);
515 if (childByQName != null) {
524 private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
525 throws UnsupportedEncodingException {
526 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
527 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
528 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
531 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
532 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
533 final boolean returnJustMountPoint) {
534 Preconditions.<List<String>>checkNotNull(strings);
536 if (parentNode == null) {
540 if (strings.isEmpty()) {
541 return createContext(builder.build(), (DataSchemaNode) parentNode,
542 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
545 final String head = strings.iterator().next();
546 final String nodeName = toNodeName(head);
547 final String moduleName = toModuleName(head);
549 DataSchemaNode targetNode = null;
550 if (!Strings.isNullOrEmpty(moduleName)) {
551 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
552 if (mountPoint != null) {
553 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
554 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
557 if (this.mountService == null) {
558 throw new RestconfDocumentedException(
559 "MountService was not found. Finding behind mount points does not work.",
560 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
563 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
564 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
565 if (!mountOpt.isPresent()) {
566 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
567 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
568 ErrorTag.DATA_MISSING);
570 final DOMMountPoint mount = mountOpt.get();
572 final SchemaContext mountPointSchema = mount.getSchemaContext();
573 if (mountPointSchema == null) {
574 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
575 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
578 if (returnJustMountPoint || strings.size() == 1) {
579 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
580 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
583 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
584 if (moduleNameBehindMountPoint == null) {
585 throw new RestconfDocumentedException(
586 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
587 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
590 final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
592 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
593 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
596 final List<String> subList = strings.subList(1, strings.size());
597 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
598 returnJustMountPoint);
601 Module module = null;
602 if (mountPoint == null) {
603 checkPreconditions();
604 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
605 if (module == null) {
606 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
607 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
610 final SchemaContext schemaContext = mountPoint.getSchemaContext();
611 if (schemaContext != null) {
612 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
616 if (module == null) {
617 throw new RestconfDocumentedException("\"" + moduleName
618 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
622 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
624 if (targetNode == null && parentNode instanceof Module) {
625 final RpcDefinition rpc;
626 if (mountPoint == null) {
627 rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
629 final String rpcName = toNodeName(head);
630 ControllerContext.getInstance();
631 rpc = ControllerContext.getRpcDefinition(module, rpcName);
634 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
635 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
639 if (targetNode == null) {
640 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
641 + "\" was not found in parent data node.\n" + " 2. \"" + head
642 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
643 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
646 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
647 if (potentialSchemaNodes.size() > 1) {
648 final StringBuilder strBuilder = new StringBuilder();
649 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
650 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
653 throw new RestconfDocumentedException(
654 "URI has bad format. Node \""
655 + nodeName + "\" is added as augment from more than one module. "
656 + "Therefore the node must have module name "
657 + "and it has to be in format \"moduleName:nodeName\"."
658 + "\nThe node is added as augment from modules with namespaces:\n"
659 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
662 if (potentialSchemaNodes.isEmpty()) {
663 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
664 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
667 targetNode = potentialSchemaNodes.iterator().next();
670 if (!isListOrContainer(targetNode)) {
671 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
672 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
676 if (targetNode instanceof ListSchemaNode) {
677 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
678 final int keysSize = listNode.getKeyDefinition().size();
679 if (strings.size() - consumed < keysSize) {
680 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
681 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
684 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
685 final HashMap<QName, Object> keyValues = new HashMap<>();
687 for (final QName key : listNode.getKeyDefinition()) {
689 final String uriKeyValue = uriKeyValues.get(index);
690 if (uriKeyValue.equals(NULL_VALUE)) {
691 throw new RestconfDocumentedException("URI has bad format. List \""
692 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
693 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
696 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
701 consumed = consumed + index;
702 builder.nodeWithKey(targetNode.getQName(), keyValues);
704 builder.node(targetNode.getQName());
707 if (targetNode instanceof DataNodeContainer) {
708 final List<String> remaining = strings.subList(consumed, strings.size());
709 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
710 returnJustMountPoint);
713 return createContext(builder.build(), targetNode, mountPoint,
714 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
717 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
718 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
719 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
720 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
723 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
724 final String name, final URI namespace) {
725 Preconditions.checkNotNull(namespace);
727 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
728 node -> namespace.equals(node.getQName().getNamespace()));
729 return Iterables.getFirst(result, null);
732 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
734 Preconditions.checkNotNull(container);
735 Preconditions.checkNotNull(name);
737 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
738 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
739 return instantiatedDataNodeContainers;
742 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
743 final DataNodeContainer container, final String name) {
745 final Iterable<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<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
759 choice -> choice.getCases().values());
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 Preconditions.checkNotNull(uriValue);
774 Preconditions.checkArgument(node instanceof LeafSchemaNode);
776 final String urlDecoded = urlPathArgDecode(uriValue);
777 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
778 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
779 if (baseType instanceof LeafrefTypeDefinition) {
780 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, this.globalSchema,
783 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
784 Object decoded = codec.deserialize(urlDecoded);
785 String additionalInfo = "";
786 if (decoded == null) {
787 if (typedef instanceof IdentityrefTypeDefinition) {
788 final SchemaContext schemaContext =
789 mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
790 decoded = toQName(schemaContext, urlDecoded);
792 "For key which is of type identityref it should be in format module_name:identity_name.";
796 if (decoded == null) {
797 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
798 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
801 map.put(node.getQName(), decoded);
804 private static String toModuleName(final String str) {
805 final int idx = str.indexOf(':');
810 // Make sure there is only one occurrence
811 if (str.indexOf(':', idx + 1) != -1) {
815 return str.substring(0, idx);
818 private static String toNodeName(final String str) {
819 final int idx = str.indexOf(':');
824 // Make sure there is only one occurrence
825 if (str.indexOf(':', idx + 1) != -1) {
829 return str.substring(idx + 1);
832 private QName toQName(final SchemaContext schemaContext, final String name,
833 final java.util.Optional<Revision> revisionDate) {
834 checkPreconditions();
835 final String module = toModuleName(name);
836 final String node = toNodeName(name);
837 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
838 return m == null ? null : QName.create(m.getQNameModule(), node);
841 private QName toQName(final SchemaContext schemaContext, final String name) {
842 checkPreconditions();
843 final String module = toModuleName(name);
844 final String node = toNodeName(name);
845 final Set<Module> modules = schemaContext.findModules(module);
846 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
849 private static boolean isListOrContainer(final DataSchemaNode node) {
850 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
853 public RpcDefinition getRpcDefinition(final String name, final java.util.Optional<Revision> revisionDate) {
854 final QName validName = toQName(this.globalSchema, name, revisionDate);
855 return validName == null ? null : this.qnameToRpc.get().get(validName);
858 public RpcDefinition getRpcDefinition(final String name) {
859 final QName validName = toQName(this.globalSchema, name);
860 return validName == null ? null : this.qnameToRpc.get().get(validName);
863 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
864 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
865 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
866 if (rpcQName.equals(rpcDefinition.getQName())) {
867 return rpcDefinition;
874 public void onGlobalContextUpdated(final SchemaContext context) {
875 if (context != null) {
876 final Collection<RpcDefinition> defs = context.getOperations();
877 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
879 for (final RpcDefinition operation : defs) {
880 newMap.put(operation.getQName(), operation);
883 // FIXME: still not completely atomic
884 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
885 setGlobalSchema(context);
889 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
891 final List<String> decodedPathArgs = new ArrayList<>();
892 for (final String pathArg : strings) {
893 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
894 decodedPathArgs.add(_decode);
896 return decodedPathArgs;
897 } catch (final UnsupportedEncodingException e) {
898 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
899 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
903 public String urlPathArgDecode(final String pathArg) {
904 if (pathArg != null) {
906 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
907 } catch (final UnsupportedEncodingException e) {
908 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
909 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
916 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
917 final DOMMountPoint mount) {
918 if (argument instanceof NodeIdentifier) {
919 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
920 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
921 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
922 (ListSchemaNode) node, mount);
923 } else if (argument != null && node != null) {
924 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
926 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
930 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
931 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
934 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
935 final ListSchemaNode node, final DOMMountPoint mount) {
936 final QName nodeType = argument.getNodeType();
937 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
938 final Map<QName, Object> keyValues = argument.getKeyValues();
940 final StringBuilder builder = new StringBuilder();
942 builder.append(nodeIdentifier);
945 final List<QName> keyDefinition = node.getKeyDefinition();
946 boolean hasElements = false;
947 for (final QName key : keyDefinition) {
948 for (final DataSchemaNode listChild : node.getChildNodes()) {
949 if (listChild.getQName().equals(key)) {
957 Preconditions.checkState(listChild instanceof LeafSchemaNode,
958 "List key has to consist of leaves, not %s", listChild);
959 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
960 } catch (final UnsupportedEncodingException e) {
961 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
969 return builder.toString();
972 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
974 return this.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 this.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 = this.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 public DataNormalizationOperation<?> getRootOperation() {
1001 return this.dataNormalizer.getRootOperation();