2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Splitter;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.Iterables;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.io.Closeable;
18 import java.io.UnsupportedEncodingException;
20 import java.net.URLDecoder;
21 import java.net.URLEncoder;
22 import java.nio.charset.Charset;
23 import java.nio.charset.StandardCharsets;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
33 import java.util.concurrent.atomic.AtomicReference;
34 import javax.ws.rs.core.Response.Status;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
36 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
37 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
38 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
39 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
40 import org.opendaylight.controller.sal.core.api.model.SchemaService;
41 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
42 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
43 import org.opendaylight.netconf.sal.rest.api.Draft02;
44 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
45 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
46 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
47 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
48 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
49 import org.opendaylight.restconf.common.util.RestUtil;
50 import org.opendaylight.yangtools.concepts.Codec;
51 import org.opendaylight.yangtools.concepts.ListenerRegistration;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.Revision;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
60 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
67 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.Module;
71 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
74 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
81 public final class ControllerContext implements SchemaContextListener, Closeable {
82 // FIXME: this should be in md-sal somewhere
83 public static final String MOUNT = "yang-ext:mount";
85 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
87 private static final String NULL_VALUE = "null";
89 private static final String MOUNT_MODULE = "yang-ext";
91 private static final String MOUNT_NODE = "mount";
93 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
95 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
97 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
99 private final DOMMountPointService mountService;
100 private final DOMYangTextSourceProvider yangTextSourceProvider;
101 private final ListenerRegistration<SchemaContextListener> listenerRegistration;
102 private volatile SchemaContext globalSchema;
103 private volatile DataNormalizer dataNormalizer;
105 private ControllerContext(SchemaService schemaService, DOMMountPointService mountService,
106 DOMYangTextSourceProvider yangTextSourceProvider) {
107 this.mountService = mountService;
108 this.yangTextSourceProvider = yangTextSourceProvider;
110 onGlobalContextUpdated(schemaService.getGlobalContext());
111 listenerRegistration = schemaService.registerSchemaContextListener(this);
114 public static ControllerContext newInstance(SchemaService schemaService, DOMMountPointService mountService,
115 DOMSchemaService domSchemaService) {
116 final DOMYangTextSourceProvider yangTextSourceProvider =
117 (DOMYangTextSourceProvider) domSchemaService.getSupportedExtensions().get(DOMYangTextSourceProvider.class);
119 return new ControllerContext(schemaService, mountService, yangTextSourceProvider);
122 private void setGlobalSchema(final SchemaContext globalSchema) {
123 this.globalSchema = globalSchema;
124 this.dataNormalizer = new DataNormalizer(globalSchema);
127 public DOMYangTextSourceProvider getYangTextSourceProvider() {
128 return yangTextSourceProvider;
131 private void checkPreconditions() {
132 if (this.globalSchema == null) {
133 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
138 public void close() {
139 listenerRegistration.close();
142 public void setSchemas(final SchemaContext schemas) {
143 onGlobalContextUpdated(schemas);
146 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
147 return toIdentifier(restconfInstance, false);
150 public SchemaContext getGlobalSchema() {
151 return this.globalSchema;
154 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
155 return toIdentifier(restconfInstance, true);
158 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
159 final boolean toMountPointIdentifier) {
160 checkPreconditions();
162 if (restconfInstance == null) {
163 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
167 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
168 omitFirstAndLastEmptyString(pathArgs);
169 if (pathArgs.isEmpty()) {
173 final String first = pathArgs.iterator().next();
174 final String startModule = toModuleName(first);
175 if (startModule == null) {
176 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
177 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
180 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
181 final Set<Module> latestModule = this.globalSchema.findModules(startModule);
183 if (latestModule.isEmpty()) {
184 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
185 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
188 final InstanceIdentifierContext<?> iiWithSchemaNode =
189 collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier);
191 if (iiWithSchemaNode == null) {
192 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
195 return iiWithSchemaNode;
198 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
199 if (list.isEmpty()) {
203 final String head = list.iterator().next();
204 if (head.isEmpty()) {
208 if (list.isEmpty()) {
212 final String last = list.get(list.size() - 1);
213 if (last.isEmpty()) {
214 list.remove(list.size() - 1);
220 public Module findModuleByName(final String moduleName) {
221 checkPreconditions();
222 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
223 return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
226 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
227 Preconditions.checkArgument(moduleName != null && mountPoint != null);
229 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
230 if (mountPointSchema == null) {
234 return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null);
237 public Module findModuleByNamespace(final URI namespace) {
238 checkPreconditions();
239 Preconditions.checkArgument(namespace != null);
240 return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null);
243 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
244 Preconditions.checkArgument(namespace != null && mountPoint != null);
246 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
247 if (mountPointSchema == null) {
251 return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null);
254 public Module findModuleByNameAndRevision(final String name, final Revision revision) {
255 checkPreconditions();
256 Preconditions.checkArgument(name != null && revision != null);
258 return this.globalSchema.findModule(name, revision).orElse(null);
261 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name,
262 final Revision revision) {
263 checkPreconditions();
264 Preconditions.checkArgument(name != null && revision != null && mountPoint != null);
266 final SchemaContext schemaContext = mountPoint.getSchemaContext();
267 return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null);
270 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
271 checkPreconditions();
273 final Iterable<PathArgument> elements = path.getPathArguments();
274 final PathArgument head = elements.iterator().next();
275 final QName startQName = head.getNodeType();
276 final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null);
277 DataNodeContainer node = initialModule;
278 for (final PathArgument element : elements) {
279 final QName _nodeType = element.getNodeType();
280 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
281 if (potentialNode == null || !isListOrContainer(potentialNode)) {
284 node = (DataNodeContainer) potentialNode;
290 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
291 checkPreconditions();
293 final Iterable<PathArgument> elements = path.getPathArguments();
294 final StringBuilder builder = new StringBuilder();
295 final PathArgument head = elements.iterator().next();
296 final QName startQName = head.getNodeType();
297 final SchemaContext schemaContext;
299 schemaContext = mount.getSchemaContext();
301 schemaContext = this.globalSchema;
303 final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null);
304 DataNodeContainer node = initialModule;
305 for (final PathArgument element : elements) {
306 if (!(element instanceof AugmentationIdentifier)) {
307 final QName _nodeType = element.getNodeType();
308 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
309 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)
310 && !(potentialNode instanceof ChoiceSchemaNode)) {
311 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
312 if (potentialNode instanceof DataNodeContainer) {
313 node = (DataNodeContainer) potentialNode;
319 return builder.toString();
322 public String findModuleNameByNamespace(final URI namespace) {
323 checkPreconditions();
325 final Module module = this.findModuleByNamespace(namespace);
326 return module == null ? null : module.getName();
329 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
330 final Module module = this.findModuleByNamespace(mountPoint, namespace);
331 return module == null ? null : module.getName();
334 public URI findNamespaceByModuleName(final String moduleName) {
335 final Module module = this.findModuleByName(moduleName);
336 return module == null ? null : module.getNamespace();
339 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
340 final Module module = this.findModuleByName(mountPoint, moduleName);
341 return module == null ? null : module.getNamespace();
344 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
345 checkPreconditions();
347 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
348 return schemaContext == null ? null : schemaContext.getModules();
351 public Set<Module> getAllModules() {
352 checkPreconditions();
353 return this.globalSchema.getModules();
356 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
357 final Module schema = context.findModule(qname.getModule()).orElse(null);
358 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
361 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
362 final SchemaContext schema;
364 schema = mount.getSchemaContext();
366 checkPreconditions();
367 schema = this.globalSchema;
370 return toRestconfIdentifier(schema, qname);
373 public CharSequence toRestconfIdentifier(final QName qname) {
374 checkPreconditions();
376 return toRestconfIdentifier(this.globalSchema, qname);
379 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
380 if (mountPoint == null) {
384 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
387 public Module getRestconfModule() {
388 return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION));
391 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
392 final Module restconfModule = getRestconfModule();
393 if (restconfModule == null) {
397 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
399 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
400 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
402 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
404 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
405 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
406 return Iterables.getFirst(instanceDataChildrenByName, null);
409 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
410 final String schemaNodeName) {
411 Module restconfModule = inRestconfModule;
412 if (restconfModule == null) {
413 restconfModule = getRestconfModule();
416 if (restconfModule == null) {
420 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
421 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
422 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
423 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
425 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
426 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
427 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
429 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
430 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
431 (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
432 return Iterables.getFirst(instances, null);
433 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
434 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
435 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
436 return Iterables.getFirst(instances, null);
437 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
438 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
439 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
440 final DataSchemaNode modules = Iterables.getFirst(instances, null);
441 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
442 RestConfModule.STREAM_LIST_SCHEMA_NODE);
443 return Iterables.getFirst(instances, null);
444 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
445 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
446 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
448 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
449 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
450 (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
451 final DataSchemaNode modules = Iterables.getFirst(instances, null);
452 instances = findInstanceDataChildrenByName((DataNodeContainer) modules,
453 RestConfModule.MODULE_LIST_SCHEMA_NODE);
454 return Iterables.getFirst(instances, null);
455 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
456 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
457 (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
458 return Iterables.getFirst(instances, null);
464 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
465 for (final CaseSchemaNode caze : container.getCases().values()) {
466 final DataSchemaNode ret = childByQName(caze, name);
475 private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) {
476 return container.getDataChildByName(name);
479 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
480 return dataNodeChildByQName(container, name);
483 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
484 return dataNodeChildByQName(container, name);
487 private static DataSchemaNode childByQName(final Module container, final QName name) {
488 return dataNodeChildByQName(container, name);
491 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
496 private static DataSchemaNode childByQName(final Object container, final QName name) {
497 if (container instanceof CaseSchemaNode) {
498 return childByQName((CaseSchemaNode) container, name);
499 } else if (container instanceof ChoiceSchemaNode) {
500 return childByQName((ChoiceSchemaNode) container, name);
501 } else if (container instanceof ContainerSchemaNode) {
502 return childByQName((ContainerSchemaNode) container, name);
503 } else if (container instanceof ListSchemaNode) {
504 return childByQName((ListSchemaNode) container, name);
505 } else if (container instanceof DataSchemaNode) {
506 return childByQName((DataSchemaNode) container, name);
507 } else if (container instanceof Module) {
508 return childByQName((Module) container, name);
510 throw new IllegalArgumentException("Unhandled parameter types: "
511 + Arrays.<Object>asList(container, name).toString());
515 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
516 final DataSchemaNode ret = container.getDataChildByName(name);
518 for (final DataSchemaNode node : container.getChildNodes()) {
519 if (node instanceof ChoiceSchemaNode) {
520 final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node;
521 final DataSchemaNode childByQName = childByQName(choiceNode, name);
522 if (childByQName != null) {
531 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
532 throws UnsupportedEncodingException {
533 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
534 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
535 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
538 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Unrecognised NullableDecl")
539 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
540 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
541 final boolean returnJustMountPoint) {
542 Preconditions.<List<String>>checkNotNull(strings);
544 if (parentNode == null) {
548 if (strings.isEmpty()) {
549 return createContext(builder.build(), (DataSchemaNode) parentNode,
550 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
553 final String head = strings.iterator().next();
554 final String nodeName = toNodeName(head);
555 final String moduleName = toModuleName(head);
557 DataSchemaNode targetNode = null;
558 if (!Strings.isNullOrEmpty(moduleName)) {
559 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
560 if (mountPoint != null) {
561 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
562 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
565 if (this.mountService == null) {
566 throw new RestconfDocumentedException(
567 "MountService was not found. Finding behind mount points does not work.",
568 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
571 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
572 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
573 if (!mountOpt.isPresent()) {
574 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
575 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
576 ErrorTag.DATA_MISSING);
578 final DOMMountPoint mount = mountOpt.get();
580 final SchemaContext mountPointSchema = mount.getSchemaContext();
581 if (mountPointSchema == null) {
582 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
583 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
586 if (returnJustMountPoint || strings.size() == 1) {
587 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
588 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
591 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
592 if (moduleNameBehindMountPoint == null) {
593 throw new RestconfDocumentedException(
594 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
595 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
598 final Iterator<Module> it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator();
600 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
601 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
604 final List<String> subList = strings.subList(1, strings.size());
605 return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount,
606 returnJustMountPoint);
609 Module module = null;
610 if (mountPoint == null) {
611 checkPreconditions();
612 module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null);
613 if (module == null) {
614 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
615 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
618 final SchemaContext schemaContext = mountPoint.getSchemaContext();
619 if (schemaContext != null) {
620 module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null);
624 if (module == null) {
625 throw new RestconfDocumentedException("\"" + moduleName
626 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
630 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
632 if (targetNode == null && parentNode instanceof Module) {
633 final RpcDefinition rpc;
634 if (mountPoint == null) {
635 rpc = getRpcDefinition(head, module.getRevision());
637 final String rpcName = toNodeName(head);
638 rpc = getRpcDefinition(module, rpcName);
641 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
642 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
646 if (targetNode == null) {
647 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
648 + "\" was not found in parent data node.\n" + " 2. \"" + head
649 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
650 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
653 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
654 if (potentialSchemaNodes.size() > 1) {
655 final StringBuilder strBuilder = new StringBuilder();
656 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
657 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
660 throw new RestconfDocumentedException(
661 "URI has bad format. Node \""
662 + nodeName + "\" is added as augment from more than one module. "
663 + "Therefore the node must have module name "
664 + "and it has to be in format \"moduleName:nodeName\"."
665 + "\nThe node is added as augment from modules with namespaces:\n"
666 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
669 if (potentialSchemaNodes.isEmpty()) {
670 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
671 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
674 targetNode = potentialSchemaNodes.iterator().next();
677 if (!isListOrContainer(targetNode)) {
678 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
679 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
683 if (targetNode instanceof ListSchemaNode) {
684 final ListSchemaNode listNode = (ListSchemaNode) targetNode;
685 final int keysSize = listNode.getKeyDefinition().size();
686 if (strings.size() - consumed < keysSize) {
687 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
688 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
691 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
692 final HashMap<QName, Object> keyValues = new HashMap<>();
694 for (final QName key : listNode.getKeyDefinition()) {
696 final String uriKeyValue = uriKeyValues.get(index);
697 if (uriKeyValue.equals(NULL_VALUE)) {
698 throw new RestconfDocumentedException("URI has bad format. List \""
699 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
700 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
703 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
708 consumed = consumed + index;
709 builder.nodeWithKey(targetNode.getQName(), keyValues);
711 builder.node(targetNode.getQName());
714 if (targetNode instanceof DataNodeContainer) {
715 final List<String> remaining = strings.subList(consumed, strings.size());
716 return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint,
717 returnJustMountPoint);
720 return createContext(builder.build(), targetNode, mountPoint,
721 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
724 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
725 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
726 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
727 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
730 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
731 final String name, final URI namespace) {
732 Preconditions.checkNotNull(namespace);
734 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
735 node -> namespace.equals(node.getQName().getNamespace()));
736 return Iterables.getFirst(result, null);
739 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
741 Preconditions.checkNotNull(container);
742 Preconditions.checkNotNull(name);
744 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
745 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
746 return instantiatedDataNodeContainers;
749 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
750 final DataNodeContainer container, final String name) {
752 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
753 node -> name.equals(node.getQName().getLocalName()));
755 // Can't combine this loop with the filter above because the filter is
756 // lazily-applied by Iterables.filter.
757 for (final DataSchemaNode potentialNode : nodes) {
758 if (isInstantiatedDataSchema(potentialNode)) {
759 potentialSchemaNodes.add(potentialNode);
763 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
764 ChoiceSchemaNode.class);
765 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
766 choice -> choice.getCases().values());
767 for (final CaseSchemaNode caze : Iterables.concat(map)) {
768 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
772 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
773 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
774 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
775 || node instanceof AnyXmlSchemaNode;
778 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
779 final DOMMountPoint mountPoint) {
780 Preconditions.checkNotNull(uriValue);
781 Preconditions.checkArgument(node instanceof LeafSchemaNode);
783 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
784 final String urlDecoded = urlPathArgDecode(uriValue);
785 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
786 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
787 if (baseType instanceof LeafrefTypeDefinition) {
788 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
790 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
791 Object decoded = codec.deserialize(urlDecoded);
792 String additionalInfo = "";
793 if (decoded == null) {
794 if (typedef instanceof IdentityrefTypeDefinition) {
795 decoded = toQName(schemaContext, urlDecoded);
797 "For key which is of type identityref it should be in format module_name:identity_name.";
801 if (decoded == null) {
802 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
803 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
806 map.put(node.getQName(), decoded);
809 private static String toModuleName(final String str) {
810 final int idx = str.indexOf(':');
815 // Make sure there is only one occurrence
816 if (str.indexOf(':', idx + 1) != -1) {
820 return str.substring(0, idx);
823 private static String toNodeName(final String str) {
824 final int idx = str.indexOf(':');
829 // Make sure there is only one occurrence
830 if (str.indexOf(':', idx + 1) != -1) {
834 return str.substring(idx + 1);
837 private QName toQName(final SchemaContext schemaContext, final String name,
838 final java.util.Optional<Revision> revisionDate) {
839 checkPreconditions();
840 final String module = toModuleName(name);
841 final String node = toNodeName(name);
842 final Module m = schemaContext.findModule(module, revisionDate).orElse(null);
843 return m == null ? null : QName.create(m.getQNameModule(), node);
846 private QName toQName(final SchemaContext schemaContext, final String name) {
847 checkPreconditions();
848 final String module = toModuleName(name);
849 final String node = toNodeName(name);
850 final Set<Module> modules = schemaContext.findModules(module);
851 return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node);
854 private static boolean isListOrContainer(final DataSchemaNode node) {
855 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
858 public RpcDefinition getRpcDefinition(final String name, final java.util.Optional<Revision> revisionDate) {
859 final QName validName = toQName(this.globalSchema, name, revisionDate);
860 return validName == null ? null : this.qnameToRpc.get().get(validName);
863 public RpcDefinition getRpcDefinition(final String name) {
864 final QName validName = toQName(this.globalSchema, name);
865 return validName == null ? null : this.qnameToRpc.get().get(validName);
868 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
869 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
870 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
871 if (rpcQName.equals(rpcDefinition.getQName())) {
872 return rpcDefinition;
879 public void onGlobalContextUpdated(final SchemaContext context) {
880 if (context != null) {
881 final Collection<RpcDefinition> defs = context.getOperations();
882 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
884 for (final RpcDefinition operation : defs) {
885 newMap.put(operation.getQName(), operation);
888 // FIXME: still not completely atomic
889 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
890 setGlobalSchema(context);
894 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
896 final List<String> decodedPathArgs = new ArrayList<>();
897 for (final String pathArg : strings) {
898 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
899 decodedPathArgs.add(_decode);
901 return decodedPathArgs;
902 } catch (final UnsupportedEncodingException e) {
903 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
904 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
908 public String urlPathArgDecode(final String pathArg) {
909 if (pathArg != null) {
911 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
912 } catch (final UnsupportedEncodingException e) {
913 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
914 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
921 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
922 final DOMMountPoint mount) {
923 if (argument instanceof NodeIdentifier) {
924 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
925 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
926 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
927 (ListSchemaNode) node, mount);
928 } else if (argument != null && node != null) {
929 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
931 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
935 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
936 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
939 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
940 final ListSchemaNode node, final DOMMountPoint mount) {
941 final QName nodeType = argument.getNodeType();
942 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
943 final Map<QName, Object> keyValues = argument.getKeyValues();
945 final StringBuilder builder = new StringBuilder();
947 builder.append(nodeIdentifier);
950 final List<QName> keyDefinition = node.getKeyDefinition();
951 boolean hasElements = false;
952 for (final QName key : keyDefinition) {
953 for (final DataSchemaNode listChild : node.getChildNodes()) {
954 if (listChild.getQName().equals(key)) {
962 Preconditions.checkState(listChild instanceof LeafSchemaNode,
963 "List key has to consist of leaves, not %s", listChild);
964 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
965 } catch (final UnsupportedEncodingException e) {
966 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
974 return builder.toString();
977 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
979 return this.dataNormalizer.toNormalized(legacy);
980 } catch (final NullPointerException e) {
981 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
985 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
987 return this.dataNormalizer.toLegacy(instanceIdentifier);
988 } catch (final NullPointerException e) {
989 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
990 } catch (final DataNormalizationException e) {
991 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
995 public boolean isNodeMixin(final YangInstanceIdentifier path) {
996 final DataNormalizationOperation<?> operation;
998 operation = this.dataNormalizer.getOperation(path);
999 } catch (final DataNormalizationException e) {
1000 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
1002 return operation.isMixin();
1005 public DataNormalizationOperation<?> getRootOperation() {
1006 return this.dataNormalizer.getRootOperation();