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.Date;
27 import java.util.HashMap;
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.RestConfModule;
40 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
41 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
42 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
43 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
44 import org.opendaylight.restconf.common.util.RestUtil;
45 import org.opendaylight.yangtools.concepts.Codec;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
74 public class ControllerContext implements SchemaContextListener {
75 // FIXME: this should be in md-sal somewhere
76 public static final String MOUNT = "yang-ext:mount";
78 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
80 // FIXME: this should be the current instance which is mutated
81 private static final ControllerContext INSTANCE = new ControllerContext();
83 private static final String NULL_VALUE = "null";
85 private static final String MOUNT_MODULE = "yang-ext";
87 private static final String MOUNT_NODE = "mount";
89 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
91 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
93 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
95 // FIXME; these three should be final
96 private volatile SchemaContext globalSchema;
97 private volatile DOMMountPointService mountService;
98 private volatile DOMYangTextSourceProvider yangTextSourceProvider;
99 private DataNormalizer dataNormalizer;
102 public void setGlobalSchema(final SchemaContext globalSchema) {
103 this.globalSchema = globalSchema;
104 this.dataNormalizer = new DataNormalizer(globalSchema);
107 public void setMountService(final DOMMountPointService mountService) {
108 this.mountService = mountService;
111 public DOMYangTextSourceProvider getYangTextSourceProvider() {
112 return yangTextSourceProvider;
115 public void setYangTextSourceProvider(DOMYangTextSourceProvider yangTextSourceProvider) {
116 this.yangTextSourceProvider = yangTextSourceProvider;
119 private ControllerContext() {
122 public static ControllerContext getInstance() {
126 private void checkPreconditions() {
127 if (this.globalSchema == null) {
128 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
132 public void setSchemas(final SchemaContext schemas) {
133 onGlobalContextUpdated(schemas);
136 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
137 return toIdentifier(restconfInstance, false);
140 public SchemaContext getGlobalSchema() {
141 return this.globalSchema;
144 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
145 return toIdentifier(restconfInstance, true);
148 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
149 final boolean toMountPointIdentifier) {
150 checkPreconditions();
152 if (restconfInstance == null) {
153 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
157 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
158 omitFirstAndLastEmptyString(pathArgs);
159 if (pathArgs.isEmpty()) {
163 final String first = pathArgs.iterator().next();
164 final String startModule = toModuleName(first);
165 if (startModule == null) {
166 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
167 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
170 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
171 final Module latestModule = this.globalSchema.findModuleByName(startModule, null);
173 if (latestModule == null) {
174 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
175 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
178 final InstanceIdentifierContext<?> iiWithSchemaNode =
179 collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier);
181 if (iiWithSchemaNode == null) {
182 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
185 return iiWithSchemaNode;
188 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
189 if (list.isEmpty()) {
193 final String head = list.iterator().next();
194 if (head.isEmpty()) {
198 if (list.isEmpty()) {
202 final String last = list.get(list.size() - 1);
203 if (last.isEmpty()) {
204 list.remove(list.size() - 1);
210 public Module findModuleByName(final String moduleName) {
211 checkPreconditions();
212 Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty());
213 return this.globalSchema.findModuleByName(moduleName, null);
216 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
217 Preconditions.checkArgument((moduleName != null) && (mountPoint != null));
219 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
220 if (mountPointSchema == null) {
224 return mountPointSchema.findModuleByName(moduleName, null);
227 public Module findModuleByNamespace(final URI namespace) {
228 checkPreconditions();
229 Preconditions.checkArgument(namespace != null);
230 return this.globalSchema.findModuleByNamespaceAndRevision(namespace, null);
233 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
234 Preconditions.checkArgument((namespace != null) && (mountPoint != null));
236 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
237 if (mountPointSchema == null) {
241 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
244 public Module findModuleByNameAndRevision(final QName module) {
245 checkPreconditions();
247 .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
249 return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
252 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
253 checkPreconditions();
255 .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
256 && (mountPoint != null));
258 final SchemaContext schemaContext = mountPoint.getSchemaContext();
259 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
260 module.getRevision());
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.findModuleByNamespaceAndRevision(startQName.getNamespace(),
270 startQName.getRevision());
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.findModuleByNamespaceAndRevision(startQName.getNamespace(),
298 startQName.getRevision());
299 DataNodeContainer node = initialModule;
300 for (final PathArgument element : elements) {
301 if (!(element instanceof AugmentationIdentifier)) {
302 final QName _nodeType = element.getNodeType();
303 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
304 if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode))
305 && !(potentialNode instanceof ChoiceSchemaNode)) {
306 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
307 if (potentialNode instanceof DataNodeContainer) {
308 node = (DataNodeContainer) potentialNode;
314 return builder.toString();
317 public String findModuleNameByNamespace(final URI namespace) {
318 checkPreconditions();
320 final Module module = this.findModuleByNamespace(namespace);
321 return module == null ? null : module.getName();
324 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
325 final Module module = this.findModuleByNamespace(mountPoint, namespace);
326 return module == null ? null : module.getName();
329 public URI findNamespaceByModuleName(final String moduleName) {
330 final Module module = this.findModuleByName(moduleName);
331 return module == null ? null : module.getNamespace();
334 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
335 final Module module = this.findModuleByName(mountPoint, moduleName);
336 return module == null ? null : module.getNamespace();
339 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
340 checkPreconditions();
342 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
343 return schemaContext == null ? null : schemaContext.getModules();
346 public Set<Module> getAllModules() {
347 checkPreconditions();
348 return this.globalSchema.getModules();
351 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
352 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
353 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
356 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
357 final SchemaContext schema;
359 schema = mount.getSchemaContext();
361 checkPreconditions();
362 schema = this.globalSchema;
365 return toRestconfIdentifier(schema, qname);
368 public CharSequence toRestconfIdentifier(final QName qname) {
369 checkPreconditions();
371 return toRestconfIdentifier(this.globalSchema, qname);
374 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
375 if (mountPoint == null) {
379 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
382 public Module getRestconfModule() {
383 return findModuleByNameAndRevision(RestConfModule.IETF_RESTCONF_QNAME);
386 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
387 final Module restconfModule = getRestconfModule();
388 if (restconfModule == null) {
392 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
394 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
395 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
397 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
399 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
400 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
401 return Iterables.getFirst(instanceDataChildrenByName, null);
404 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
405 final String schemaNodeName) {
406 Module restconfModule = inRestconfModule;
407 if (restconfModule == null) {
408 restconfModule = getRestconfModule();
411 if (restconfModule == null) {
415 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
416 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
417 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
418 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
420 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
421 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
422 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
424 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
425 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
426 ((DataNodeContainer) restconfContainer), RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
427 return Iterables.getFirst(instances, null);
428 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
429 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
430 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
431 return Iterables.getFirst(instances, null);
432 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
433 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
434 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
435 final DataSchemaNode modules = Iterables.getFirst(instances, null);
436 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
437 RestConfModule.STREAM_LIST_SCHEMA_NODE);
438 return Iterables.getFirst(instances, null);
439 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
440 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
441 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
442 return Iterables.getFirst(instances, null);
443 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
444 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
445 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
446 final DataSchemaNode modules = Iterables.getFirst(instances, null);
447 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
448 RestConfModule.MODULE_LIST_SCHEMA_NODE);
449 return Iterables.getFirst(instances, null);
450 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
451 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
452 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
453 return Iterables.getFirst(instances, null);
459 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
460 for (final ChoiceCaseNode caze : container.getCases()) {
461 final DataSchemaNode ret = childByQName(caze, name);
470 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
471 return container.getDataChildByName(name);
474 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
475 return dataNodeChildByQName(container, name);
478 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
479 return dataNodeChildByQName(container, name);
482 private static DataSchemaNode childByQName(final Module container, final QName name) {
483 return dataNodeChildByQName(container, name);
486 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
491 private static DataSchemaNode childByQName(final Object container, final QName name) {
492 if (container instanceof ChoiceCaseNode) {
493 return childByQName((ChoiceCaseNode) container, name);
494 } else if (container instanceof ChoiceSchemaNode) {
495 return childByQName((ChoiceSchemaNode) container, name);
496 } else if (container instanceof ContainerSchemaNode) {
497 return childByQName((ContainerSchemaNode) container, name);
498 } else if (container instanceof ListSchemaNode) {
499 return childByQName((ListSchemaNode) container, name);
500 } else if (container instanceof DataSchemaNode) {
501 return childByQName((DataSchemaNode) container, name);
502 } else if (container instanceof Module) {
503 return childByQName((Module) container, name);
505 throw new IllegalArgumentException("Unhandled parameter types: "
506 + Arrays.<Object>asList(container, name).toString());
510 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
511 final DataSchemaNode ret = container.getDataChildByName(name);
513 for (final DataSchemaNode node : container.getChildNodes()) {
514 if ((node instanceof ChoiceSchemaNode)) {
515 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
516 final DataSchemaNode childByQName = childByQName(choiceNode, name);
517 if (childByQName != null) {
526 private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
527 throws UnsupportedEncodingException {
528 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
529 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
530 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
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 Module moduleBehindMountPoint =
593 mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
594 if (moduleBehindMountPoint == null) {
595 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
596 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
599 final List<String> subList = strings.subList(1, strings.size());
600 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
601 returnJustMountPoint);
604 Module module = null;
605 if (mountPoint == null) {
606 checkPreconditions();
607 module = this.globalSchema.findModuleByName(moduleName, null);
608 if (module == null) {
609 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
610 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
613 final SchemaContext schemaContext = mountPoint.getSchemaContext();
614 if (schemaContext != null) {
615 module = schemaContext.findModuleByName(moduleName, null);
619 if (module == null) {
620 throw new RestconfDocumentedException("\"" + moduleName
621 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
625 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
627 if ((targetNode == null) && (parentNode instanceof Module)) {
628 final RpcDefinition rpc;
629 if (mountPoint == null) {
630 rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
632 final String rpcName = toNodeName(head);
633 ControllerContext.getInstance();
634 rpc = ControllerContext.getRpcDefinition(module, rpcName);
637 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
638 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
642 if (targetNode == null) {
643 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
644 + "\" was not found in parent data node.\n" + " 2. \"" + head
645 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
646 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
649 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
650 if (potentialSchemaNodes.size() > 1) {
651 final StringBuilder strBuilder = new StringBuilder();
652 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
653 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
656 throw new RestconfDocumentedException(
657 "URI has bad format. Node \""
658 + nodeName + "\" is added as augment from more than one module. "
659 + "Therefore the node must have module name "
660 + "and it has to be in format \"moduleName:nodeName\"."
661 + "\nThe node is added as augment from modules with namespaces:\n"
662 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
665 if (potentialSchemaNodes.isEmpty()) {
666 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
667 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
670 targetNode = potentialSchemaNodes.iterator().next();
673 if (!isListOrContainer(targetNode)) {
674 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
675 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
679 if ((targetNode instanceof ListSchemaNode)) {
680 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
681 final int keysSize = listNode.getKeyDefinition().size();
682 if ((strings.size() - consumed) < keysSize) {
683 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
684 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
687 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
688 final HashMap<QName, Object> keyValues = new HashMap<>();
690 for (final QName key : listNode.getKeyDefinition()) {
692 final String uriKeyValue = uriKeyValues.get(index);
693 if (uriKeyValue.equals(NULL_VALUE)) {
694 throw new RestconfDocumentedException("URI has bad format. List \""
695 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
696 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
699 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
704 consumed = consumed + index;
705 builder.nodeWithKey(targetNode.getQName(), keyValues);
707 builder.node(targetNode.getQName());
710 if ((targetNode instanceof DataNodeContainer)) {
711 final List<String> remaining = strings.subList(consumed, strings.size());
712 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
713 returnJustMountPoint);
716 return createContext(builder.build(), targetNode, mountPoint,
717 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
720 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
721 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
722 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
723 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
726 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
727 final String name, final URI namespace) {
728 Preconditions.checkNotNull(namespace);
730 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
731 node -> namespace.equals(node.getQName().getNamespace()));
732 return Iterables.getFirst(result, null);
735 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
737 Preconditions.checkNotNull(container);
738 Preconditions.checkNotNull(name);
740 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
741 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
742 return instantiatedDataNodeContainers;
745 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
746 final DataNodeContainer container, final String name) {
748 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
749 node -> name.equals(node.getQName().getLocalName()));
751 // Can't combine this loop with the filter above because the filter is
752 // lazily-applied by Iterables.filter.
753 for (final DataSchemaNode potentialNode : nodes) {
754 if (isInstantiatedDataSchema(potentialNode)) {
755 potentialSchemaNodes.add(potentialNode);
759 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
760 ChoiceSchemaNode.class);
761 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
762 for (final ChoiceCaseNode 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 String urlDecoded = urlPathArgDecode(uriValue);
779 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
780 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
781 if (baseType instanceof LeafrefTypeDefinition) {
782 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, this.globalSchema,
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 final SchemaContext schemaContext =
791 mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
792 decoded = toQName(schemaContext, urlDecoded, null);
794 "For key which is of type identityref it should be in format module_name:identity_name.";
798 if (decoded == null) {
799 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
800 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
803 map.put(node.getQName(), decoded);
806 private static String toModuleName(final String str) {
807 final int idx = str.indexOf(':');
812 // Make sure there is only one occurrence
813 if (str.indexOf(':', idx + 1) != -1) {
817 return str.substring(0, idx);
820 private static String toNodeName(final String str) {
821 final int idx = str.indexOf(':');
826 // Make sure there is only one occurrence
827 if (str.indexOf(':', idx + 1) != -1) {
831 return str.substring(idx + 1);
834 private QName toQName(final SchemaContext schemaContext, final String name, final Date revisionDate) {
835 checkPreconditions();
836 final String module = toModuleName(name);
837 final String node = toNodeName(name);
838 final Module m = schemaContext.findModuleByName(module, revisionDate);
839 return m == null ? null : QName.create(m.getQNameModule(), node);
842 private static boolean isListOrContainer(final DataSchemaNode node) {
843 return (node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode);
846 public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) {
847 final QName validName = toQName(this.globalSchema, name, revisionDate);
848 return validName == null ? null : this.qnameToRpc.get().get(validName);
851 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
852 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
853 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
854 if (rpcQName.equals(rpcDefinition.getQName())) {
855 return rpcDefinition;
862 public void onGlobalContextUpdated(final SchemaContext context) {
863 if (context != null) {
864 final Collection<RpcDefinition> defs = context.getOperations();
865 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
867 for (final RpcDefinition operation : defs) {
868 newMap.put(operation.getQName(), operation);
871 // FIXME: still not completely atomic
872 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
873 setGlobalSchema(context);
877 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
879 final List<String> decodedPathArgs = new ArrayList<>();
880 for (final String pathArg : strings) {
881 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
882 decodedPathArgs.add(_decode);
884 return decodedPathArgs;
885 } catch (final UnsupportedEncodingException e) {
886 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
887 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
891 public String urlPathArgDecode(final String pathArg) {
892 if (pathArg != null) {
894 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
895 } catch (final UnsupportedEncodingException e) {
896 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
897 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
904 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
905 final DOMMountPoint mount) {
906 if (argument instanceof NodeIdentifier) {
907 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
908 } else if ((argument instanceof NodeIdentifierWithPredicates) && (node instanceof ListSchemaNode)) {
909 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
910 (ListSchemaNode) node, mount);
911 } else if ((argument != null) && (node != null)) {
912 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
914 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
918 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
919 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
922 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
923 final ListSchemaNode node, final DOMMountPoint mount) {
924 final QName nodeType = argument.getNodeType();
925 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
926 final Map<QName, Object> keyValues = argument.getKeyValues();
928 final StringBuilder builder = new StringBuilder();
930 builder.append(nodeIdentifier);
933 final List<QName> keyDefinition = node.getKeyDefinition();
934 boolean hasElements = false;
935 for (final QName key : keyDefinition) {
936 for (final DataSchemaNode listChild : node.getChildNodes()) {
937 if (listChild.getQName().equals(key)) {
945 Preconditions.checkState(listChild instanceof LeafSchemaNode,
946 "List key has to consist of leaves, not %s", listChild);
947 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
948 } catch (final UnsupportedEncodingException e) {
949 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
957 return builder.toString();
960 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
962 return this.dataNormalizer.toNormalized(legacy);
963 } catch (final NullPointerException e) {
964 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
968 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
970 return this.dataNormalizer.toLegacy(instanceIdentifier);
971 } catch (final NullPointerException e) {
972 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
973 } catch (final DataNormalizationException e) {
974 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
978 public boolean isNodeMixin(final YangInstanceIdentifier path) {
979 final DataNormalizationOperation<?> operation;
981 operation = this.dataNormalizer.getOperation(path);
982 } catch (final DataNormalizationException e) {
983 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
985 return operation.isMixin();
988 public DataNormalizationOperation<?> getRootOperation() {
989 return this.dataNormalizer.getRootOperation();