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 java.io.UnsupportedEncodingException;
18 import java.net.URLDecoder;
19 import java.net.URLEncoder;
20 import java.nio.charset.Charset;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.List;
31 import java.util.concurrent.atomic.AtomicReference;
32 import javax.ws.rs.core.Response.Status;
33 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
34 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
36 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
38 import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
39 import org.opendaylight.netconf.sal.rest.impl.RestUtil;
40 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
41 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
42 import org.opendaylight.yangtools.concepts.Codec;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class ControllerContext implements SchemaContextListener {
72 // FIXME: this should be in md-sal somewhere
73 public static final String MOUNT = "yang-ext:mount";
75 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
77 // FIXME: this should be the current instance which is mutated
78 private static final ControllerContext INSTANCE = new ControllerContext();
80 private static final String NULL_VALUE = "null";
82 private static final String MOUNT_MODULE = "yang-ext";
84 private static final String MOUNT_NODE = "mount";
86 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
88 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
90 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
92 // FIXME; these three should be final
93 private volatile SchemaContext globalSchema;
94 private volatile DOMMountPointService mountService;
95 private DataNormalizer dataNormalizer;
98 public void setGlobalSchema(final SchemaContext globalSchema) {
99 this.globalSchema = globalSchema;
100 this.dataNormalizer = new DataNormalizer(globalSchema);
103 public void setMountService(final DOMMountPointService mountService) {
104 this.mountService = mountService;
107 private ControllerContext() {
110 public static ControllerContext getInstance() {
114 private void checkPreconditions() {
115 if (this.globalSchema == null) {
116 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
120 public void setSchemas(final SchemaContext schemas) {
121 onGlobalContextUpdated(schemas);
124 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
125 return toIdentifier(restconfInstance, false);
128 public SchemaContext getGlobalSchema() {
129 return this.globalSchema;
132 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
133 return toIdentifier(restconfInstance, true);
136 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
137 checkPreconditions();
139 if(restconfInstance == null) {
140 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
144 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
145 omitFirstAndLastEmptyString(pathArgs);
146 if (pathArgs.isEmpty()) {
150 final String first = pathArgs.iterator().next();
151 final String startModule = toModuleName(first);
152 if (startModule == null) {
153 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
154 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
157 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
158 final Module latestModule = this.globalSchema.findModuleByName(startModule, null);
160 if (latestModule == null) {
161 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
164 final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
165 toMountPointIdentifier);
167 if (iiWithSchemaNode == null) {
168 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
171 return iiWithSchemaNode;
174 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
175 if (list.isEmpty()) {
179 final String head = list.iterator().next();
180 if (head.isEmpty()) {
184 if (list.isEmpty()) {
188 final String last = list.get(list.size() - 1);
189 if (last.isEmpty()) {
190 list.remove(list.size() - 1);
195 public Module findModuleByName(final String moduleName) {
196 checkPreconditions();
197 Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty());
198 return this.globalSchema.findModuleByName(moduleName, null);
201 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
202 Preconditions.checkArgument((moduleName != null) && (mountPoint != null));
204 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
205 if (mountPointSchema == null) {
209 return mountPointSchema.findModuleByName(moduleName, null);
212 public Module findModuleByNamespace(final URI namespace) {
213 checkPreconditions();
214 Preconditions.checkArgument(namespace != null);
215 return this.globalSchema.findModuleByNamespaceAndRevision(namespace, null);
218 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
219 Preconditions.checkArgument((namespace != null) && (mountPoint != null));
221 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
222 if (mountPointSchema == null) {
226 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
229 public Module findModuleByNameAndRevision(final QName module) {
230 checkPreconditions();
231 Preconditions.checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
233 return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
236 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
237 checkPreconditions();
238 Preconditions.checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
239 && (mountPoint != null));
241 final SchemaContext schemaContext = mountPoint.getSchemaContext();
242 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
243 module.getRevision());
246 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
247 checkPreconditions();
249 final Iterable<PathArgument> elements = path.getPathArguments();
250 final PathArgument head = elements.iterator().next();
251 final QName startQName = head.getNodeType();
252 final Module initialModule = this.globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
253 startQName.getRevision());
254 DataNodeContainer node = initialModule;
255 for (final PathArgument element : elements) {
256 final QName _nodeType = element.getNodeType();
257 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
258 if ((potentialNode == null) || !isListOrContainer(potentialNode)) {
261 node = (DataNodeContainer) potentialNode;
267 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
268 checkPreconditions();
270 final Iterable<PathArgument> elements = path.getPathArguments();
271 final StringBuilder builder = new StringBuilder();
272 final PathArgument head = elements.iterator().next();
273 final QName startQName = head.getNodeType();
274 final SchemaContext schemaContext;
276 schemaContext = mount.getSchemaContext();
278 schemaContext = this.globalSchema;
280 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
281 startQName.getRevision());
282 DataNodeContainer node = initialModule;
283 for (final PathArgument element : elements) {
284 if (!(element instanceof AugmentationIdentifier)) {
285 final QName _nodeType = element.getNodeType();
286 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
287 if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode)) &&
288 !(potentialNode instanceof ChoiceSchemaNode)) {
289 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
290 if (potentialNode instanceof DataNodeContainer) {
291 node = (DataNodeContainer) potentialNode;
297 return builder.toString();
300 public String findModuleNameByNamespace(final URI namespace) {
301 checkPreconditions();
303 final Module module = this.findModuleByNamespace(namespace);
304 return module == null ? null : module.getName();
307 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
308 final Module module = this.findModuleByNamespace(mountPoint, namespace);
309 return module == null ? null : module.getName();
312 public URI findNamespaceByModuleName(final String moduleName) {
313 final Module module = this.findModuleByName(moduleName);
314 return module == null ? null : module.getNamespace();
317 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
318 final Module module = this.findModuleByName(mountPoint, moduleName);
319 return module == null ? null : module.getNamespace();
322 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
323 checkPreconditions();
325 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
326 return schemaContext == null ? null : schemaContext.getModules();
329 public Set<Module> getAllModules() {
330 checkPreconditions();
331 return this.globalSchema.getModules();
334 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
335 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
336 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
339 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
340 final SchemaContext schema;
342 schema = mount.getSchemaContext();
344 checkPreconditions();
345 schema = this.globalSchema;
348 return toRestconfIdentifier(schema, qname);
351 public CharSequence toRestconfIdentifier(final QName qname) {
352 checkPreconditions();
354 return toRestconfIdentifier(this.globalSchema, qname);
357 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
358 if (mountPoint == null) {
362 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
365 public Module getRestconfModule() {
366 return findModuleByNameAndRevision(RestConfModule.IETF_RESTCONF_QNAME);
369 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
370 final Module restconfModule = getRestconfModule();
371 if (restconfModule == null) {
375 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
377 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
378 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
380 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
382 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
383 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
384 return Iterables.getFirst(instanceDataChildrenByName, null);
387 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
388 final String schemaNodeName) {
389 Module restconfModule = inRestconfModule;
390 if (restconfModule == null) {
391 restconfModule = getRestconfModule();
394 if (restconfModule == null) {
398 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
399 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
400 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
401 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
403 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
404 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
405 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
407 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
408 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
409 ((DataNodeContainer) restconfContainer), RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
410 return Iterables.getFirst(instances, null);
411 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
412 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
413 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
414 return Iterables.getFirst(instances, null);
415 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
416 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
417 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
418 final DataSchemaNode modules = Iterables.getFirst(instances, null);
419 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
420 RestConfModule.STREAM_LIST_SCHEMA_NODE);
421 return Iterables.getFirst(instances, null);
422 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
423 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
424 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
425 return Iterables.getFirst(instances, null);
426 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
427 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
428 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
429 final DataSchemaNode modules = Iterables.getFirst(instances, null);
430 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
431 RestConfModule.MODULE_LIST_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);
442 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
443 for (final ChoiceCaseNode caze : container.getCases()) {
444 final DataSchemaNode ret = childByQName(caze, name);
453 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
454 return container.getDataChildByName(name);
457 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
458 return dataNodeChildByQName(container, name);
461 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
462 return dataNodeChildByQName(container, name);
465 private static DataSchemaNode childByQName(final Module container, final QName name) {
466 return dataNodeChildByQName(container, name);
469 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
473 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
474 final DataSchemaNode ret = container.getDataChildByName(name);
476 for (final DataSchemaNode node : container.getChildNodes()) {
477 if ((node instanceof ChoiceSchemaNode)) {
478 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
479 final DataSchemaNode childByQName = childByQName(choiceNode, name);
480 if (childByQName != null) {
489 private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
490 throws UnsupportedEncodingException {
491 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
492 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
493 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
496 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
497 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
498 final boolean returnJustMountPoint) {
499 Preconditions.<List<String>> checkNotNull(strings);
501 if (parentNode == null) {
505 if (strings.isEmpty()) {
506 return createContext(builder.build(), ((DataSchemaNode) parentNode),
507 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
510 final String head = strings.iterator().next();
511 final String nodeName = toNodeName(head);
512 final String moduleName = toModuleName(head);
514 DataSchemaNode targetNode = null;
515 if (!Strings.isNullOrEmpty(moduleName)) {
516 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
517 if (mountPoint != null) {
518 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
519 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
522 if (this.mountService == null) {
523 throw new RestconfDocumentedException(
524 "MountService was not found. Finding behind mount points does not work.",
525 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
528 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
529 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
530 if (!mountOpt.isPresent()) {
531 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
532 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
533 ErrorTag.DATA_MISSING);
535 final DOMMountPoint mount = mountOpt.get();
537 final SchemaContext mountPointSchema = mount.getSchemaContext();
538 if (mountPointSchema == null) {
539 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
540 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
543 if (returnJustMountPoint || (strings.size() == 1)) {
544 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
545 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
548 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
549 if (moduleNameBehindMountPoint == null) {
550 throw new RestconfDocumentedException(
551 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
552 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
555 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
556 if (moduleBehindMountPoint == null) {
557 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
558 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
561 final List<String> subList = strings.subList(1, strings.size());
562 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
563 returnJustMountPoint);
566 Module module = null;
567 if (mountPoint == null) {
568 checkPreconditions();
569 module = this.globalSchema.findModuleByName(moduleName, null);
570 if (module == null) {
571 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
572 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
575 final SchemaContext schemaContext = mountPoint.getSchemaContext();
576 if (schemaContext != null) {
577 module = schemaContext.findModuleByName(moduleName, null);
581 if (module == null) {
582 throw new RestconfDocumentedException("\"" + moduleName
583 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
587 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
589 if ((targetNode == null) && (parentNode instanceof Module)) {
590 final RpcDefinition rpc;
591 if (mountPoint == null) {
592 rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
594 final String rpcName = toNodeName(head);
595 ControllerContext.getInstance();
596 rpc = ControllerContext.getRpcDefinition(module, rpcName);
599 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
600 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
604 if (targetNode == null) {
605 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
606 + "\" was not found in parent data node.\n" + " 2. \"" + head
607 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
608 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
611 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
612 if (potentialSchemaNodes.size() > 1) {
613 final StringBuilder strBuilder = new StringBuilder();
614 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
615 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
618 throw new RestconfDocumentedException(
619 "URI has bad format. Node \""
621 + "\" is added as augment from more than one module. "
622 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
623 + "\nThe node is added as augment from modules with namespaces:\n"
624 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
627 if (potentialSchemaNodes.isEmpty()) {
628 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
629 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
632 targetNode = potentialSchemaNodes.iterator().next();
635 if (!isListOrContainer(targetNode)) {
636 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
637 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
641 if ((targetNode instanceof ListSchemaNode)) {
642 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
643 final int keysSize = listNode.getKeyDefinition().size();
644 if ((strings.size() - consumed) < keysSize) {
645 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
646 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
649 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
650 final HashMap<QName, Object> keyValues = new HashMap<>();
652 for (final QName key : listNode.getKeyDefinition()) {
654 final String uriKeyValue = uriKeyValues.get(i);
655 if (uriKeyValue.equals(NULL_VALUE)) {
656 throw new RestconfDocumentedException("URI has bad format. List \""
657 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
658 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
661 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
666 consumed = consumed + i;
667 builder.nodeWithKey(targetNode.getQName(), keyValues);
669 builder.node(targetNode.getQName());
672 if ((targetNode instanceof DataNodeContainer)) {
673 final List<String> remaining = strings.subList(consumed, strings.size());
674 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
675 returnJustMountPoint);
678 return createContext(builder.build(), targetNode, mountPoint,
679 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
682 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
683 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
684 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
685 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
688 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
689 final String name, final URI namespace) {
690 Preconditions.checkNotNull(namespace);
692 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
693 node -> namespace.equals(node.getQName().getNamespace()));
694 return Iterables.getFirst(result, null);
697 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
699 Preconditions.checkNotNull(container);
700 Preconditions.checkNotNull(name);
702 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
703 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
704 return instantiatedDataNodeContainers;
707 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
708 final DataNodeContainer container, final String name) {
710 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
711 node -> name.equals(node.getQName().getLocalName()));
713 // Can't combine this loop with the filter above because the filter is
714 // lazily-applied by Iterables.filter.
715 for (final DataSchemaNode potentialNode : nodes) {
716 if (isInstantiatedDataSchema(potentialNode)) {
717 potentialSchemaNodes.add(potentialNode);
721 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
722 ChoiceSchemaNode.class);
723 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
724 for (final ChoiceCaseNode caze : Iterables.concat(map)) {
725 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
729 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
730 return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode)
731 || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode)
732 || (node instanceof AnyXmlSchemaNode);
735 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
736 final DOMMountPoint mountPoint) {
737 Preconditions.checkNotNull(uriValue);
738 Preconditions.checkArgument((node instanceof LeafSchemaNode));
740 final String urlDecoded = urlPathArgDecode(uriValue);
741 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
742 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
743 if (baseType instanceof LeafrefTypeDefinition) {
744 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, this.globalSchema,
747 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
748 Object decoded = codec.deserialize(urlDecoded);
749 String additionalInfo = "";
750 if (decoded == null) {
751 if ((typedef instanceof IdentityrefTypeDefinition)) {
752 final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
753 decoded = toQName(schemaContext, urlDecoded, null);
755 "For key which is of type identityref it should be in format module_name:identity_name.";
759 if (decoded == null) {
760 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
761 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
764 map.put(node.getQName(), decoded);
767 private static String toModuleName(final String str) {
768 final int idx = str.indexOf(':');
773 // Make sure there is only one occurrence
774 if (str.indexOf(':', idx + 1) != -1) {
778 return str.substring(0, idx);
781 private static String toNodeName(final String str) {
782 final int idx = str.indexOf(':');
787 // Make sure there is only one occurrence
788 if (str.indexOf(':', idx + 1) != -1) {
792 return str.substring(idx + 1);
795 private QName toQName(final SchemaContext schemaContext, final String name, final Date revisionDate) {
796 checkPreconditions();
797 final String module = toModuleName(name);
798 final String node = toNodeName(name);
799 final Module m = schemaContext.findModuleByName(module, revisionDate);
800 return m == null ? null : QName.create(m.getQNameModule(), node);
803 private static boolean isListOrContainer(final DataSchemaNode node) {
804 return (node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode);
807 public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) {
808 final QName validName = toQName(this.globalSchema, name, revisionDate);
809 return validName == null ? null : this.qnameToRpc.get().get(validName);
812 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
813 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
814 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
815 if (rpcQName.equals(rpcDefinition.getQName())) {
816 return rpcDefinition;
823 public void onGlobalContextUpdated(final SchemaContext context) {
824 if (context != null) {
825 final Collection<RpcDefinition> defs = context.getOperations();
826 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
828 for (final RpcDefinition operation : defs) {
829 newMap.put(operation.getQName(), operation);
832 // FIXME: still not completely atomic
833 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
834 setGlobalSchema(context);
838 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
840 final List<String> decodedPathArgs = new ArrayList<>();
841 for (final String pathArg : strings) {
842 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
843 decodedPathArgs.add(_decode);
845 return decodedPathArgs;
846 } catch (final UnsupportedEncodingException e) {
847 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
848 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
852 public String urlPathArgDecode(final String pathArg) {
853 if (pathArg != null) {
855 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
856 } catch (final UnsupportedEncodingException e) {
857 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
858 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
865 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
866 final DOMMountPoint mount) {
867 if (argument instanceof NodeIdentifier) {
868 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
869 } else if ((argument instanceof NodeIdentifierWithPredicates) && (node instanceof ListSchemaNode)) {
870 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
871 (ListSchemaNode) node, mount);
872 } else if ((argument != null) && (node != null)) {
873 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
875 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
879 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
880 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
883 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
884 final ListSchemaNode node, final DOMMountPoint mount) {
885 final QName nodeType = argument.getNodeType();
886 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
887 final Map<QName, Object> keyValues = argument.getKeyValues();
889 final StringBuilder builder = new StringBuilder();
891 builder.append(nodeIdentifier);
894 final List<QName> keyDefinition = node.getKeyDefinition();
895 boolean hasElements = false;
896 for (final QName key : keyDefinition) {
897 for (final DataSchemaNode listChild : node.getChildNodes()) {
898 if (listChild.getQName().equals(key)) {
906 Preconditions.checkState(listChild instanceof LeafSchemaNode,
907 "List key has to consist of leaves, not %s", listChild);
908 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
909 } catch (final UnsupportedEncodingException e) {
910 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
918 return builder.toString();
921 private static DataSchemaNode childByQName(final Object container, final QName name) {
922 if (container instanceof ChoiceCaseNode) {
923 return childByQName((ChoiceCaseNode) container, name);
924 } else if (container instanceof ChoiceSchemaNode) {
925 return childByQName((ChoiceSchemaNode) container, name);
926 } else if (container instanceof ContainerSchemaNode) {
927 return childByQName((ContainerSchemaNode) container, name);
928 } else if (container instanceof ListSchemaNode) {
929 return childByQName((ListSchemaNode) container, name);
930 } else if (container instanceof DataSchemaNode) {
931 return childByQName((DataSchemaNode) container, name);
932 } else if (container instanceof Module) {
933 return childByQName((Module) container, name);
935 throw new IllegalArgumentException("Unhandled parameter types: "
936 + Arrays.<Object> asList(container, name).toString());
940 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
942 return this.dataNormalizer.toNormalized(legacy);
943 } catch (final NullPointerException e) {
944 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
948 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
950 return this.dataNormalizer.toLegacy(instanceIdentifier);
951 } catch (final NullPointerException e) {
952 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
953 } catch (final DataNormalizationException e) {
954 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
958 public boolean isNodeMixin(final YangInstanceIdentifier path) {
959 final DataNormalizationOperation<?> operation;
961 operation = this.dataNormalizer.getOperation(path);
962 } catch (final DataNormalizationException e) {
963 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
965 return operation.isMixin();
968 public DataNormalizationOperation<?> getRootOperation() {
969 return this.dataNormalizer.getRootOperation();