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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.Iterables;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.io.Closeable;
20 import java.io.UnsupportedEncodingException;
22 import java.net.URLDecoder;
23 import java.net.URLEncoder;
24 import java.nio.charset.StandardCharsets;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Optional;
34 import java.util.concurrent.atomic.AtomicReference;
35 import javax.annotation.PreDestroy;
36 import javax.inject.Inject;
37 import javax.inject.Singleton;
38 import javax.ws.rs.core.Response.Status;
39 import org.apache.aries.blueprint.annotation.service.Reference;
40 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
41 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
42 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
43 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
44 import org.opendaylight.netconf.sal.rest.api.Draft02;
45 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
46 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
47 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
48 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
49 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
50 import org.opendaylight.restconf.common.util.RestUtil;
51 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
52 import org.opendaylight.yangtools.concepts.ListenerRegistration;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.Revision;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
61 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
66 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
68 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
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.TypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 public final class ControllerContext implements EffectiveModelContextListener, Closeable {
85 // FIXME: this should be in md-sal somewhere
86 public static final String MOUNT = "yang-ext:mount";
88 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
90 private static final String NULL_VALUE = "null";
92 private static final String MOUNT_MODULE = "yang-ext";
94 private static final String MOUNT_NODE = "mount";
96 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
98 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
100 private final DOMMountPointService mountService;
101 private final DOMYangTextSourceProvider yangTextSourceProvider;
102 private final ListenerRegistration<?> listenerRegistration;
103 private volatile EffectiveModelContext globalSchema;
104 private volatile DataNormalizer dataNormalizer;
107 public ControllerContext(final @Reference DOMSchemaService schemaService,
108 final @Reference DOMMountPointService mountService, final @Reference DOMSchemaService domSchemaService) {
109 this.mountService = mountService;
110 this.yangTextSourceProvider = domSchemaService.getExtensions().getInstance(DOMYangTextSourceProvider.class);
112 onModelContextUpdated(schemaService.getGlobalContext());
113 listenerRegistration = schemaService.registerSchemaContextListener(this);
119 * @deprecated Just use the
120 * {@link #ControllerContext(DOMSchemaService, DOMMountPointService, DOMSchemaService)}
121 * constructor instead.
124 public static ControllerContext newInstance(final DOMSchemaService schemaService,
125 final DOMMountPointService mountService, final DOMSchemaService domSchemaService) {
126 return new ControllerContext(schemaService, mountService, domSchemaService);
129 private void setGlobalSchema(final EffectiveModelContext globalSchema) {
130 this.globalSchema = globalSchema;
131 this.dataNormalizer = new DataNormalizer(globalSchema);
134 public DOMYangTextSourceProvider getYangTextSourceProvider() {
135 return yangTextSourceProvider;
138 private void checkPreconditions() {
139 if (this.globalSchema == null) {
140 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
146 public void close() {
147 listenerRegistration.close();
150 public void setSchemas(final EffectiveModelContext schemas) {
151 onModelContextUpdated(schemas);
154 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
155 return toIdentifier(restconfInstance, false);
158 public EffectiveModelContext getGlobalSchema() {
159 return this.globalSchema;
162 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
163 return toIdentifier(restconfInstance, true);
166 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
167 final boolean toMountPointIdentifier) {
168 checkPreconditions();
170 if (restconfInstance == null) {
171 return new InstanceIdentifierContext<>(YangInstanceIdentifier.empty(), this.globalSchema, null,
175 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
176 omitFirstAndLastEmptyString(pathArgs);
177 if (pathArgs.isEmpty()) {
181 final String first = pathArgs.iterator().next();
182 final String startModule = toModuleName(first);
183 if (startModule == null) {
184 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
185 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
188 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
189 final Collection<? extends Module> latestModule = this.globalSchema.findModules(startModule);
191 if (latestModule.isEmpty()) {
192 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
193 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
196 final InstanceIdentifierContext<?> iiWithSchemaNode =
197 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
199 if (iiWithSchemaNode == null) {
200 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
203 return iiWithSchemaNode;
206 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
207 if (list.isEmpty()) {
211 final String head = list.iterator().next();
212 if (head.isEmpty()) {
216 if (list.isEmpty()) {
220 final String last = list.get(list.size() - 1);
221 if (last.isEmpty()) {
222 list.remove(list.size() - 1);
228 public Module findModuleByName(final String moduleName) {
229 checkPreconditions();
230 checkArgument(moduleName != null && !moduleName.isEmpty());
231 return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
234 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
235 checkArgument(moduleName != null && mountPoint != null);
237 final SchemaContext mountPointSchema = getModelContext(mountPoint);
238 if (mountPointSchema == null) {
242 return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
245 public Module findModuleByNamespace(final URI namespace) {
246 checkPreconditions();
247 checkArgument(namespace != null);
248 return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
251 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
252 checkArgument(namespace != null && mountPoint != null);
254 final SchemaContext mountPointSchema = getModelContext(mountPoint);
255 if (mountPointSchema == null) {
259 return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
262 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
263 checkPreconditions();
264 checkArgument(name != null && revision != null);
266 return this.globalSchema.findModule(name, revision).orElse(null);
269 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
270 final Revision revision) {
271 checkPreconditions();
272 checkArgument(name != null && revision != null && mountPoint != null);
274 final SchemaContext schemaContext = getModelContext(mountPoint);
275 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
278 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
279 checkPreconditions();
281 final Iterable<PathArgument> elements = path.getPathArguments();
282 final PathArgument head = elements.iterator().next();
283 final QName startQName = head.getNodeType();
284 final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
285 DataNodeContainer node = initialModule;
286 for (final PathArgument element : elements) {
287 final QName _nodeType = element.getNodeType();
288 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
289 if (potentialNode == null || !isListOrContainer(potentialNode)) {
292 node = (DataNodeContainer) potentialNode;
298 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
299 checkPreconditions();
301 final Iterable<PathArgument> elements = path.getPathArguments();
302 final StringBuilder builder = new StringBuilder();
303 final PathArgument head = elements.iterator().next();
304 final QName startQName = head.getNodeType();
305 final SchemaContext schemaContext;
307 schemaContext = getModelContext(mount);
309 schemaContext = this.globalSchema;
311 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
312 DataNodeContainer node = initialModule;
313 for (final PathArgument element : elements) {
314 if (!(element instanceof AugmentationIdentifier)) {
315 final QName _nodeType = element.getNodeType();
316 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
317 if ((!(element instanceof NodeIdentifier) || !(potentialNode instanceof ListSchemaNode))
318 && !(potentialNode instanceof ChoiceSchemaNode)) {
319 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
320 if (potentialNode instanceof DataNodeContainer) {
321 node = (DataNodeContainer) potentialNode;
327 return builder.toString();
330 public String findModuleNameByNamespace(final URI namespace) {
331 checkPreconditions();
333 final Module module = this.findModuleByNamespace(namespace);
334 return module == null ? null : module.getName();
337 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
338 final Module module = this.findModuleByNamespace(mountPoint, namespace);
339 return module == null ? null : module.getName();
342 public URI findNamespaceByModuleName(final String moduleName) {
343 final Module module = this.findModuleByName(moduleName);
344 return module == null ? null : module.getNamespace();
347 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
348 final Module module = this.findModuleByName(mountPoint, moduleName);
349 return module == null ? null : module.getNamespace();
352 public Collection<? extends Module> getAllModules(final DOMMountPoint mountPoint) {
353 checkPreconditions();
355 final SchemaContext schemaContext = mountPoint == null ? null : getModelContext(mountPoint);
356 return schemaContext == null ? null : schemaContext.getModules();
359 public Collection<? extends Module> getAllModules() {
360 checkPreconditions();
361 return this.globalSchema.getModules();
364 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
365 final Module schema = context.findModule(qname.getModule()).orElse(null);
366 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
369 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
370 final SchemaContext schema;
372 schema = getModelContext(mount);
374 checkPreconditions();
375 schema = this.globalSchema;
378 return toRestconfIdentifier(schema, qname);
381 public CharSequence toRestconfIdentifier(final QName qname) {
382 checkPreconditions();
384 return toRestconfIdentifier(this.globalSchema, qname);
387 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
388 if (mountPoint == null) {
392 return toRestconfIdentifier(getModelContext(mountPoint), qname);
395 public Module getRestconfModule() {
396 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
399 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
400 final Module restconfModule = getRestconfModule();
401 if (restconfModule == null) {
405 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
407 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
408 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
410 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
412 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
413 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
414 return Iterables.getFirst(instanceDataChildrenByName, null);
417 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
418 final String schemaNodeName) {
419 Module restconfModule = inRestconfModule;
420 if (restconfModule == null) {
421 restconfModule = getRestconfModule();
424 if (restconfModule == null) {
428 final Collection<? extends GroupingDefinition> groupings = restconfModule.getGroupings();
429 final Iterable<? extends GroupingDefinition> filteredGroups = Iterables.filter(groupings,
430 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
431 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
433 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
434 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
435 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
437 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
438 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
439 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
440 return Iterables.getFirst(instances, null);
441 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
442 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
443 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
444 return Iterables.getFirst(instances, null);
445 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
446 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
447 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
448 final DataSchemaNode modules = Iterables.getFirst(instances, null);
449 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
450 RestConfModule.STREAM_LIST_SCHEMA_NODE);
451 return Iterables.getFirst(instances, null);
452 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
453 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
454 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
455 return Iterables.getFirst(instances, null);
456 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
457 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
458 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
459 final DataSchemaNode modules = Iterables.getFirst(instances, null);
460 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
461 RestConfModule.MODULE_LIST_SCHEMA_NODE);
462 return Iterables.getFirst(instances, null);
463 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
464 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
465 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
466 return Iterables.getFirst(instances, null);
472 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
473 for (final CaseSchemaNode caze : container.getCases()) {
474 final DataSchemaNode ret = childByQName(caze, name);
483 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
484 return container.getDataChildByName(name);
487 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
488 return dataNodeChildByQName(container, name);
491 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
492 return dataNodeChildByQName(container, name);
495 private static DataSchemaNode childByQName(final Module container, final QName name) {
496 return dataNodeChildByQName(container, name);
499 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
504 private static DataSchemaNode childByQName(final Object container, final QName name) {
505 if (container instanceof CaseSchemaNode) {
506 return childByQName((CaseSchemaNode) container, name);
507 } else if (container instanceof ChoiceSchemaNode) {
508 return childByQName((ChoiceSchemaNode) container, name);
509 } else if (container instanceof ContainerSchemaNode) {
510 return childByQName((ContainerSchemaNode) container, name);
511 } else if (container instanceof ListSchemaNode) {
512 return childByQName((ListSchemaNode) container, name);
513 } else if (container instanceof DataSchemaNode) {
514 return childByQName((DataSchemaNode) container, name);
515 } else if (container instanceof Module) {
516 return childByQName((Module) container, name);
518 throw new IllegalArgumentException("Unhandled parameter types: "
519 + Arrays.asList(container, name).toString());
523 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
524 final DataSchemaNode ret = container.getDataChildByName(name);
526 for (final DataSchemaNode node : container.getChildNodes()) {
527 if (node instanceof ChoiceSchemaNode) {
528 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
529 final DataSchemaNode childByQName = childByQName(choiceNode, name);
530 if (childByQName != null) {
539 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
540 throws UnsupportedEncodingException {
541 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
542 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), StandardCharsets.UTF_8);
545 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
546 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
547 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
548 final boolean returnJustMountPoint) {
549 requireNonNull(strings);
551 if (parentNode == null) {
555 if (strings.isEmpty()) {
556 return createContext(builder.build(), (DataSchemaNode) parentNode, mountPoint,
557 mountPoint != null ? getModelContext(mountPoint) : this.globalSchema);
560 final String head = strings.iterator().next();
562 if (head.isEmpty()) {
563 final List<String> remaining = strings.subList(1, strings.size());
564 return collectPathArguments(builder, remaining, parentNode, mountPoint, returnJustMountPoint);
567 final String nodeName = toNodeName(head);
568 final String moduleName = toModuleName(head);
570 DataSchemaNode targetNode = null;
571 if (!Strings.isNullOrEmpty(moduleName)) {
572 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
573 if (mountPoint != null) {
574 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
575 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
578 if (this.mountService == null) {
579 throw new RestconfDocumentedException(
580 "MountService was not found. Finding behind mount points does not work.",
581 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
584 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
585 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
586 if (mountOpt.isEmpty()) {
587 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
588 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
589 ErrorTag.DATA_MISSING);
591 final DOMMountPoint mount = mountOpt.get();
593 final EffectiveModelContext mountPointSchema = getModelContext(mount);
594 if (mountPointSchema == null) {
595 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
596 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
599 if (returnJustMountPoint || strings.size() == 1) {
600 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
601 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount, mountPointSchema);
604 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
605 if (moduleNameBehindMountPoint == null) {
606 throw new RestconfDocumentedException(
607 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
608 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
611 final Iterator<? extends Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint)
614 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
615 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
618 final List<String> subList = strings.subList(1, strings.size());
619 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
620 returnJustMountPoint);
623 Module module = null;
624 if (mountPoint == null) {
625 checkPreconditions();
626 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
627 if (module == null) {
628 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
629 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
632 final EffectiveModelContext schemaContext = getModelContext(mountPoint);
633 if (schemaContext != null) {
634 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
638 if (module == null) {
639 throw new RestconfDocumentedException("\"" + moduleName
640 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
644 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
646 if (targetNode == null && parentNode instanceof Module) {
647 final RpcDefinition rpc;
648 if (mountPoint == null) {
649 rpc = getRpcDefinition(head, module.getRevision());
651 final String rpcName = toNodeName(head);
652 rpc = getRpcDefinition(module, rpcName);
655 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
656 mountPoint != null ? getModelContext(mountPoint) : this.globalSchema);
660 if (targetNode == null) {
661 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
662 + "\" was not found in parent data node.\n" + " 2. \"" + head
663 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
664 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
667 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
668 if (potentialSchemaNodes.size() > 1) {
669 final StringBuilder strBuilder = new StringBuilder();
670 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
671 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
674 throw new RestconfDocumentedException(
675 "URI has bad format. Node \""
676 + nodeName + "\" is added as augment from more than one module. "
677 + "Therefore the node must have module name "
678 + "and it has to be in format \"moduleName:nodeName\"."
679 + "\nThe node is added as augment from modules with namespaces:\n"
680 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
683 if (potentialSchemaNodes.isEmpty()) {
684 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
685 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
688 targetNode = potentialSchemaNodes.iterator().next();
691 if (!isListOrContainer(targetNode)) {
692 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
693 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
697 if (targetNode instanceof ListSchemaNode) {
698 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
699 final int keysSize = listNode.getKeyDefinition().size();
700 if (strings.size() - consumed < keysSize) {
701 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
702 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
705 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
706 final HashMap<QName, Object> keyValues = new HashMap<>();
708 for (final QName key : listNode.getKeyDefinition()) {
710 final String uriKeyValue = uriKeyValues.get(index);
711 if (uriKeyValue.equals(NULL_VALUE)) {
712 throw new RestconfDocumentedException("URI has bad format. List \""
713 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
714 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
717 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
722 consumed = consumed + index;
723 builder.nodeWithKey(targetNode.getQName(), keyValues);
725 builder.node(targetNode.getQName());
728 if (targetNode instanceof DataNodeContainer) {
729 final List<String> remaining = strings.subList(consumed, strings.size());
730 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
731 returnJustMountPoint);
734 return createContext(builder.build(), targetNode, mountPoint,
735 mountPoint != null ? getModelContext(mountPoint) : this.globalSchema);
738 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
739 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint,
740 final EffectiveModelContext schemaContext) {
741 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
742 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
745 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
746 final String name, final URI namespace) {
747 requireNonNull(namespace);
749 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
750 node -> namespace.equals(node.getQName().getNamespace()));
751 return Iterables.getFirst(result, null);
754 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
756 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
757 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
758 requireNonNull(name));
759 return instantiatedDataNodeContainers;
762 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
763 final DataNodeContainer container, final String name) {
765 final Iterable<? extends DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
766 node -> name.equals(node.getQName().getLocalName()));
768 // Can't combine this loop with the filter above because the filter is
769 // lazily-applied by Iterables.filter.
770 for (final DataSchemaNode potentialNode : nodes) {
771 if (isInstantiatedDataSchema(potentialNode)) {
772 potentialSchemaNodes.add(potentialNode);
776 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
777 ChoiceSchemaNode.class);
778 final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
779 ChoiceSchemaNode::getCases);
780 for (final CaseSchemaNode caze : Iterables.concat(map)) {
781 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
785 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
786 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
787 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
788 || node instanceof AnyxmlSchemaNode;
791 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
792 final DOMMountPoint mountPoint) {
793 checkArgument(node instanceof LeafSchemaNode);
795 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : getModelContext(mountPoint);
796 final String urlDecoded = urlPathArgDecode(requireNonNull(uriValue));
797 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
798 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
799 if (baseType instanceof LeafrefTypeDefinition) {
800 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
802 final IllegalArgumentCodec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
803 Object decoded = codec.deserialize(urlDecoded);
804 String additionalInfo = "";
805 if (decoded == null) {
806 if (typedef instanceof IdentityrefTypeDefinition) {
807 decoded = toQName(schemaContext, urlDecoded);
809 "For key which is of type identityref it should be in format module_name:identity_name.";
813 if (decoded == null) {
814 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
815 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
818 map.put(node.getQName(), decoded);
821 private static String toModuleName(final String str) {
822 final int idx = str.indexOf(':');
827 // Make sure there is only one occurrence
828 if (str.indexOf(':', idx + 1) != -1) {
832 return str.substring(0, idx);
835 private static String toNodeName(final String str) {
836 final int idx = str.indexOf(':');
841 // Make sure there is only one occurrence
842 if (str.indexOf(':', idx + 1) != -1) {
846 return str.substring(idx + 1);
849 private QName toQName(final SchemaContext schemaContext, final String name,
850 final Optional<Revision> revisionDate) {
851 checkPreconditions();
852 final String module = toModuleName(name);
853 final String node = toNodeName(name);
854 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
855 return m == null ? null : QName.create(m.getQNameModule(), node);
858 private QName toQName(final SchemaContext schemaContext, final String name) {
859 checkPreconditions();
860 final String module = toModuleName(name);
861 final String node = toNodeName(name);
862 final Collection<? extends Module> modules = schemaContext.findModules(module);
863 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
866 private static boolean isListOrContainer(final DataSchemaNode node) {
867 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
870 public RpcDefinition getRpcDefinition(final String name, final Optional<Revision> revisionDate) {
871 final QName validName = toQName(this.globalSchema, name, revisionDate);
872 return validName == null ? null : this.qnameToRpc.get().get(validName);
875 public RpcDefinition getRpcDefinition(final String name) {
876 final QName validName = toQName(this.globalSchema, name);
877 return validName == null ? null : this.qnameToRpc.get().get(validName);
880 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
881 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
882 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
883 if (rpcQName.equals(rpcDefinition.getQName())) {
884 return rpcDefinition;
891 public void onModelContextUpdated(final EffectiveModelContext context) {
892 if (context != null) {
893 final Collection<? extends RpcDefinition> defs = context.getOperations();
894 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
896 for (final RpcDefinition operation : defs) {
897 newMap.put(operation.getQName(), operation);
900 // FIXME: still not completely atomic
901 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
902 setGlobalSchema(context);
906 private 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, StandardCharsets.UTF_8);
910 decodedPathArgs.add(_decode);
912 return decodedPathArgs;
915 static String urlPathArgDecode(final String pathArg) {
916 if (pathArg == null) {
919 return URLDecoder.decode(pathArg, StandardCharsets.UTF_8);
922 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
923 final DOMMountPoint mount) {
924 if (argument instanceof NodeIdentifier) {
925 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
926 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
927 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
928 (ListSchemaNode) node, mount);
929 } else if (argument != null && node != null) {
930 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
932 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
936 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
937 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
940 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
941 final ListSchemaNode node, final DOMMountPoint mount) {
942 final QName nodeType = argument.getNodeType();
943 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
945 final StringBuilder builder = new StringBuilder().append('/').append(nodeIdentifier).append('/');
947 final List<QName> keyDefinition = node.getKeyDefinition();
948 boolean hasElements = false;
949 for (final QName key : keyDefinition) {
950 for (final DataSchemaNode listChild : node.getChildNodes()) {
951 if (listChild.getQName().equals(key)) {
958 checkState(listChild instanceof LeafSchemaNode,
959 "List key has to consist of leaves, not %s", listChild);
961 final Object value = argument.getValue(key);
963 builder.append(toUriString(value, (LeafSchemaNode)listChild, mount));
964 } catch (final UnsupportedEncodingException e) {
965 LOG.error("Error parsing URI: {}", value, 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 private static EffectiveModelContext getModelContext(final DOMMountPoint mountPoint) {
1005 return mountPoint.getService(DOMSchemaService.class)
1006 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))