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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.io.UnsupportedEncodingException;
19 import java.net.URLDecoder;
20 import java.net.URLEncoder;
21 import java.nio.charset.Charset;
22 import java.nio.charset.StandardCharsets;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
32 import java.util.concurrent.atomic.AtomicReference;
33 import javax.ws.rs.core.Response.Status;
34 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
36 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
38 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
39 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
40 import org.opendaylight.netconf.sal.rest.api.Draft02;
41 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
42 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
43 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
44 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
45 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
46 import org.opendaylight.restconf.common.util.RestUtil;
47 import org.opendaylight.yangtools.concepts.Codec;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.Revision;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
61 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
63 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.Module;
67 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
70 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
77 public class ControllerContext implements SchemaContextListener {
78 // FIXME: this should be in md-sal somewhere
79 public static final String MOUNT = "yang-ext:mount";
81 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
83 // FIXME: this should be the current instance which is mutated
84 private static final ControllerContext INSTANCE = new ControllerContext();
86 private static final String NULL_VALUE = "null";
88 private static final String MOUNT_MODULE = "yang-ext";
90 private static final String MOUNT_NODE = "mount";
92 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
94 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
96 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
98 // FIXME; these three should be final
99 private volatile SchemaContext globalSchema;
100 private volatile DOMMountPointService mountService;
101 private volatile DOMYangTextSourceProvider yangTextSourceProvider;
102 private DataNormalizer dataNormalizer;
105 public void setGlobalSchema(final SchemaContext globalSchema) {
106 this.globalSchema = globalSchema;
107 this.dataNormalizer = new DataNormalizer(globalSchema);
110 public void setMountService(final DOMMountPointService mountService) {
111 this.mountService = mountService;
114 public DOMYangTextSourceProvider getYangTextSourceProvider() {
115 return yangTextSourceProvider;
118 public void setYangTextSourceProvider(DOMYangTextSourceProvider yangTextSourceProvider) {
119 this.yangTextSourceProvider = yangTextSourceProvider;
122 ControllerContext() {
126 public static ControllerContext getInstance() {
130 private void checkPreconditions() {
131 if (this.globalSchema == null) {
132 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
136 public void setSchemas(final SchemaContext schemas) {
137 onGlobalContextUpdated(schemas);
140 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
141 return toIdentifier(restconfInstance, false);
144 public SchemaContext getGlobalSchema() {
145 return this.globalSchema;
148 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
149 return toIdentifier(restconfInstance, true);
152 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
153 final boolean toMountPointIdentifier) {
154 checkPreconditions();
156 if (restconfInstance == null) {
157 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
161 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
162 omitFirstAndLastEmptyString(pathArgs);
163 if (pathArgs.isEmpty()) {
167 final String first = pathArgs.iterator().next();
168 final String startModule = toModuleName(first);
169 if (startModule == null) {
170 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
171 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
174 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
175 final Set<Module> latestModule = this.globalSchema.findModules(startModule);
177 if (latestModule.isEmpty()) {
178 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
179 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
182 final InstanceIdentifierContext<?> iiWithSchemaNode =
183 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
185 if (iiWithSchemaNode == null) {
186 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
189 return iiWithSchemaNode;
192 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
193 if (list.isEmpty()) {
197 final String head = list.iterator().next();
198 if (head.isEmpty()) {
202 if (list.isEmpty()) {
206 final String last = list.get(list.size() - 1);
207 if (last.isEmpty()) {
208 list.remove(list.size() - 1);
214 public Module findModuleByName(final String moduleName) {
215 checkPreconditions();
216 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
217 return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
220 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
221 Preconditions.checkArgument(moduleName != null && mountPoint != null);
223 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
224 if (mountPointSchema == null) {
228 return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
231 public Module findModuleByNamespace(final URI namespace) {
232 checkPreconditions();
233 Preconditions.checkArgument(namespace != null);
234 return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
237 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
238 Preconditions.checkArgument(namespace != null && mountPoint != null);
240 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
241 if (mountPointSchema == null) {
245 return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
248 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
249 checkPreconditions();
250 Preconditions.checkArgument(name != null && revision != null);
252 return this.globalSchema.findModule(name, revision).orElse(null);
255 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
256 final Revision revision) {
257 checkPreconditions();
258 Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
260 final SchemaContext schemaContext = mountPoint.getSchemaContext();
261 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
264 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
265 checkPreconditions();
267 final Iterable<PathArgument> elements = path.getPathArguments();
268 final PathArgument head = elements.iterator().next();
269 final QName startQName = head.getNodeType();
270 final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
271 DataNodeContainer node = initialModule;
272 for (final PathArgument element : elements) {
273 final QName _nodeType = element.getNodeType();
274 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
275 if (potentialNode == null || !isListOrContainer(potentialNode)) {
278 node = (DataNodeContainer) potentialNode;
284 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
285 checkPreconditions();
287 final Iterable<PathArgument> elements = path.getPathArguments();
288 final StringBuilder builder = new StringBuilder();
289 final PathArgument head = elements.iterator().next();
290 final QName startQName = head.getNodeType();
291 final SchemaContext schemaContext;
293 schemaContext = mount.getSchemaContext();
295 schemaContext = this.globalSchema;
297 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
298 DataNodeContainer node = initialModule;
299 for (final PathArgument element : elements) {
300 if (!(element instanceof AugmentationIdentifier)) {
301 final QName _nodeType = element.getNodeType();
302 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
303 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)
304 && !(potentialNode instanceof ChoiceSchemaNode)) {
305 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
306 if (potentialNode instanceof DataNodeContainer) {
307 node = (DataNodeContainer) potentialNode;
313 return builder.toString();
316 public String findModuleNameByNamespace(final URI namespace) {
317 checkPreconditions();
319 final Module module = this.findModuleByNamespace(namespace);
320 return module == null ? null : module.getName();
323 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
324 final Module module = this.findModuleByNamespace(mountPoint, namespace);
325 return module == null ? null : module.getName();
328 public URI findNamespaceByModuleName(final String moduleName) {
329 final Module module = this.findModuleByName(moduleName);
330 return module == null ? null : module.getNamespace();
333 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
334 final Module module = this.findModuleByName(mountPoint, moduleName);
335 return module == null ? null : module.getNamespace();
338 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
339 checkPreconditions();
341 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
342 return schemaContext == null ? null : schemaContext.getModules();
345 public Set<Module> getAllModules() {
346 checkPreconditions();
347 return this.globalSchema.getModules();
350 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
351 final Module schema = context.findModule(qname.getModule()).orElse(null);
352 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
355 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
356 final SchemaContext schema;
358 schema = mount.getSchemaContext();
360 checkPreconditions();
361 schema = this.globalSchema;
364 return toRestconfIdentifier(schema, qname);
367 public CharSequence toRestconfIdentifier(final QName qname) {
368 checkPreconditions();
370 return toRestconfIdentifier(this.globalSchema, qname);
373 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
374 if (mountPoint == null) {
378 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
381 public Module getRestconfModule() {
382 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
385 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
386 final Module restconfModule = getRestconfModule();
387 if (restconfModule == null) {
391 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
393 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
394 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
396 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
398 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
399 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
400 return Iterables.getFirst(instanceDataChildrenByName, null);
403 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
404 final String schemaNodeName) {
405 Module restconfModule = inRestconfModule;
406 if (restconfModule == null) {
407 restconfModule = getRestconfModule();
410 if (restconfModule == null) {
414 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
415 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
416 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
417 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
419 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
420 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
421 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
423 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
424 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
425 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
426 return Iterables.getFirst(instances, null);
427 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
428 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
429 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
430 return Iterables.getFirst(instances, null);
431 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
432 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
433 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
434 final DataSchemaNode modules = Iterables.getFirst(instances, null);
435 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
436 RestConfModule.STREAM_LIST_SCHEMA_NODE);
437 return Iterables.getFirst(instances, null);
438 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
439 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
440 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
441 return Iterables.getFirst(instances, null);
442 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
443 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
444 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
445 final DataSchemaNode modules = Iterables.getFirst(instances, null);
446 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
447 RestConfModule.MODULE_LIST_SCHEMA_NODE);
448 return Iterables.getFirst(instances, null);
449 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
450 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
451 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
452 return Iterables.getFirst(instances, null);
458 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
459 for (final CaseSchemaNode caze : container.getCases().values()) {
460 final DataSchemaNode ret = childByQName(caze, name);
469 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
470 return container.getDataChildByName(name);
473 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
474 return dataNodeChildByQName(container, name);
477 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
478 return dataNodeChildByQName(container, name);
481 private static DataSchemaNode childByQName(final Module container, final QName name) {
482 return dataNodeChildByQName(container, name);
485 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
490 private static DataSchemaNode childByQName(final Object container, final QName name) {
491 if (container instanceof CaseSchemaNode) {
492 return childByQName((CaseSchemaNode) container, name);
493 } else if (container instanceof ChoiceSchemaNode) {
494 return childByQName((ChoiceSchemaNode) container, name);
495 } else if (container instanceof ContainerSchemaNode) {
496 return childByQName((ContainerSchemaNode) container, name);
497 } else if (container instanceof ListSchemaNode) {
498 return childByQName((ListSchemaNode) container, name);
499 } else if (container instanceof DataSchemaNode) {
500 return childByQName((DataSchemaNode) container, name);
501 } else if (container instanceof Module) {
502 return childByQName((Module) container, name);
504 throw new IllegalArgumentException("Unhandled parameter types: "
505 + Arrays.<Object>asList(container, name).toString());
509 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
510 final DataSchemaNode ret = container.getDataChildByName(name);
512 for (final DataSchemaNode node : container.getChildNodes()) {
513 if (node instanceof ChoiceSchemaNode) {
514 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
515 final DataSchemaNode childByQName = childByQName(choiceNode, name);
516 if (childByQName != null) {
525 private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
526 throws UnsupportedEncodingException {
527 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
528 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
529 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
532 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
533 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
534 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
535 final boolean returnJustMountPoint) {
536 Preconditions.<List<String>>checkNotNull(strings);
538 if (parentNode == null) {
542 if (strings.isEmpty()) {
543 return createContext(builder.build(), (DataSchemaNode) parentNode,
544 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
547 final String head = strings.iterator().next();
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 (this.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 = this.dataNormalizer.toNormalized(builder.build());
566 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
567 if (!mountOpt.isPresent()) {
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 SchemaContext mountPointSchema = mount.getSchemaContext();
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 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
582 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
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<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
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 = this.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 SchemaContext schemaContext = mountPoint.getSchemaContext();
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 = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
631 final String rpcName = toNodeName(head);
632 ControllerContext.getInstance();
633 rpc = ControllerContext.getRpcDefinition(module, rpcName);
636 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
637 mountPoint != null ? mountPoint.getSchemaContext() : this.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 ? mountPoint.getSchemaContext() : this.globalSchema);
719 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
720 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext 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 URI namespace) {
727 Preconditions.checkNotNull(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 Preconditions.checkNotNull(container);
737 Preconditions.checkNotNull(name);
739 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
740 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
741 return instantiatedDataNodeContainers;
744 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
745 final DataNodeContainer container, final String name) {
747 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
748 node -> name.equals(node.getQName().getLocalName()));
750 // Can't combine this loop with the filter above because the filter is
751 // lazily-applied by Iterables.filter.
752 for (final DataSchemaNode potentialNode : nodes) {
753 if (isInstantiatedDataSchema(potentialNode)) {
754 potentialSchemaNodes.add(potentialNode);
758 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
759 ChoiceSchemaNode.class);
760 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
761 choice -> choice.getCases().values());
762 for (final CaseSchemaNode caze : Iterables.concat(map)) {
763 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
767 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
768 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
769 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
770 || node instanceof AnyXmlSchemaNode;
773 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
774 final DOMMountPoint mountPoint) {
775 Preconditions.checkNotNull(uriValue);
776 Preconditions.checkArgument(node instanceof LeafSchemaNode);
778 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
779 final String urlDecoded = urlPathArgDecode(uriValue);
780 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
781 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
782 if (baseType instanceof LeafrefTypeDefinition) {
783 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
785 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
786 Object decoded = codec.deserialize(urlDecoded);
787 String additionalInfo = "";
788 if (decoded == null) {
789 if (typedef instanceof IdentityrefTypeDefinition) {
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();