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.Closeable;
18 import java.io.UnsupportedEncodingException;
20 import java.net.URLDecoder;
21 import java.net.URLEncoder;
22 import java.nio.charset.Charset;
23 import java.nio.charset.StandardCharsets;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
33 import java.util.concurrent.atomic.AtomicReference;
34 import javax.ws.rs.core.Response.Status;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
36 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
37 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
38 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
39 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
40 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
41 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
42 import org.opendaylight.netconf.sal.rest.api.Draft02;
43 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
44 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
45 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
46 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
47 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
48 import org.opendaylight.restconf.common.util.RestUtil;
49 import org.opendaylight.yangtools.concepts.Codec;
50 import org.opendaylight.yangtools.concepts.ListenerRegistration;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.Revision;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
59 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
64 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
66 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.Module;
70 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
73 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
80 public final class ControllerContext implements SchemaContextListener, Closeable {
81 // FIXME: this should be in md-sal somewhere
82 public static final String MOUNT = "yang-ext:mount";
84 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
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 private final DOMMountPointService mountService;
99 private final DOMYangTextSourceProvider yangTextSourceProvider;
100 private final ListenerRegistration<SchemaContextListener> listenerRegistration;
101 private volatile SchemaContext globalSchema;
102 private volatile DataNormalizer dataNormalizer;
104 private ControllerContext(DOMSchemaService schemaService, DOMMountPointService mountService,
105 DOMYangTextSourceProvider yangTextSourceProvider) {
106 this.mountService = mountService;
107 this.yangTextSourceProvider = yangTextSourceProvider;
109 onGlobalContextUpdated(schemaService.getGlobalContext());
110 listenerRegistration = schemaService.registerSchemaContextListener(this);
113 public static ControllerContext newInstance(DOMSchemaService schemaService, DOMMountPointService mountService,
114 DOMSchemaService domSchemaService) {
115 final DOMYangTextSourceProvider yangTextSourceProvider =
116 (DOMYangTextSourceProvider) domSchemaService.getSupportedExtensions().get(DOMYangTextSourceProvider.class);
118 return new ControllerContext(schemaService, mountService, yangTextSourceProvider);
121 private void setGlobalSchema(final SchemaContext globalSchema) {
122 this.globalSchema = globalSchema;
123 this.dataNormalizer = new DataNormalizer(globalSchema);
126 public DOMYangTextSourceProvider getYangTextSourceProvider() {
127 return yangTextSourceProvider;
130 private void checkPreconditions() {
131 if (this.globalSchema == null) {
132 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
137 public void close() {
138 listenerRegistration.close();
141 public void setSchemas(final SchemaContext schemas) {
142 onGlobalContextUpdated(schemas);
145 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
146 return toIdentifier(restconfInstance, false);
149 public SchemaContext getGlobalSchema() {
150 return this.globalSchema;
153 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
154 return toIdentifier(restconfInstance, true);
157 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
158 final boolean toMountPointIdentifier) {
159 checkPreconditions();
161 if (restconfInstance == null) {
162 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
166 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
167 omitFirstAndLastEmptyString(pathArgs);
168 if (pathArgs.isEmpty()) {
172 final String first = pathArgs.iterator().next();
173 final String startModule = toModuleName(first);
174 if (startModule == null) {
175 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
176 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
179 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
180 final Set<Module> latestModule = this.globalSchema.findModules(startModule);
182 if (latestModule.isEmpty()) {
183 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
184 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
187 final InstanceIdentifierContext<?> iiWithSchemaNode =
188 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
190 if (iiWithSchemaNode == null) {
191 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
194 return iiWithSchemaNode;
197 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
198 if (list.isEmpty()) {
202 final String head = list.iterator().next();
203 if (head.isEmpty()) {
207 if (list.isEmpty()) {
211 final String last = list.get(list.size() - 1);
212 if (last.isEmpty()) {
213 list.remove(list.size() - 1);
219 public Module findModuleByName(final String moduleName) {
220 checkPreconditions();
221 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
222 return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
225 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
226 Preconditions.checkArgument(moduleName != null && mountPoint != null);
228 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
229 if (mountPointSchema == null) {
233 return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
236 public Module findModuleByNamespace(final URI namespace) {
237 checkPreconditions();
238 Preconditions.checkArgument(namespace != null);
239 return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
242 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
243 Preconditions.checkArgument(namespace != null && mountPoint != null);
245 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
246 if (mountPointSchema == null) {
250 return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
253 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
254 checkPreconditions();
255 Preconditions.checkArgument(name != null && revision != null);
257 return this.globalSchema.findModule(name, revision).orElse(null);
260 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
261 final Revision revision) {
262 checkPreconditions();
263 Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
265 final SchemaContext schemaContext = mountPoint.getSchemaContext();
266 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
269 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
270 checkPreconditions();
272 final Iterable<PathArgument> elements = path.getPathArguments();
273 final PathArgument head = elements.iterator().next();
274 final QName startQName = head.getNodeType();
275 final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
276 DataNodeContainer node = initialModule;
277 for (final PathArgument element : elements) {
278 final QName _nodeType = element.getNodeType();
279 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
280 if (potentialNode == null || !isListOrContainer(potentialNode)) {
283 node = (DataNodeContainer) potentialNode;
289 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
290 checkPreconditions();
292 final Iterable<PathArgument> elements = path.getPathArguments();
293 final StringBuilder builder = new StringBuilder();
294 final PathArgument head = elements.iterator().next();
295 final QName startQName = head.getNodeType();
296 final SchemaContext schemaContext;
298 schemaContext = mount.getSchemaContext();
300 schemaContext = this.globalSchema;
302 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
303 DataNodeContainer node = initialModule;
304 for (final PathArgument element : elements) {
305 if (!(element instanceof AugmentationIdentifier)) {
306 final QName _nodeType = element.getNodeType();
307 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
308 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)
309 && !(potentialNode instanceof ChoiceSchemaNode)) {
310 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
311 if (potentialNode instanceof DataNodeContainer) {
312 node = (DataNodeContainer) potentialNode;
318 return builder.toString();
321 public String findModuleNameByNamespace(final URI namespace) {
322 checkPreconditions();
324 final Module module = this.findModuleByNamespace(namespace);
325 return module == null ? null : module.getName();
328 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
329 final Module module = this.findModuleByNamespace(mountPoint, namespace);
330 return module == null ? null : module.getName();
333 public URI findNamespaceByModuleName(final String moduleName) {
334 final Module module = this.findModuleByName(moduleName);
335 return module == null ? null : module.getNamespace();
338 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
339 final Module module = this.findModuleByName(mountPoint, moduleName);
340 return module == null ? null : module.getNamespace();
343 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
344 checkPreconditions();
346 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
347 return schemaContext == null ? null : schemaContext.getModules();
350 public Set<Module> getAllModules() {
351 checkPreconditions();
352 return this.globalSchema.getModules();
355 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
356 final Module schema = context.findModule(qname.getModule()).orElse(null);
357 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
360 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
361 final SchemaContext schema;
363 schema = mount.getSchemaContext();
365 checkPreconditions();
366 schema = this.globalSchema;
369 return toRestconfIdentifier(schema, qname);
372 public CharSequence toRestconfIdentifier(final QName qname) {
373 checkPreconditions();
375 return toRestconfIdentifier(this.globalSchema, qname);
378 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
379 if (mountPoint == null) {
383 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
386 public Module getRestconfModule() {
387 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
390 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
391 final Module restconfModule = getRestconfModule();
392 if (restconfModule == null) {
396 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
398 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
399 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
401 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
403 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
404 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
405 return Iterables.getFirst(instanceDataChildrenByName, null);
408 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
409 final String schemaNodeName) {
410 Module restconfModule = inRestconfModule;
411 if (restconfModule == null) {
412 restconfModule = getRestconfModule();
415 if (restconfModule == null) {
419 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
420 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
421 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
422 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
424 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
425 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
426 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
428 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
429 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
430 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
431 return Iterables.getFirst(instances, null);
432 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
433 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
434 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
435 return Iterables.getFirst(instances, null);
436 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
437 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
438 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
439 final DataSchemaNode modules = Iterables.getFirst(instances, null);
440 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
441 RestConfModule.STREAM_LIST_SCHEMA_NODE);
442 return Iterables.getFirst(instances, null);
443 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
444 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
445 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
446 return Iterables.getFirst(instances, null);
447 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
448 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
449 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
450 final DataSchemaNode modules = Iterables.getFirst(instances, null);
451 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
452 RestConfModule.MODULE_LIST_SCHEMA_NODE);
453 return Iterables.getFirst(instances, null);
454 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
455 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
456 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
457 return Iterables.getFirst(instances, null);
463 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
464 for (final CaseSchemaNode caze : container.getCases().values()) {
465 final DataSchemaNode ret = childByQName(caze, name);
474 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
475 return container.getDataChildByName(name);
478 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
479 return dataNodeChildByQName(container, name);
482 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
483 return dataNodeChildByQName(container, name);
486 private static DataSchemaNode childByQName(final Module container, final QName name) {
487 return dataNodeChildByQName(container, name);
490 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
495 private static DataSchemaNode childByQName(final Object container, final QName name) {
496 if (container instanceof CaseSchemaNode) {
497 return childByQName((CaseSchemaNode) container, name);
498 } else if (container instanceof ChoiceSchemaNode) {
499 return childByQName((ChoiceSchemaNode) container, name);
500 } else if (container instanceof ContainerSchemaNode) {
501 return childByQName((ContainerSchemaNode) container, name);
502 } else if (container instanceof ListSchemaNode) {
503 return childByQName((ListSchemaNode) container, name);
504 } else if (container instanceof DataSchemaNode) {
505 return childByQName((DataSchemaNode) container, name);
506 } else if (container instanceof Module) {
507 return childByQName((Module) container, name);
509 throw new IllegalArgumentException("Unhandled parameter types: "
510 + Arrays.asList(container, name).toString());
514 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
515 final DataSchemaNode ret = container.getDataChildByName(name);
517 for (final DataSchemaNode node : container.getChildNodes()) {
518 if (node instanceof ChoiceSchemaNode) {
519 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
520 final DataSchemaNode childByQName = childByQName(choiceNode, name);
521 if (childByQName != null) {
530 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
531 throws UnsupportedEncodingException {
532 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
533 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
534 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
537 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
538 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
539 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
540 final boolean returnJustMountPoint) {
541 Preconditions.checkNotNull(strings);
543 if (parentNode == null) {
547 if (strings.isEmpty()) {
548 return createContext(builder.build(), (DataSchemaNode) parentNode,
549 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
552 final String head = strings.iterator().next();
553 final String nodeName = toNodeName(head);
554 final String moduleName = toModuleName(head);
556 DataSchemaNode targetNode = null;
557 if (!Strings.isNullOrEmpty(moduleName)) {
558 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
559 if (mountPoint != null) {
560 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
561 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
564 if (this.mountService == null) {
565 throw new RestconfDocumentedException(
566 "MountService was not found. Finding behind mount points does not work.",
567 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
570 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
571 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
572 if (!mountOpt.isPresent()) {
573 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
574 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
575 ErrorTag.DATA_MISSING);
577 final DOMMountPoint mount = mountOpt.get();
579 final SchemaContext mountPointSchema = mount.getSchemaContext();
580 if (mountPointSchema == null) {
581 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
582 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
585 if (returnJustMountPoint || strings.size() == 1) {
586 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
587 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
590 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
591 if (moduleNameBehindMountPoint == null) {
592 throw new RestconfDocumentedException(
593 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
594 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
597 final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
599 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
600 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
603 final List<String> subList = strings.subList(1, strings.size());
604 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
605 returnJustMountPoint);
608 Module module = null;
609 if (mountPoint == null) {
610 checkPreconditions();
611 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
612 if (module == null) {
613 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
614 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
617 final SchemaContext schemaContext = mountPoint.getSchemaContext();
618 if (schemaContext != null) {
619 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
623 if (module == null) {
624 throw new RestconfDocumentedException("\"" + moduleName
625 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
629 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
631 if (targetNode == null && parentNode instanceof Module) {
632 final RpcDefinition rpc;
633 if (mountPoint == null) {
634 rpc = getRpcDefinition(head, module.getRevision());
636 final String rpcName = toNodeName(head);
637 rpc = getRpcDefinition(module, rpcName);
640 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
641 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
645 if (targetNode == null) {
646 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
647 + "\" was not found in parent data node.\n" + " 2. \"" + head
648 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
649 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
652 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
653 if (potentialSchemaNodes.size() > 1) {
654 final StringBuilder strBuilder = new StringBuilder();
655 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
656 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
659 throw new RestconfDocumentedException(
660 "URI has bad format. Node \""
661 + nodeName + "\" is added as augment from more than one module. "
662 + "Therefore the node must have module name "
663 + "and it has to be in format \"moduleName:nodeName\"."
664 + "\nThe node is added as augment from modules with namespaces:\n"
665 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
668 if (potentialSchemaNodes.isEmpty()) {
669 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
670 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
673 targetNode = potentialSchemaNodes.iterator().next();
676 if (!isListOrContainer(targetNode)) {
677 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
678 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
682 if (targetNode instanceof ListSchemaNode) {
683 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
684 final int keysSize = listNode.getKeyDefinition().size();
685 if (strings.size() - consumed < keysSize) {
686 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
687 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
690 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
691 final HashMap<QName, Object> keyValues = new HashMap<>();
693 for (final QName key : listNode.getKeyDefinition()) {
695 final String uriKeyValue = uriKeyValues.get(index);
696 if (uriKeyValue.equals(NULL_VALUE)) {
697 throw new RestconfDocumentedException("URI has bad format. List \""
698 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
699 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
702 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
707 consumed = consumed + index;
708 builder.nodeWithKey(targetNode.getQName(), keyValues);
710 builder.node(targetNode.getQName());
713 if (targetNode instanceof DataNodeContainer) {
714 final List<String> remaining = strings.subList(consumed, strings.size());
715 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
716 returnJustMountPoint);
719 return createContext(builder.build(), targetNode, mountPoint,
720 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
723 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
724 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
725 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
726 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
729 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
730 final String name, final URI namespace) {
731 Preconditions.checkNotNull(namespace);
733 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
734 node -> namespace.equals(node.getQName().getNamespace()));
735 return Iterables.getFirst(result, null);
738 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
740 Preconditions.checkNotNull(container);
741 Preconditions.checkNotNull(name);
743 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
744 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
745 return instantiatedDataNodeContainers;
748 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
749 final DataNodeContainer container, final String name) {
751 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
752 node -> name.equals(node.getQName().getLocalName()));
754 // Can't combine this loop with the filter above because the filter is
755 // lazily-applied by Iterables.filter.
756 for (final DataSchemaNode potentialNode : nodes) {
757 if (isInstantiatedDataSchema(potentialNode)) {
758 potentialSchemaNodes.add(potentialNode);
762 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
763 ChoiceSchemaNode.class);
764 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
765 choice -> choice.getCases().values());
766 for (final CaseSchemaNode caze : Iterables.concat(map)) {
767 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
771 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
772 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
773 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
774 || node instanceof AnyXmlSchemaNode;
777 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
778 final DOMMountPoint mountPoint) {
779 Preconditions.checkNotNull(uriValue);
780 Preconditions.checkArgument(node instanceof LeafSchemaNode);
782 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
783 final String urlDecoded = urlPathArgDecode(uriValue);
784 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
785 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
786 if (baseType instanceof LeafrefTypeDefinition) {
787 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
789 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
790 Object decoded = codec.deserialize(urlDecoded);
791 String additionalInfo = "";
792 if (decoded == null) {
793 if (typedef instanceof IdentityrefTypeDefinition) {
794 decoded = toQName(schemaContext, urlDecoded);
796 "For key which is of type identityref it should be in format module_name:identity_name.";
800 if (decoded == null) {
801 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
802 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
805 map.put(node.getQName(), decoded);
808 private static String toModuleName(final String str) {
809 final int idx = str.indexOf(':');
814 // Make sure there is only one occurrence
815 if (str.indexOf(':', idx + 1) != -1) {
819 return str.substring(0, idx);
822 private static String toNodeName(final String str) {
823 final int idx = str.indexOf(':');
828 // Make sure there is only one occurrence
829 if (str.indexOf(':', idx + 1) != -1) {
833 return str.substring(idx + 1);
836 private QName toQName(final SchemaContext schemaContext, final String name,
837 final java.util.Optional<Revision> revisionDate) {
838 checkPreconditions();
839 final String module = toModuleName(name);
840 final String node = toNodeName(name);
841 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
842 return m == null ? null : QName.create(m.getQNameModule(), node);
845 private QName toQName(final SchemaContext schemaContext, final String name) {
846 checkPreconditions();
847 final String module = toModuleName(name);
848 final String node = toNodeName(name);
849 final Set<Module> modules = schemaContext.findModules(module);
850 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
853 private static boolean isListOrContainer(final DataSchemaNode node) {
854 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
857 public RpcDefinition getRpcDefinition(final String name, final java.util.Optional<Revision> revisionDate) {
858 final QName validName = toQName(this.globalSchema, name, revisionDate);
859 return validName == null ? null : this.qnameToRpc.get().get(validName);
862 public RpcDefinition getRpcDefinition(final String name) {
863 final QName validName = toQName(this.globalSchema, name);
864 return validName == null ? null : this.qnameToRpc.get().get(validName);
867 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
868 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
869 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
870 if (rpcQName.equals(rpcDefinition.getQName())) {
871 return rpcDefinition;
878 public void onGlobalContextUpdated(final SchemaContext context) {
879 if (context != null) {
880 final Collection<RpcDefinition> defs = context.getOperations();
881 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
883 for (final RpcDefinition operation : defs) {
884 newMap.put(operation.getQName(), operation);
887 // FIXME: still not completely atomic
888 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
889 setGlobalSchema(context);
893 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
895 final List<String> decodedPathArgs = new ArrayList<>();
896 for (final String pathArg : strings) {
897 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
898 decodedPathArgs.add(_decode);
900 return decodedPathArgs;
901 } catch (final UnsupportedEncodingException e) {
902 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
903 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
907 public String urlPathArgDecode(final String pathArg) {
908 if (pathArg != null) {
910 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
911 } catch (final UnsupportedEncodingException e) {
912 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
913 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
920 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
921 final DOMMountPoint mount) {
922 if (argument instanceof NodeIdentifier) {
923 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
924 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
925 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
926 (ListSchemaNode) node, mount);
927 } else if (argument != null && node != null) {
928 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
930 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
934 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
935 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
938 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
939 final ListSchemaNode node, final DOMMountPoint mount) {
940 final QName nodeType = argument.getNodeType();
941 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
942 final Map<QName, Object> keyValues = argument.getKeyValues();
944 final StringBuilder builder = new StringBuilder();
946 builder.append(nodeIdentifier);
949 final List<QName> keyDefinition = node.getKeyDefinition();
950 boolean hasElements = false;
951 for (final QName key : keyDefinition) {
952 for (final DataSchemaNode listChild : node.getChildNodes()) {
953 if (listChild.getQName().equals(key)) {
961 Preconditions.checkState(listChild instanceof LeafSchemaNode,
962 "List key has to consist of leaves, not %s", listChild);
963 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
964 } catch (final UnsupportedEncodingException e) {
965 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
973 return builder.toString();
976 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
978 return this.dataNormalizer.toNormalized(legacy);
979 } catch (final NullPointerException e) {
980 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
984 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
986 return this.dataNormalizer.toLegacy(instanceIdentifier);
987 } catch (final NullPointerException e) {
988 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
989 } catch (final DataNormalizationException e) {
990 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
994 public boolean isNodeMixin(final YangInstanceIdentifier path) {
995 final DataNormalizationOperation<?> operation;
997 operation = this.dataNormalizer.getOperation(path);
998 } catch (final DataNormalizationException e) {
999 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1001 return operation.isMixin();
1004 public DataNormalizationOperation<?> getRootOperation() {
1005 return this.dataNormalizer.getRootOperation();