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.IllegalArgumentCodec;
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 IllegalArgumentCodec<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();
566 if (head.isEmpty()) {
567 final List<String> remaining = strings.subList(1, strings.size());
568 return collectPathArguments(builder, remaining, parentNode, mountPoint, returnJustMountPoint);
571 final String nodeName = toNodeName(head);
572 final String moduleName = toModuleName(head);
574 DataSchemaNode targetNode = null;
575 if (!Strings.isNullOrEmpty(moduleName)) {
576 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
577 if (mountPoint != null) {
578 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
579 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
582 if (this.mountService == null) {
583 throw new RestconfDocumentedException(
584 "MountService was not found. Finding behind mount points does not work.",
585 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
588 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
589 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
590 if (!mountOpt.isPresent()) {
591 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
592 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
593 ErrorTag.DATA_MISSING);
595 final DOMMountPoint mount = mountOpt.get();
597 final SchemaContext mountPointSchema = mount.getSchemaContext();
598 if (mountPointSchema == null) {
599 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
600 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
603 if (returnJustMountPoint || strings.size() == 1) {
604 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
605 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
608 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
609 if (moduleNameBehindMountPoint == null) {
610 throw new RestconfDocumentedException(
611 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
612 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
615 final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
617 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
618 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
621 final List<String> subList = strings.subList(1, strings.size());
622 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
623 returnJustMountPoint);
626 Module module = null;
627 if (mountPoint == null) {
628 checkPreconditions();
629 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
630 if (module == null) {
631 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
632 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
635 final SchemaContext schemaContext = mountPoint.getSchemaContext();
636 if (schemaContext != null) {
637 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
641 if (module == null) {
642 throw new RestconfDocumentedException("\"" + moduleName
643 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
647 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
649 if (targetNode == null && parentNode instanceof Module) {
650 final RpcDefinition rpc;
651 if (mountPoint == null) {
652 rpc = getRpcDefinition(head, module.getRevision());
654 final String rpcName = toNodeName(head);
655 rpc = getRpcDefinition(module, rpcName);
658 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
659 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
663 if (targetNode == null) {
664 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
665 + "\" was not found in parent data node.\n" + " 2. \"" + head
666 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
667 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
670 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
671 if (potentialSchemaNodes.size() > 1) {
672 final StringBuilder strBuilder = new StringBuilder();
673 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
674 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
677 throw new RestconfDocumentedException(
678 "URI has bad format. Node \""
679 + nodeName + "\" is added as augment from more than one module. "
680 + "Therefore the node must have module name "
681 + "and it has to be in format \"moduleName:nodeName\"."
682 + "\nThe node is added as augment from modules with namespaces:\n"
683 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
686 if (potentialSchemaNodes.isEmpty()) {
687 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
688 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
691 targetNode = potentialSchemaNodes.iterator().next();
694 if (!isListOrContainer(targetNode)) {
695 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
696 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
700 if (targetNode instanceof ListSchemaNode) {
701 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
702 final int keysSize = listNode.getKeyDefinition().size();
703 if (strings.size() - consumed < keysSize) {
704 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
705 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
708 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
709 final HashMap<QName, Object> keyValues = new HashMap<>();
711 for (final QName key : listNode.getKeyDefinition()) {
713 final String uriKeyValue = uriKeyValues.get(index);
714 if (uriKeyValue.equals(NULL_VALUE)) {
715 throw new RestconfDocumentedException("URI has bad format. List \""
716 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
717 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
720 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
725 consumed = consumed + index;
726 builder.nodeWithKey(targetNode.getQName(), keyValues);
728 builder.node(targetNode.getQName());
731 if (targetNode instanceof DataNodeContainer) {
732 final List<String> remaining = strings.subList(consumed, strings.size());
733 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
734 returnJustMountPoint);
737 return createContext(builder.build(), targetNode, mountPoint,
738 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
741 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
742 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
743 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
744 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
747 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
748 final String name, final URI namespace) {
749 Preconditions.checkNotNull(namespace);
751 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
752 node -> namespace.equals(node.getQName().getNamespace()));
753 return Iterables.getFirst(result, null);
756 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
758 Preconditions.checkNotNull(container);
759 Preconditions.checkNotNull(name);
761 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
762 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
763 return instantiatedDataNodeContainers;
766 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
767 final DataNodeContainer container, final String name) {
769 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
770 node -> name.equals(node.getQName().getLocalName()));
772 // Can't combine this loop with the filter above because the filter is
773 // lazily-applied by Iterables.filter.
774 for (final DataSchemaNode potentialNode : nodes) {
775 if (isInstantiatedDataSchema(potentialNode)) {
776 potentialSchemaNodes.add(potentialNode);
780 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
781 ChoiceSchemaNode.class);
782 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
783 choice -> choice.getCases().values());
784 for (final CaseSchemaNode caze : Iterables.concat(map)) {
785 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
789 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
790 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
791 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
792 || node instanceof AnyxmlSchemaNode;
795 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
796 final DOMMountPoint mountPoint) {
797 Preconditions.checkNotNull(uriValue);
798 Preconditions.checkArgument(node instanceof LeafSchemaNode);
800 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
801 final String urlDecoded = urlPathArgDecode(uriValue);
802 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
803 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
804 if (baseType instanceof LeafrefTypeDefinition) {
805 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
807 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
808 Object decoded = codec.deserialize(urlDecoded);
809 String additionalInfo = "";
810 if (decoded == null) {
811 if (typedef instanceof IdentityrefTypeDefinition) {
812 decoded = toQName(schemaContext, urlDecoded);
814 "For key which is of type identityref it should be in format module_name:identity_name.";
818 if (decoded == null) {
819 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
820 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
823 map.put(node.getQName(), decoded);
826 private static String toModuleName(final String str) {
827 final int idx = str.indexOf(':');
832 // Make sure there is only one occurrence
833 if (str.indexOf(':', idx + 1) != -1) {
837 return str.substring(0, idx);
840 private static String toNodeName(final String str) {
841 final int idx = str.indexOf(':');
846 // Make sure there is only one occurrence
847 if (str.indexOf(':', idx + 1) != -1) {
851 return str.substring(idx + 1);
854 private QName toQName(final SchemaContext schemaContext, final String name,
855 final Optional<Revision> revisionDate) {
856 checkPreconditions();
857 final String module = toModuleName(name);
858 final String node = toNodeName(name);
859 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
860 return m == null ? null : QName.create(m.getQNameModule(), node);
863 private QName toQName(final SchemaContext schemaContext, final String name) {
864 checkPreconditions();
865 final String module = toModuleName(name);
866 final String node = toNodeName(name);
867 final Set<Module> modules = schemaContext.findModules(module);
868 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
871 private static boolean isListOrContainer(final DataSchemaNode node) {
872 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
875 public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
876 final QName validName = toQName(this.globalSchema, name, revisionDate);
877 return validName == null ? null : this.qnameToRpc.get().get(validName);
880 public RpcDefinition getRpcDefinition(final String name) {
881 final QName validName = toQName(this.globalSchema, name);
882 return validName == null ? null : this.qnameToRpc.get().get(validName);
885 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
886 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
887 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
888 if (rpcQName.equals(rpcDefinition.getQName())) {
889 return rpcDefinition;
896 public void onGlobalContextUpdated(final SchemaContext context) {
897 if (context != null) {
898 final Collection<RpcDefinition> defs = context.getOperations();
899 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
901 for (final RpcDefinition operation : defs) {
902 newMap.put(operation.getQName(), operation);
905 // FIXME: still not completely atomic
906 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
907 setGlobalSchema(context);
911 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
913 final List<String> decodedPathArgs = new ArrayList<>();
914 for (final String pathArg : strings) {
915 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
916 decodedPathArgs.add(_decode);
918 return decodedPathArgs;
919 } catch (final UnsupportedEncodingException e) {
920 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
921 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
925 public String urlPathArgDecode(final String pathArg) {
926 if (pathArg != null) {
928 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
929 } catch (final UnsupportedEncodingException e) {
930 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
931 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
938 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
939 final DOMMountPoint mount) {
940 if (argument instanceof NodeIdentifier) {
941 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
942 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
943 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
944 (ListSchemaNode) node, mount);
945 } else if (argument != null && node != null) {
946 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
948 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
952 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
953 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
956 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
957 final ListSchemaNode node, final DOMMountPoint mount) {
958 final QName nodeType = argument.getNodeType();
959 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
961 final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
963 final List<QName> keyDefinition = node.getKeyDefinition();
964 boolean hasElements = false;
965 for (final QName key : keyDefinition) {
966 for (final DataSchemaNode listChild : node.getChildNodes()) {
967 if (listChild.getQName().equals(key)) {
974 Preconditions.checkState(listChild instanceof LeafSchemaNode,
975 "List key has to consist of leaves, not %s", listChild);
977 final Object value = argument.getValue(key);
979 builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
980 } catch (final UnsupportedEncodingException e) {
981 LOG.error("Error parsing URI: {}", value, e);
989 return builder.toString();
992 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
994 return this.dataNormalizer.toNormalized(legacy);
995 } catch (final NullPointerException e) {
996 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
1000 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
1002 return this.dataNormalizer.toLegacy(instanceIdentifier);
1003 } catch (final NullPointerException e) {
1004 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
1005 } catch (final DataNormalizationException e) {
1006 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1010 public boolean isNodeMixin(final YangInstanceIdentifier path) {
1011 final DataNormalizationOperation<?> operation;
1013 operation = this.dataNormalizer.getOperation(path);
1014 } catch (final DataNormalizationException e) {
1015 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1017 return operation.isMixin();
1020 public DataNormalizationOperation<?> getRootOperation() {
1021 return this.dataNormalizer.getRootOperation();