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.controller.sal.restconf.impl;
10 import com.google.common.base.Function;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicate;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.Iterables;
19 import java.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import java.util.concurrent.atomic.AtomicReference;
33 import javax.ws.rs.core.Response.Status;
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.controller.sal.rest.api.Draft02;
39 import org.opendaylight.controller.sal.rest.impl.RestUtil;
40 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
41 import org.opendaylight.controller.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.CompositeNode;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.data.api.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
54 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
65 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 public class ControllerContext implements SchemaContextListener {
71 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
73 private final static ControllerContext INSTANCE = new ControllerContext();
75 private final static String NULL_VALUE = "null";
77 private final static String MOUNT_MODULE = "yang-ext";
79 private final static String MOUNT_NODE = "mount";
81 public final static String MOUNT = "yang-ext:mount";
83 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
85 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
87 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
88 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
90 private volatile SchemaContext globalSchema;
91 private volatile DOMMountPointService mountService;
93 private DataNormalizer dataNormalizer;
95 public void setGlobalSchema(final SchemaContext globalSchema) {
96 this.globalSchema = globalSchema;
97 this.dataNormalizer = new DataNormalizer(globalSchema);
100 public void setMountService(final DOMMountPointService mountService) {
101 this.mountService = mountService;
104 private ControllerContext() {
107 public static ControllerContext getInstance() {
108 return ControllerContext.INSTANCE;
111 private void checkPreconditions() {
112 if (globalSchema == null) {
113 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
117 public void setSchemas(final SchemaContext schemas) {
118 this.onGlobalContextUpdated(schemas);
121 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
122 return this.toIdentifier(restconfInstance, false);
125 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
126 return this.toIdentifier(restconfInstance, true);
129 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
130 this.checkPreconditions();
132 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
133 omitFirstAndLastEmptyString(pathArgs);
134 if (pathArgs.isEmpty()) {
138 String first = pathArgs.iterator().next();
139 final String startModule = ControllerContext.toModuleName(first);
140 if (startModule == null) {
141 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
142 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
145 InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
146 Module latestModule = globalSchema.findModuleByName(startModule, null);
147 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
148 toMountPointIdentifier);
150 if (iiWithSchemaNode == null) {
151 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
154 return iiWithSchemaNode;
157 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
158 if (list.isEmpty()) {
162 String head = list.iterator().next();
163 if (head.isEmpty()) {
167 if (list.isEmpty()) {
171 String last = list.get(list.size() - 1);
172 if (last.isEmpty()) {
173 list.remove(list.size() - 1);
178 public Module findModuleByName(final String moduleName) {
179 this.checkPreconditions();
180 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
181 return globalSchema.findModuleByName(moduleName, null);
184 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
185 Preconditions.checkArgument(moduleName != null && mountPoint != null);
187 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
188 if (mountPointSchema == null) {
192 return mountPointSchema.findModuleByName(moduleName, null);
195 public Module findModuleByNamespace(final URI namespace) {
196 this.checkPreconditions();
197 Preconditions.checkArgument(namespace != null);
198 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
201 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
202 Preconditions.checkArgument(namespace != null && mountPoint != null);
204 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
205 if (mountPointSchema == null) {
209 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
212 public Module findModuleByNameAndRevision(final QName module) {
213 this.checkPreconditions();
214 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
216 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
219 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
220 this.checkPreconditions();
221 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
222 && mountPoint != null);
224 SchemaContext schemaContext = mountPoint.getSchemaContext();
225 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
226 module.getRevision());
229 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
230 this.checkPreconditions();
232 final Iterable<PathArgument> elements = path.getPathArguments();
233 PathArgument head = elements.iterator().next();
234 final QName startQName = head.getNodeType();
235 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
236 startQName.getRevision());
237 DataNodeContainer node = initialModule;
238 for (final PathArgument element : elements) {
239 QName _nodeType = element.getNodeType();
240 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
241 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
244 node = (DataNodeContainer) potentialNode;
250 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
251 this.checkPreconditions();
253 final Iterable<PathArgument> elements = path.getPathArguments();
254 final StringBuilder builder = new StringBuilder();
255 PathArgument head = elements.iterator().next();
256 final QName startQName = head.getNodeType();
257 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
258 startQName.getRevision());
259 DataNodeContainer node = initialModule;
260 for (final PathArgument element : elements) {
261 QName _nodeType = element.getNodeType();
262 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
263 if (!ControllerContext.isListOrContainer(potentialNode)) {
266 node = ((DataNodeContainer) potentialNode);
267 builder.append(this.convertToRestconfIdentifier(element, node));
270 return builder.toString();
273 public String findModuleNameByNamespace(final URI namespace) {
274 this.checkPreconditions();
276 final Module module = this.findModuleByNamespace(namespace);
277 return module == null ? null : module.getName();
280 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
281 final Module module = this.findModuleByNamespace(mountPoint, namespace);
282 return module == null ? null : module.getName();
285 public URI findNamespaceByModuleName(final String moduleName) {
286 final Module module = this.findModuleByName(moduleName);
287 return module == null ? null : module.getNamespace();
290 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
291 final Module module = this.findModuleByName(mountPoint, moduleName);
292 return module == null ? null : module.getNamespace();
295 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
296 this.checkPreconditions();
298 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
299 return schemaContext == null ? null : schemaContext.getModules();
302 public Set<Module> getAllModules() {
303 this.checkPreconditions();
304 return globalSchema.getModules();
307 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
308 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
309 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
312 public CharSequence toRestconfIdentifier(final QName qname) {
313 this.checkPreconditions();
315 return toRestconfIdentifier(globalSchema, qname);
318 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
319 if (mountPoint == null) {
323 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
326 public Module getRestconfModule() {
327 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
330 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
332 public boolean apply(final GroupingDefinition g) {
333 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
337 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
338 Module restconfModule = getRestconfModule();
339 if (restconfModule == null) {
343 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
345 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
347 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
349 List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
350 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
351 return Iterables.getFirst(instanceDataChildrenByName, null);
354 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
356 public boolean apply(final GroupingDefinition g) {
357 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
361 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
362 Module restconfModule = inRestconfModule;
363 if (restconfModule == null) {
364 restconfModule = getRestconfModule();
367 if (restconfModule == null) {
371 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
372 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
373 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
375 List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
376 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
377 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
379 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
380 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
381 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
382 return Iterables.getFirst(instances, null);
383 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
384 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
385 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
386 return Iterables.getFirst(instances, null);
387 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
388 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
389 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
390 final DataSchemaNode modules = Iterables.getFirst(instances, null);
391 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
392 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
393 return Iterables.getFirst(instances, null);
394 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
395 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
396 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
397 return Iterables.getFirst(instances, null);
398 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
399 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
400 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
401 final DataSchemaNode modules = Iterables.getFirst(instances, null);
402 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
403 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
404 return Iterables.getFirst(instances, null);
405 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
406 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
407 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
408 return Iterables.getFirst(instances, null);
414 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
415 for (final ChoiceCaseNode caze : container.getCases()) {
416 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
425 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
426 return container.getDataChildByName(name);
429 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
430 return ControllerContext.dataNodeChildByQName(container, name);
433 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
434 return ControllerContext.dataNodeChildByQName(container, name);
437 private static DataSchemaNode childByQName(final Module container, final QName name) {
438 return ControllerContext.dataNodeChildByQName(container, name);
441 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
445 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
446 DataSchemaNode ret = container.getDataChildByName(name);
448 for (final DataSchemaNode node : container.getChildNodes()) {
449 if ((node instanceof ChoiceNode)) {
450 final ChoiceNode choiceNode = ((ChoiceNode) node);
451 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
452 if (childByQName != null) {
461 private String toUriString(final Object object) throws UnsupportedEncodingException {
462 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
465 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
466 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
467 final boolean returnJustMountPoint) {
468 Preconditions.<List<String>> checkNotNull(strings);
470 if (parentNode == null) {
474 if (strings.isEmpty()) {
475 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
478 String head = strings.iterator().next();
479 final String nodeName = toNodeName(head);
480 final String moduleName = ControllerContext.toModuleName(head);
482 DataSchemaNode targetNode = null;
483 if (!Strings.isNullOrEmpty(moduleName)) {
484 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
485 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
486 if (mountPoint != null) {
487 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
488 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
491 if (mountService == null) {
492 throw new RestconfDocumentedException(
493 "MountService was not found. Finding behind mount points does not work.",
494 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
497 final YangInstanceIdentifier partialPath = builder.toInstance();
498 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
499 if (!mountOpt.isPresent()) {
500 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
501 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
502 ErrorTag.UNKNOWN_ELEMENT);
504 DOMMountPoint mount = mountOpt.get();
506 final SchemaContext mountPointSchema = mount.getSchemaContext();
507 if (mountPointSchema == null) {
508 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
509 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
512 if (returnJustMountPoint) {
513 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
514 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
517 if (strings.size() == 1) {
518 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
519 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
522 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
523 if (moduleNameBehindMountPoint == null) {
524 throw new RestconfDocumentedException(
525 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
526 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
529 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
530 if (moduleBehindMountPoint == null) {
531 throw new RestconfDocumentedException("\"" + moduleName
532 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
535 List<String> subList = strings.subList(1, strings.size());
536 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
537 returnJustMountPoint);
540 Module module = null;
541 if (mountPoint == null) {
542 module = globalSchema.findModuleByName(moduleName, null);
543 if (module == null) {
544 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
545 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
548 SchemaContext schemaContext = mountPoint.getSchemaContext();
549 if (schemaContext != null) {
550 module = schemaContext.findModuleByName(moduleName, null);
554 if (module == null) {
555 throw new RestconfDocumentedException("\"" + moduleName
556 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
560 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
561 if (targetNode == null) {
562 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
563 + "\" was not found in parent data node.\n" + " 2. \"" + head
564 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
565 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
568 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
569 if (potentialSchemaNodes.size() > 1) {
570 final StringBuilder strBuilder = new StringBuilder();
571 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
572 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
575 throw new RestconfDocumentedException(
576 "URI has bad format. Node \""
578 + "\" is added as augment from more than one module. "
579 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
580 + "\nThe node is added as augment from modules with namespaces:\n"
581 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
584 if (potentialSchemaNodes.isEmpty()) {
585 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
586 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
589 targetNode = potentialSchemaNodes.iterator().next();
592 if (!ControllerContext.isListOrContainer(targetNode)) {
593 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
594 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
598 if ((targetNode instanceof ListSchemaNode)) {
599 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
600 final int keysSize = listNode.getKeyDefinition().size();
601 if ((strings.size() - consumed) < keysSize) {
602 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
603 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
606 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
607 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
609 for (final QName key : listNode.getKeyDefinition()) {
611 final String uriKeyValue = uriKeyValues.get(i);
612 if (uriKeyValue.equals(NULL_VALUE)) {
613 throw new RestconfDocumentedException("URI has bad format. List \""
614 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
615 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
618 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
623 consumed = consumed + i;
624 builder.nodeWithKey(targetNode.getQName(), keyValues);
626 builder.node(targetNode.getQName());
629 if ((targetNode instanceof DataNodeContainer)) {
630 final List<String> remaining = strings.subList(consumed, strings.size());
631 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
632 returnJustMountPoint);
635 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
638 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
639 final URI namespace) {
640 Preconditions.<URI> checkNotNull(namespace);
642 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
644 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
646 public boolean apply(final DataSchemaNode node) {
647 return Objects.equal(node.getQName().getNamespace(), namespace);
651 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
652 return Iterables.getFirst(result, null);
655 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
656 Preconditions.<DataNodeContainer> checkNotNull(container);
657 Preconditions.<String> checkNotNull(name);
659 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
660 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
661 return instantiatedDataNodeContainers;
664 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
666 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
667 return node.getCases();
671 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
672 final DataNodeContainer container, final String name) {
674 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
676 public boolean apply(final DataSchemaNode node) {
677 return Objects.equal(node.getQName().getLocalName(), name);
681 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
683 // Can't combine this loop with the filter above because the filter is
684 // lazily-applied by Iterables.filter.
685 for (final DataSchemaNode potentialNode : nodes) {
686 if (isInstantiatedDataSchema(potentialNode)) {
687 potentialSchemaNodes.add(potentialNode);
691 Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
692 Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
694 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
695 for (final ChoiceCaseNode caze : allCases) {
696 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
700 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
701 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
702 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
703 || node instanceof AnyXmlSchemaNode;
706 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
707 final DOMMountPoint mountPoint) {
708 Preconditions.<String> checkNotNull(uriValue);
709 Preconditions.checkArgument((node instanceof LeafSchemaNode));
711 final String urlDecoded = urlPathArgDecode(uriValue);
712 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
713 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
715 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
716 String additionalInfo = "";
717 if (decoded == null) {
718 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
719 if ((baseType instanceof IdentityrefTypeDefinition)) {
720 decoded = this.toQName(urlDecoded);
721 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
725 if (decoded == null) {
726 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
727 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
730 map.put(node.getQName(), decoded);
733 private static String toModuleName(final String str) {
734 final int idx = str.indexOf(':');
739 // Make sure there is only one occurrence
740 if (str.indexOf(':', idx + 1) != -1) {
744 return str.substring(0, idx);
747 private static String toNodeName(final String str) {
748 final int idx = str.indexOf(':');
753 // Make sure there is only one occurrence
754 if (str.indexOf(':', idx + 1) != -1) {
758 return str.substring(idx + 1);
761 private QName toQName(final String name) {
762 final String module = toModuleName(name);
763 final String node = toNodeName(name);
764 final Module m = globalSchema.findModuleByName(module, null);
765 return m == null ? null : QName.create(m.getQNameModule(), node);
768 private static boolean isListOrContainer(final DataSchemaNode node) {
769 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
772 public RpcDefinition getRpcDefinition(final String name) {
773 final QName validName = this.toQName(name);
774 return validName == null ? null : this.qnameToRpc.get().get(validName);
778 public void onGlobalContextUpdated(final SchemaContext context) {
779 if (context != null) {
780 final Collection<RpcDefinition> defs = context.getOperations();
781 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
783 for (final RpcDefinition operation : defs) {
784 newMap.put(operation.getQName(), operation);
787 // FIXME: still not completely atomic
788 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
789 this.setGlobalSchema(context);
793 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
795 List<String> decodedPathArgs = new ArrayList<String>();
796 for (final String pathArg : strings) {
797 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
798 decodedPathArgs.add(_decode);
800 return decodedPathArgs;
801 } catch (UnsupportedEncodingException e) {
802 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
803 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
807 public String urlPathArgDecode(final String pathArg) {
808 if (pathArg != null) {
810 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
811 } catch (UnsupportedEncodingException e) {
812 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
813 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
820 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
821 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
822 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
823 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
824 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
825 } else if (argument != null && node != null) {
826 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
828 throw new IllegalArgumentException("Unhandled parameter types: "
829 + Arrays.<Object> asList(argument, node).toString());
833 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
834 return "/" + this.toRestconfIdentifier(argument.getNodeType());
837 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
838 final ListSchemaNode node) {
839 QName nodeType = argument.getNodeType();
840 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
841 final Map<QName, Object> keyValues = argument.getKeyValues();
843 StringBuilder builder = new StringBuilder();
845 builder.append(nodeIdentifier);
848 List<QName> keyDefinition = node.getKeyDefinition();
849 boolean hasElements = false;
850 for (final QName key : keyDefinition) {
858 builder.append(this.toUriString(keyValues.get(key)));
859 } catch (UnsupportedEncodingException e) {
860 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
865 return builder.toString();
868 private static DataSchemaNode childByQName(final Object container, final QName name) {
869 if (container instanceof ChoiceCaseNode) {
870 return childByQName((ChoiceCaseNode) container, name);
871 } else if (container instanceof ChoiceNode) {
872 return childByQName((ChoiceNode) container, name);
873 } else if (container instanceof ContainerSchemaNode) {
874 return childByQName((ContainerSchemaNode) container, name);
875 } else if (container instanceof ListSchemaNode) {
876 return childByQName((ListSchemaNode) container, name);
877 } else if (container instanceof DataSchemaNode) {
878 return childByQName((DataSchemaNode) container, name);
879 } else if (container instanceof Module) {
880 return childByQName((Module) container, name);
882 throw new IllegalArgumentException("Unhandled parameter types: "
883 + Arrays.<Object> asList(container, name).toString());
887 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
888 final CompositeNode compositeNode) {
890 return dataNormalizer.toNormalized(legacy, compositeNode);
891 } catch (NullPointerException e) {
892 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
896 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
898 return dataNormalizer.toNormalized(legacy);
899 } catch (NullPointerException e) {
900 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
904 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
905 final NormalizedNode<?,?> normalizedNode) {
907 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
908 } catch (NullPointerException e) {
909 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
913 public DataNormalizationOperation<?> getRootOperation() {
914 return dataNormalizer.getRootOperation();