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.Preconditions;
11 import com.google.common.base.Splitter;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.Iterables;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.Closeable;
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;
31 import java.util.Optional;
33 import java.util.concurrent.atomic.AtomicReference;
34 import javax.annotation.PreDestroy;
35 import javax.inject.Inject;
36 import javax.inject.Singleton;
37 import javax.ws.rs.core.Response.Status;
38 import org.apache.aries.blueprint.annotation.service.Reference;
39 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
40 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
41 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
42 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
43 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
44 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
45 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
46 import org.opendaylight.netconf.sal.rest.api.Draft02;
47 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
48 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
49 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
50 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
51 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
52 import org.opendaylight.restconf.common.util.RestUtil;
53 import org.opendaylight.yangtools.concepts.Codec;
54 import org.opendaylight.yangtools.concepts.ListenerRegistration;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.Revision;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
68 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
70 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.Module;
74 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
77 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
85 public final class ControllerContext implements SchemaContextListener, Closeable {
86 // FIXME: this should be in md-sal somewhere
87 public static final String MOUNT = "yang-ext:mount";
89 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
91 private static final String NULL_VALUE = "null";
93 private static final String MOUNT_MODULE = "yang-ext";
95 private static final String MOUNT_NODE = "mount";
97 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
99 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
101 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
103 private final DOMMountPointService mountService;
104 private final DOMYangTextSourceProvider yangTextSourceProvider;
105 private final ListenerRegistration<SchemaContextListener> listenerRegistration;
106 private volatile SchemaContext globalSchema;
107 private volatile DataNormalizer dataNormalizer;
110 public ControllerContext(final @Reference DOMSchemaService schemaService,
111 final @Reference DOMMountPointService mountService, final @Reference DOMSchemaService domSchemaService) {
112 this.mountService = mountService;
113 this.yangTextSourceProvider = domSchemaService.getExtensions().getInstance(DOMYangTextSourceProvider.class);
115 onGlobalContextUpdated(schemaService.getGlobalContext());
116 listenerRegistration = schemaService.registerSchemaContextListener(this);
122 * @deprecated Just use the
123 * {@link #ControllerContext(DOMSchemaService, DOMMountPointService, DOMSchemaService)}
124 * constructor instead.
127 public static ControllerContext newInstance(final DOMSchemaService schemaService,
128 final DOMMountPointService mountService, final DOMSchemaService domSchemaService) {
129 return new ControllerContext(schemaService, mountService, domSchemaService);
132 private void setGlobalSchema(final SchemaContext globalSchema) {
133 this.globalSchema = globalSchema;
134 this.dataNormalizer = new DataNormalizer(globalSchema);
137 public DOMYangTextSourceProvider getYangTextSourceProvider() {
138 return yangTextSourceProvider;
141 private void checkPreconditions() {
142 if (this.globalSchema == null) {
143 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
149 public void close() {
150 listenerRegistration.close();
153 public void setSchemas(final SchemaContext schemas) {
154 onGlobalContextUpdated(schemas);
157 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
158 return toIdentifier(restconfInstance, false);
161 public SchemaContext getGlobalSchema() {
162 return this.globalSchema;
165 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
166 return toIdentifier(restconfInstance, true);
169 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
170 final boolean toMountPointIdentifier) {
171 checkPreconditions();
173 if (restconfInstance == null) {
174 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
178 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
179 omitFirstAndLastEmptyString(pathArgs);
180 if (pathArgs.isEmpty()) {
184 final String first = pathArgs.iterator().next();
185 final String startModule = toModuleName(first);
186 if (startModule == null) {
187 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
188 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
191 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
192 final Set<Module> latestModule = this.globalSchema.findModules(startModule);
194 if (latestModule.isEmpty()) {
195 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
196 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
199 final InstanceIdentifierContext<?> iiWithSchemaNode =
200 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
202 if (iiWithSchemaNode == null) {
203 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
206 return iiWithSchemaNode;
209 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
210 if (list.isEmpty()) {
214 final String head = list.iterator().next();
215 if (head.isEmpty()) {
219 if (list.isEmpty()) {
223 final String last = list.get(list.size() - 1);
224 if (last.isEmpty()) {
225 list.remove(list.size() - 1);
231 public Module findModuleByName(final String moduleName) {
232 checkPreconditions();
233 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
234 return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
237 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
238 Preconditions.checkArgument(moduleName != null && mountPoint != null);
240 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
241 if (mountPointSchema == null) {
245 return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
248 public Module findModuleByNamespace(final URI namespace) {
249 checkPreconditions();
250 Preconditions.checkArgument(namespace != null);
251 return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
254 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
255 Preconditions.checkArgument(namespace != null && mountPoint != null);
257 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
258 if (mountPointSchema == null) {
262 return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
265 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
266 checkPreconditions();
267 Preconditions.checkArgument(name != null && revision != null);
269 return this.globalSchema.findModule(name, revision).orElse(null);
272 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
273 final Revision revision) {
274 checkPreconditions();
275 Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
277 final SchemaContext schemaContext = mountPoint.getSchemaContext();
278 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
281 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
282 checkPreconditions();
284 final Iterable<PathArgument> elements = path.getPathArguments();
285 final PathArgument head = elements.iterator().next();
286 final QName startQName = head.getNodeType();
287 final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
288 DataNodeContainer node = initialModule;
289 for (final PathArgument element : elements) {
290 final QName _nodeType = element.getNodeType();
291 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
292 if (potentialNode == null || !isListOrContainer(potentialNode)) {
295 node = (DataNodeContainer) potentialNode;
301 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
302 checkPreconditions();
304 final Iterable<PathArgument> elements = path.getPathArguments();
305 final StringBuilder builder = new StringBuilder();
306 final PathArgument head = elements.iterator().next();
307 final QName startQName = head.getNodeType();
308 final SchemaContext schemaContext;
310 schemaContext = mount.getSchemaContext();
312 schemaContext = this.globalSchema;
314 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
315 DataNodeContainer node = initialModule;
316 for (final PathArgument element : elements) {
317 if (!(element instanceof AugmentationIdentifier)) {
318 final QName _nodeType = element.getNodeType();
319 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
320 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)
321 && !(potentialNode instanceof ChoiceSchemaNode)) {
322 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
323 if (potentialNode instanceof DataNodeContainer) {
324 node = (DataNodeContainer) potentialNode;
330 return builder.toString();
333 public String findModuleNameByNamespace(final URI namespace) {
334 checkPreconditions();
336 final Module module = this.findModuleByNamespace(namespace);
337 return module == null ? null : module.getName();
340 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
341 final Module module = this.findModuleByNamespace(mountPoint, namespace);
342 return module == null ? null : module.getName();
345 public URI findNamespaceByModuleName(final String moduleName) {
346 final Module module = this.findModuleByName(moduleName);
347 return module == null ? null : module.getNamespace();
350 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
351 final Module module = this.findModuleByName(mountPoint, moduleName);
352 return module == null ? null : module.getNamespace();
355 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
356 checkPreconditions();
358 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
359 return schemaContext == null ? null : schemaContext.getModules();
362 public Set<Module> getAllModules() {
363 checkPreconditions();
364 return this.globalSchema.getModules();
367 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
368 final Module schema = context.findModule(qname.getModule()).orElse(null);
369 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
372 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
373 final SchemaContext schema;
375 schema = mount.getSchemaContext();
377 checkPreconditions();
378 schema = this.globalSchema;
381 return toRestconfIdentifier(schema, qname);
384 public CharSequence toRestconfIdentifier(final QName qname) {
385 checkPreconditions();
387 return toRestconfIdentifier(this.globalSchema, qname);
390 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
391 if (mountPoint == null) {
395 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
398 public Module getRestconfModule() {
399 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
402 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
403 final Module restconfModule = getRestconfModule();
404 if (restconfModule == null) {
408 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
410 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
411 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
413 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
415 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
416 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
417 return Iterables.getFirst(instanceDataChildrenByName, null);
420 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
421 final String schemaNodeName) {
422 Module restconfModule = inRestconfModule;
423 if (restconfModule == null) {
424 restconfModule = getRestconfModule();
427 if (restconfModule == null) {
431 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
432 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
433 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
434 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
436 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
437 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
438 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
440 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
441 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
442 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
443 return Iterables.getFirst(instances, null);
444 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
445 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
446 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
448 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
449 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
450 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
451 final DataSchemaNode modules = Iterables.getFirst(instances, null);
452 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
453 RestConfModule.STREAM_LIST_SCHEMA_NODE);
454 return Iterables.getFirst(instances, null);
455 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
456 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
457 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
458 return Iterables.getFirst(instances, null);
459 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
460 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
461 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
462 final DataSchemaNode modules = Iterables.getFirst(instances, null);
463 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
464 RestConfModule.MODULE_LIST_SCHEMA_NODE);
465 return Iterables.getFirst(instances, null);
466 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
467 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
468 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
469 return Iterables.getFirst(instances, null);
475 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
476 for (final CaseSchemaNode caze : container.getCases().values()) {
477 final DataSchemaNode ret = childByQName(caze, name);
486 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
487 return container.getDataChildByName(name);
490 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
491 return dataNodeChildByQName(container, name);
494 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
495 return dataNodeChildByQName(container, name);
498 private static DataSchemaNode childByQName(final Module container, final QName name) {
499 return dataNodeChildByQName(container, name);
502 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
507 private static DataSchemaNode childByQName(final Object container, final QName name) {
508 if (container instanceof CaseSchemaNode) {
509 return childByQName((CaseSchemaNode) container, name);
510 } else if (container instanceof ChoiceSchemaNode) {
511 return childByQName((ChoiceSchemaNode) container, name);
512 } else if (container instanceof ContainerSchemaNode) {
513 return childByQName((ContainerSchemaNode) container, name);
514 } else if (container instanceof ListSchemaNode) {
515 return childByQName((ListSchemaNode) container, name);
516 } else if (container instanceof DataSchemaNode) {
517 return childByQName((DataSchemaNode) container, name);
518 } else if (container instanceof Module) {
519 return childByQName((Module) container, name);
521 throw new IllegalArgumentException("Unhandled parameter types: "
522 + Arrays.asList(container, name).toString());
526 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
527 final DataSchemaNode ret = container.getDataChildByName(name);
529 for (final DataSchemaNode node : container.getChildNodes()) {
530 if (node instanceof ChoiceSchemaNode) {
531 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
532 final DataSchemaNode childByQName = childByQName(choiceNode, name);
533 if (childByQName != null) {
542 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
543 throws UnsupportedEncodingException {
544 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
545 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
546 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
549 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
550 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
551 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
552 final boolean returnJustMountPoint) {
553 Preconditions.checkNotNull(strings);
555 if (parentNode == null) {
559 if (strings.isEmpty()) {
560 return createContext(builder.build(), (DataSchemaNode) parentNode,
561 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
564 final String head = strings.iterator().next();
565 final String nodeName = toNodeName(head);
566 final String moduleName = toModuleName(head);
568 DataSchemaNode targetNode = null;
569 if (!Strings.isNullOrEmpty(moduleName)) {
570 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
571 if (mountPoint != null) {
572 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
573 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
576 if (this.mountService == null) {
577 throw new RestconfDocumentedException(
578 "MountService was not found. Finding behind mount points does not work.",
579 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
582 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
583 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
584 if (!mountOpt.isPresent()) {
585 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
586 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
587 ErrorTag.DATA_MISSING);
589 final DOMMountPoint mount = mountOpt.get();
591 final SchemaContext mountPointSchema = mount.getSchemaContext();
592 if (mountPointSchema == null) {
593 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
594 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
597 if (returnJustMountPoint || strings.size() == 1) {
598 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
599 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
602 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
603 if (moduleNameBehindMountPoint == null) {
604 throw new RestconfDocumentedException(
605 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
606 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
609 final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
611 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
612 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
615 final List<String> subList = strings.subList(1, strings.size());
616 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
617 returnJustMountPoint);
620 Module module = null;
621 if (mountPoint == null) {
622 checkPreconditions();
623 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
624 if (module == null) {
625 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
626 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
629 final SchemaContext schemaContext = mountPoint.getSchemaContext();
630 if (schemaContext != null) {
631 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
635 if (module == null) {
636 throw new RestconfDocumentedException("\"" + moduleName
637 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
641 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
643 if (targetNode == null && parentNode instanceof Module) {
644 final RpcDefinition rpc;
645 if (mountPoint == null) {
646 rpc = getRpcDefinition(head, module.getRevision());
648 final String rpcName = toNodeName(head);
649 rpc = getRpcDefinition(module, rpcName);
652 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
653 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
657 if (targetNode == null) {
658 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
659 + "\" was not found in parent data node.\n" + " 2. \"" + head
660 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
661 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
664 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
665 if (potentialSchemaNodes.size() > 1) {
666 final StringBuilder strBuilder = new StringBuilder();
667 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
668 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
671 throw new RestconfDocumentedException(
672 "URI has bad format. Node \""
673 + nodeName + "\" is added as augment from more than one module. "
674 + "Therefore the node must have module name "
675 + "and it has to be in format \"moduleName:nodeName\"."
676 + "\nThe node is added as augment from modules with namespaces:\n"
677 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
680 if (potentialSchemaNodes.isEmpty()) {
681 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
682 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
685 targetNode = potentialSchemaNodes.iterator().next();
688 if (!isListOrContainer(targetNode)) {
689 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
690 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
694 if (targetNode instanceof ListSchemaNode) {
695 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
696 final int keysSize = listNode.getKeyDefinition().size();
697 if (strings.size() - consumed < keysSize) {
698 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
699 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
702 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
703 final HashMap<QName, Object> keyValues = new HashMap<>();
705 for (final QName key : listNode.getKeyDefinition()) {
707 final String uriKeyValue = uriKeyValues.get(index);
708 if (uriKeyValue.equals(NULL_VALUE)) {
709 throw new RestconfDocumentedException("URI has bad format. List \""
710 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
711 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
714 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
719 consumed = consumed + index;
720 builder.nodeWithKey(targetNode.getQName(), keyValues);
722 builder.node(targetNode.getQName());
725 if (targetNode instanceof DataNodeContainer) {
726 final List<String> remaining = strings.subList(consumed, strings.size());
727 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
728 returnJustMountPoint);
731 return createContext(builder.build(), targetNode, mountPoint,
732 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
735 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
736 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
737 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
738 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
741 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
742 final String name, final URI namespace) {
743 Preconditions.checkNotNull(namespace);
745 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
746 node -> namespace.equals(node.getQName().getNamespace()));
747 return Iterables.getFirst(result, null);
750 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
752 Preconditions.checkNotNull(container);
753 Preconditions.checkNotNull(name);
755 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
756 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
757 return instantiatedDataNodeContainers;
760 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
761 final DataNodeContainer container, final String name) {
763 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
764 node -> name.equals(node.getQName().getLocalName()));
766 // Can't combine this loop with the filter above because the filter is
767 // lazily-applied by Iterables.filter.
768 for (final DataSchemaNode potentialNode : nodes) {
769 if (isInstantiatedDataSchema(potentialNode)) {
770 potentialSchemaNodes.add(potentialNode);
774 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
775 ChoiceSchemaNode.class);
776 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
777 choice -> choice.getCases().values());
778 for (final CaseSchemaNode caze : Iterables.concat(map)) {
779 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
783 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
784 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
785 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
786 || node instanceof AnyXmlSchemaNode;
789 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
790 final DOMMountPoint mountPoint) {
791 Preconditions.checkNotNull(uriValue);
792 Preconditions.checkArgument(node instanceof LeafSchemaNode);
794 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
795 final String urlDecoded = urlPathArgDecode(uriValue);
796 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
797 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
798 if (baseType instanceof LeafrefTypeDefinition) {
799 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
801 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
802 Object decoded = codec.deserialize(urlDecoded);
803 String additionalInfo = "";
804 if (decoded == null) {
805 if (typedef instanceof IdentityrefTypeDefinition) {
806 decoded = toQName(schemaContext, urlDecoded);
808 "For key which is of type identityref it should be in format module_name:identity_name.";
812 if (decoded == null) {
813 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
814 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
817 map.put(node.getQName(), decoded);
820 private static String toModuleName(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(0, idx);
834 private static String toNodeName(final String str) {
835 final int idx = str.indexOf(':');
840 // Make sure there is only one occurrence
841 if (str.indexOf(':', idx + 1) != -1) {
845 return str.substring(idx + 1);
848 private QName toQName(final SchemaContext schemaContext, final String name,
849 final java.util.Optional<Revision> revisionDate) {
850 checkPreconditions();
851 final String module = toModuleName(name);
852 final String node = toNodeName(name);
853 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
854 return m == null ? null : QName.create(m.getQNameModule(), node);
857 private QName toQName(final SchemaContext schemaContext, final String name) {
858 checkPreconditions();
859 final String module = toModuleName(name);
860 final String node = toNodeName(name);
861 final Set<Module> modules = schemaContext.findModules(module);
862 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
865 private static boolean isListOrContainer(final DataSchemaNode node) {
866 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
869 public RpcDefinition getRpcDefinition(final String name, final java.util.Optional<Revision> revisionDate) {
870 final QName validName = toQName(this.globalSchema, name, revisionDate);
871 return validName == null ? null : this.qnameToRpc.get().get(validName);
874 public RpcDefinition getRpcDefinition(final String name) {
875 final QName validName = toQName(this.globalSchema, name);
876 return validName == null ? null : this.qnameToRpc.get().get(validName);
879 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
880 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
881 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
882 if (rpcQName.equals(rpcDefinition.getQName())) {
883 return rpcDefinition;
890 public void onGlobalContextUpdated(final SchemaContext context) {
891 if (context != null) {
892 final Collection<RpcDefinition> defs = context.getOperations();
893 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
895 for (final RpcDefinition operation : defs) {
896 newMap.put(operation.getQName(), operation);
899 // FIXME: still not completely atomic
900 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
901 setGlobalSchema(context);
905 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
907 final List<String> decodedPathArgs = new ArrayList<>();
908 for (final String pathArg : strings) {
909 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
910 decodedPathArgs.add(_decode);
912 return decodedPathArgs;
913 } catch (final UnsupportedEncodingException e) {
914 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
915 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
919 public String urlPathArgDecode(final String pathArg) {
920 if (pathArg != null) {
922 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
923 } catch (final UnsupportedEncodingException e) {
924 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
925 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
932 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
933 final DOMMountPoint mount) {
934 if (argument instanceof NodeIdentifier) {
935 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
936 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
937 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
938 (ListSchemaNode) node, mount);
939 } else if (argument != null && node != null) {
940 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
942 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
946 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
947 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
950 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
951 final ListSchemaNode node, final DOMMountPoint mount) {
952 final QName nodeType = argument.getNodeType();
953 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
954 final Map<QName, Object> keyValues = argument.getKeyValues();
956 final StringBuilder builder = new StringBuilder();
958 builder.append(nodeIdentifier);
961 final List<QName> keyDefinition = node.getKeyDefinition();
962 boolean hasElements = false;
963 for (final QName key : keyDefinition) {
964 for (final DataSchemaNode listChild : node.getChildNodes()) {
965 if (listChild.getQName().equals(key)) {
973 Preconditions.checkState(listChild instanceof LeafSchemaNode,
974 "List key has to consist of leaves, not %s", listChild);
975 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
976 } catch (final UnsupportedEncodingException e) {
977 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
985 return builder.toString();
988 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
990 return this.dataNormalizer.toNormalized(legacy);
991 } catch (final NullPointerException e) {
992 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
996 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
998 return this.dataNormalizer.toLegacy(instanceIdentifier);
999 } catch (final NullPointerException e) {
1000 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
1001 } catch (final DataNormalizationException e) {
1002 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1006 public boolean isNodeMixin(final YangInstanceIdentifier path) {
1007 final DataNormalizationOperation<?> operation;
1009 operation = this.dataNormalizer.getOperation(path);
1010 } catch (final DataNormalizationException e) {
1011 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1013 return operation.isMixin();
1016 public DataNormalizationOperation<?> getRootOperation() {
1017 return this.dataNormalizer.getRootOperation();