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.restconf.common.context.InstanceIdentifierContext;
41 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
42 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
43 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
44 import org.opendaylight.yangtools.concepts.Codec;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
59 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
66 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
73 public class ControllerContext implements SchemaContextListener {
74 // FIXME: this should be in md-sal somewhere
75 public static final String MOUNT = "yang-ext:mount";
77 private static final Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
79 // FIXME: this should be the current instance which is mutated
80 private static final ControllerContext INSTANCE = new ControllerContext();
82 private static final String NULL_VALUE = "null";
84 private static final String MOUNT_MODULE = "yang-ext";
86 private static final String MOUNT_NODE = "mount";
88 private static final Charset URI_ENCODING_CHARSET = StandardCharsets.UTF_8;
90 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
92 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
94 // FIXME; these three should be final
95 private volatile SchemaContext globalSchema;
96 private volatile DOMMountPointService mountService;
97 private DataNormalizer dataNormalizer;
100 public void setGlobalSchema(final SchemaContext globalSchema) {
101 this.globalSchema = globalSchema;
102 this.dataNormalizer = new DataNormalizer(globalSchema);
105 public void setMountService(final DOMMountPointService mountService) {
106 this.mountService = mountService;
109 private ControllerContext() {
112 public static ControllerContext getInstance() {
116 private void checkPreconditions() {
117 if (this.globalSchema == null) {
118 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
122 public void setSchemas(final SchemaContext schemas) {
123 onGlobalContextUpdated(schemas);
126 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
127 return toIdentifier(restconfInstance, false);
130 public SchemaContext getGlobalSchema() {
131 return this.globalSchema;
134 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
135 return toIdentifier(restconfInstance, true);
138 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
139 final boolean toMountPointIdentifier) {
140 checkPreconditions();
142 if (restconfInstance == null) {
143 return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
147 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
148 omitFirstAndLastEmptyString(pathArgs);
149 if (pathArgs.isEmpty()) {
153 final String first = pathArgs.iterator().next();
154 final String startModule = toModuleName(first);
155 if (startModule == null) {
156 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
157 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
160 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
161 final Module latestModule = this.globalSchema.findModuleByName(startModule, null);
163 if (latestModule == null) {
164 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
165 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
168 final InstanceIdentifierContext<?> iiWithSchemaNode =
169 collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier);
171 if (iiWithSchemaNode == null) {
172 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
175 return iiWithSchemaNode;
178 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
179 if (list.isEmpty()) {
183 final String head = list.iterator().next();
184 if (head.isEmpty()) {
188 if (list.isEmpty()) {
192 final String last = list.get(list.size() - 1);
193 if (last.isEmpty()) {
194 list.remove(list.size() - 1);
200 public Module findModuleByName(final String moduleName) {
201 checkPreconditions();
202 Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty());
203 return this.globalSchema.findModuleByName(moduleName, null);
206 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
207 Preconditions.checkArgument((moduleName != null) && (mountPoint != null));
209 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
210 if (mountPointSchema == null) {
214 return mountPointSchema.findModuleByName(moduleName, null);
217 public Module findModuleByNamespace(final URI namespace) {
218 checkPreconditions();
219 Preconditions.checkArgument(namespace != null);
220 return this.globalSchema.findModuleByNamespaceAndRevision(namespace, null);
223 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
224 Preconditions.checkArgument((namespace != null) && (mountPoint != null));
226 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
227 if (mountPointSchema == null) {
231 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
234 public Module findModuleByNameAndRevision(final QName module) {
235 checkPreconditions();
237 .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
239 return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
242 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
243 checkPreconditions();
245 .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
246 && (mountPoint != null));
248 final SchemaContext schemaContext = mountPoint.getSchemaContext();
249 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
250 module.getRevision());
253 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
254 checkPreconditions();
256 final Iterable<PathArgument> elements = path.getPathArguments();
257 final PathArgument head = elements.iterator().next();
258 final QName startQName = head.getNodeType();
259 final Module initialModule = this.globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
260 startQName.getRevision());
261 DataNodeContainer node = initialModule;
262 for (final PathArgument element : elements) {
263 final QName _nodeType = element.getNodeType();
264 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
265 if ((potentialNode == null) || !isListOrContainer(potentialNode)) {
268 node = (DataNodeContainer) potentialNode;
274 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
275 checkPreconditions();
277 final Iterable<PathArgument> elements = path.getPathArguments();
278 final StringBuilder builder = new StringBuilder();
279 final PathArgument head = elements.iterator().next();
280 final QName startQName = head.getNodeType();
281 final SchemaContext schemaContext;
283 schemaContext = mount.getSchemaContext();
285 schemaContext = this.globalSchema;
287 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
288 startQName.getRevision());
289 DataNodeContainer node = initialModule;
290 for (final PathArgument element : elements) {
291 if (!(element instanceof AugmentationIdentifier)) {
292 final QName _nodeType = element.getNodeType();
293 final DataSchemaNode potentialNode = childByQName(node, _nodeType);
294 if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode))
295 && !(potentialNode instanceof ChoiceSchemaNode)) {
296 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
297 if (potentialNode instanceof DataNodeContainer) {
298 node = (DataNodeContainer) potentialNode;
304 return builder.toString();
307 public String findModuleNameByNamespace(final URI namespace) {
308 checkPreconditions();
310 final Module module = this.findModuleByNamespace(namespace);
311 return module == null ? null : module.getName();
314 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
315 final Module module = this.findModuleByNamespace(mountPoint, namespace);
316 return module == null ? null : module.getName();
319 public URI findNamespaceByModuleName(final String moduleName) {
320 final Module module = this.findModuleByName(moduleName);
321 return module == null ? null : module.getNamespace();
324 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
325 final Module module = this.findModuleByName(mountPoint, moduleName);
326 return module == null ? null : module.getNamespace();
329 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
330 checkPreconditions();
332 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
333 return schemaContext == null ? null : schemaContext.getModules();
336 public Set<Module> getAllModules() {
337 checkPreconditions();
338 return this.globalSchema.getModules();
341 private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
342 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
343 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
346 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
347 final SchemaContext schema;
349 schema = mount.getSchemaContext();
351 checkPreconditions();
352 schema = this.globalSchema;
355 return toRestconfIdentifier(schema, qname);
358 public CharSequence toRestconfIdentifier(final QName qname) {
359 checkPreconditions();
361 return toRestconfIdentifier(this.globalSchema, qname);
364 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
365 if (mountPoint == null) {
369 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
372 public Module getRestconfModule() {
373 return findModuleByNameAndRevision(RestConfModule.IETF_RESTCONF_QNAME);
376 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
377 final Module restconfModule = getRestconfModule();
378 if (restconfModule == null) {
382 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
384 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
385 g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
387 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
389 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
390 RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
391 return Iterables.getFirst(instanceDataChildrenByName, null);
394 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule,
395 final String schemaNodeName) {
396 Module restconfModule = inRestconfModule;
397 if (restconfModule == null) {
398 restconfModule = getRestconfModule();
401 if (restconfModule == null) {
405 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
406 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
407 g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
408 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
410 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
411 RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
412 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
414 if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
415 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
416 ((DataNodeContainer) restconfContainer), RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
417 return Iterables.getFirst(instances, null);
418 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
419 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
420 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
421 return Iterables.getFirst(instances, null);
422 } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
423 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
424 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
425 final DataSchemaNode modules = Iterables.getFirst(instances, null);
426 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
427 RestConfModule.STREAM_LIST_SCHEMA_NODE);
428 return Iterables.getFirst(instances, null);
429 } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
430 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
431 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
432 return Iterables.getFirst(instances, null);
433 } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) {
434 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
435 ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
436 final DataSchemaNode modules = Iterables.getFirst(instances, null);
437 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
438 RestConfModule.MODULE_LIST_SCHEMA_NODE);
439 return Iterables.getFirst(instances, null);
440 } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) {
441 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
442 ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
443 return Iterables.getFirst(instances, null);
449 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
450 for (final ChoiceCaseNode caze : container.getCases()) {
451 final DataSchemaNode ret = childByQName(caze, name);
460 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
461 return container.getDataChildByName(name);
464 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
465 return dataNodeChildByQName(container, name);
468 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
469 return dataNodeChildByQName(container, name);
472 private static DataSchemaNode childByQName(final Module container, final QName name) {
473 return dataNodeChildByQName(container, name);
476 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
481 private static DataSchemaNode childByQName(final Object container, final QName name) {
482 if (container instanceof ChoiceCaseNode) {
483 return childByQName((ChoiceCaseNode) container, name);
484 } else if (container instanceof ChoiceSchemaNode) {
485 return childByQName((ChoiceSchemaNode) container, name);
486 } else if (container instanceof ContainerSchemaNode) {
487 return childByQName((ContainerSchemaNode) container, name);
488 } else if (container instanceof ListSchemaNode) {
489 return childByQName((ListSchemaNode) container, name);
490 } else if (container instanceof DataSchemaNode) {
491 return childByQName((DataSchemaNode) container, name);
492 } else if (container instanceof Module) {
493 return childByQName((Module) container, name);
495 throw new IllegalArgumentException("Unhandled parameter types: "
496 + Arrays.<Object>asList(container, name).toString());
500 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
501 final DataSchemaNode ret = container.getDataChildByName(name);
503 for (final DataSchemaNode node : container.getChildNodes()) {
504 if ((node instanceof ChoiceSchemaNode)) {
505 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
506 final DataSchemaNode childByQName = childByQName(choiceNode, name);
507 if (childByQName != null) {
516 private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
517 throws UnsupportedEncodingException {
518 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
519 // FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
520 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
523 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
524 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
525 final boolean returnJustMountPoint) {
526 Preconditions.<List<String>>checkNotNull(strings);
528 if (parentNode == null) {
532 if (strings.isEmpty()) {
533 return createContext(builder.build(), ((DataSchemaNode) parentNode),
534 mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
537 final String head = strings.iterator().next();
538 final String nodeName = toNodeName(head);
539 final String moduleName = toModuleName(head);
541 DataSchemaNode targetNode = null;
542 if (!Strings.isNullOrEmpty(moduleName)) {
543 if (MOUNT_MODULE.equals(moduleName) && MOUNT_NODE.equals(nodeName)) {
544 if (mountPoint != null) {
545 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
546 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
549 if (this.mountService == null) {
550 throw new RestconfDocumentedException(
551 "MountService was not found. Finding behind mount points does not work.",
552 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
555 final YangInstanceIdentifier partialPath = this.dataNormalizer.toNormalized(builder.build());
556 final Optional<DOMMountPoint> mountOpt = this.mountService.getMountPoint(partialPath);
557 if (!mountOpt.isPresent()) {
558 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
559 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
560 ErrorTag.DATA_MISSING);
562 final DOMMountPoint mount = mountOpt.get();
564 final SchemaContext mountPointSchema = mount.getSchemaContext();
565 if (mountPointSchema == null) {
566 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
567 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
570 if (returnJustMountPoint || (strings.size() == 1)) {
571 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
572 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
575 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
576 if (moduleNameBehindMountPoint == null) {
577 throw new RestconfDocumentedException(
578 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
579 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
582 final Module moduleBehindMountPoint =
583 mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
584 if (moduleBehindMountPoint == null) {
585 throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
586 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
589 final List<String> subList = strings.subList(1, strings.size());
590 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
591 returnJustMountPoint);
594 Module module = null;
595 if (mountPoint == null) {
596 checkPreconditions();
597 module = this.globalSchema.findModuleByName(moduleName, null);
598 if (module == null) {
599 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
600 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
603 final SchemaContext schemaContext = mountPoint.getSchemaContext();
604 if (schemaContext != null) {
605 module = schemaContext.findModuleByName(moduleName, null);
609 if (module == null) {
610 throw new RestconfDocumentedException("\"" + moduleName
611 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
615 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
617 if ((targetNode == null) && (parentNode instanceof Module)) {
618 final RpcDefinition rpc;
619 if (mountPoint == null) {
620 rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
622 final String rpcName = toNodeName(head);
623 ControllerContext.getInstance();
624 rpc = ControllerContext.getRpcDefinition(module, rpcName);
627 return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
628 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
632 if (targetNode == null) {
633 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
634 + "\" was not found in parent data node.\n" + " 2. \"" + head
635 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
636 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
639 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
640 if (potentialSchemaNodes.size() > 1) {
641 final StringBuilder strBuilder = new StringBuilder();
642 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
643 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
646 throw new RestconfDocumentedException(
647 "URI has bad format. Node \""
648 + nodeName + "\" is added as augment from more than one module. "
649 + "Therefore the node must have module name "
650 + "and it has to be in format \"moduleName:nodeName\"."
651 + "\nThe node is added as augment from modules with namespaces:\n"
652 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
655 if (potentialSchemaNodes.isEmpty()) {
656 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
657 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
660 targetNode = potentialSchemaNodes.iterator().next();
663 if (!isListOrContainer(targetNode)) {
664 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
665 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
669 if ((targetNode instanceof ListSchemaNode)) {
670 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
671 final int keysSize = listNode.getKeyDefinition().size();
672 if ((strings.size() - consumed) < keysSize) {
673 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
674 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
677 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
678 final HashMap<QName, Object> keyValues = new HashMap<>();
680 for (final QName key : listNode.getKeyDefinition()) {
682 final String uriKeyValue = uriKeyValues.get(index);
683 if (uriKeyValue.equals(NULL_VALUE)) {
684 throw new RestconfDocumentedException("URI has bad format. List \""
685 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
686 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
689 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
694 consumed = consumed + index;
695 builder.nodeWithKey(targetNode.getQName(), keyValues);
697 builder.node(targetNode.getQName());
700 if ((targetNode instanceof DataNodeContainer)) {
701 final List<String> remaining = strings.subList(consumed, strings.size());
702 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
703 returnJustMountPoint);
706 return createContext(builder.build(), targetNode, mountPoint,
707 mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema);
710 private static InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance,
711 final DataSchemaNode dataSchemaNode, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
712 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
713 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint, schemaContext);
716 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
717 final String name, final URI namespace) {
718 Preconditions.checkNotNull(namespace);
720 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
721 node -> namespace.equals(node.getQName().getNamespace()));
722 return Iterables.getFirst(result, null);
725 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
727 Preconditions.checkNotNull(container);
728 Preconditions.checkNotNull(name);
730 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
731 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
732 return instantiatedDataNodeContainers;
735 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
736 final DataNodeContainer container, final String name) {
738 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(),
739 node -> name.equals(node.getQName().getLocalName()));
741 // Can't combine this loop with the filter above because the filter is
742 // lazily-applied by Iterables.filter.
743 for (final DataSchemaNode potentialNode : nodes) {
744 if (isInstantiatedDataSchema(potentialNode)) {
745 potentialSchemaNodes.add(potentialNode);
749 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(),
750 ChoiceSchemaNode.class);
751 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
752 for (final ChoiceCaseNode caze : Iterables.concat(map)) {
753 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
757 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
758 return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode)
759 || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode)
760 || (node instanceof AnyXmlSchemaNode);
763 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
764 final DOMMountPoint mountPoint) {
765 Preconditions.checkNotNull(uriValue);
766 Preconditions.checkArgument((node instanceof LeafSchemaNode));
768 final String urlDecoded = urlPathArgDecode(uriValue);
769 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
770 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
771 if (baseType instanceof LeafrefTypeDefinition) {
772 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, this.globalSchema,
775 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
776 Object decoded = codec.deserialize(urlDecoded);
777 String additionalInfo = "";
778 if (decoded == null) {
779 if ((typedef instanceof IdentityrefTypeDefinition)) {
780 final SchemaContext schemaContext =
781 mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
782 decoded = toQName(schemaContext, urlDecoded, null);
784 "For key which is of type identityref it should be in format module_name:identity_name.";
788 if (decoded == null) {
789 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
790 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
793 map.put(node.getQName(), decoded);
796 private static String toModuleName(final String str) {
797 final int idx = str.indexOf(':');
802 // Make sure there is only one occurrence
803 if (str.indexOf(':', idx + 1) != -1) {
807 return str.substring(0, idx);
810 private static String toNodeName(final String str) {
811 final int idx = str.indexOf(':');
816 // Make sure there is only one occurrence
817 if (str.indexOf(':', idx + 1) != -1) {
821 return str.substring(idx + 1);
824 private QName toQName(final SchemaContext schemaContext, final String name, final Date revisionDate) {
825 checkPreconditions();
826 final String module = toModuleName(name);
827 final String node = toNodeName(name);
828 final Module m = schemaContext.findModuleByName(module, revisionDate);
829 return m == null ? null : QName.create(m.getQNameModule(), node);
832 private static boolean isListOrContainer(final DataSchemaNode node) {
833 return (node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode);
836 public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) {
837 final QName validName = toQName(this.globalSchema, name, revisionDate);
838 return validName == null ? null : this.qnameToRpc.get().get(validName);
841 private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) {
842 final QName rpcQName = QName.create(module.getQNameModule(), rpcName);
843 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
844 if (rpcQName.equals(rpcDefinition.getQName())) {
845 return rpcDefinition;
852 public void onGlobalContextUpdated(final SchemaContext context) {
853 if (context != null) {
854 final Collection<RpcDefinition> defs = context.getOperations();
855 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
857 for (final RpcDefinition operation : defs) {
858 newMap.put(operation.getQName(), operation);
861 // FIXME: still not completely atomic
862 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
863 setGlobalSchema(context);
867 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
869 final List<String> decodedPathArgs = new ArrayList<>();
870 for (final String pathArg : strings) {
871 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
872 decodedPathArgs.add(_decode);
874 return decodedPathArgs;
875 } catch (final UnsupportedEncodingException e) {
876 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
877 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
881 public String urlPathArgDecode(final String pathArg) {
882 if (pathArg != null) {
884 return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name());
885 } catch (final UnsupportedEncodingException e) {
886 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
887 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
894 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node,
895 final DOMMountPoint mount) {
896 if (argument instanceof NodeIdentifier) {
897 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
898 } else if ((argument instanceof NodeIdentifierWithPredicates) && (node instanceof ListSchemaNode)) {
899 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument,
900 (ListSchemaNode) node, mount);
901 } else if ((argument != null) && (node != null)) {
902 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
904 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node));
908 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
909 return "/" + toRestconfIdentifier(argument.getNodeType(),node);
912 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
913 final ListSchemaNode node, final DOMMountPoint mount) {
914 final QName nodeType = argument.getNodeType();
915 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
916 final Map<QName, Object> keyValues = argument.getKeyValues();
918 final StringBuilder builder = new StringBuilder();
920 builder.append(nodeIdentifier);
923 final List<QName> keyDefinition = node.getKeyDefinition();
924 boolean hasElements = false;
925 for (final QName key : keyDefinition) {
926 for (final DataSchemaNode listChild : node.getChildNodes()) {
927 if (listChild.getQName().equals(key)) {
935 Preconditions.checkState(listChild instanceof LeafSchemaNode,
936 "List key has to consist of leaves, not %s", listChild);
937 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
938 } catch (final UnsupportedEncodingException e) {
939 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
947 return builder.toString();
950 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
952 return this.dataNormalizer.toNormalized(legacy);
953 } catch (final NullPointerException e) {
954 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
958 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
960 return this.dataNormalizer.toLegacy(instanceIdentifier);
961 } catch (final NullPointerException e) {
962 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
963 } catch (final DataNormalizationException e) {
964 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
968 public boolean isNodeMixin(final YangInstanceIdentifier path) {
969 final DataNormalizationOperation<?> operation;
971 operation = this.dataNormalizer.getOperation(path);
972 } catch (final DataNormalizationException e) {
973 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
975 return operation.isMixin();
978 public DataNormalizationOperation<?> getRootOperation() {
979 return this.dataNormalizer.getRootOperation();