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 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 onGlobalContextUpdated(schemas);
121 public InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
122 return toIdentifier(restconfInstance, false);
125 public SchemaContext getGlobalSchema() {
129 public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
130 return toIdentifier(restconfInstance, true);
133 private InstanceIdentifierContext toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
134 checkPreconditions();
136 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
137 omitFirstAndLastEmptyString(pathArgs);
138 if (pathArgs.isEmpty()) {
142 final String first = pathArgs.iterator().next();
143 final String startModule = ControllerContext.toModuleName(first);
144 if (startModule == null) {
145 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
146 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
149 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
150 final Module latestModule = globalSchema.findModuleByName(startModule, null);
151 final InstanceIdentifierContext iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
152 toMountPointIdentifier);
154 if (iiWithSchemaNode == null) {
155 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
158 return iiWithSchemaNode;
161 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
162 if (list.isEmpty()) {
166 final String head = list.iterator().next();
167 if (head.isEmpty()) {
171 if (list.isEmpty()) {
175 final String last = list.get(list.size() - 1);
176 if (last.isEmpty()) {
177 list.remove(list.size() - 1);
182 public Module findModuleByName(final String moduleName) {
183 checkPreconditions();
184 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
185 return globalSchema.findModuleByName(moduleName, null);
188 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
189 Preconditions.checkArgument(moduleName != null && mountPoint != null);
191 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
192 if (mountPointSchema == null) {
196 return mountPointSchema.findModuleByName(moduleName, null);
199 public Module findModuleByNamespace(final URI namespace) {
200 checkPreconditions();
201 Preconditions.checkArgument(namespace != null);
202 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
205 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
206 Preconditions.checkArgument(namespace != null && mountPoint != null);
208 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
209 if (mountPointSchema == null) {
213 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
216 public Module findModuleByNameAndRevision(final QName module) {
217 checkPreconditions();
218 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
220 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
223 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
224 checkPreconditions();
225 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
226 && mountPoint != null);
228 final SchemaContext schemaContext = mountPoint.getSchemaContext();
229 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
230 module.getRevision());
233 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
234 checkPreconditions();
236 final Iterable<PathArgument> elements = path.getPathArguments();
237 final PathArgument head = elements.iterator().next();
238 final QName startQName = head.getNodeType();
239 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
240 startQName.getRevision());
241 DataNodeContainer node = initialModule;
242 for (final PathArgument element : elements) {
243 final QName _nodeType = element.getNodeType();
244 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
245 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
248 node = (DataNodeContainer) potentialNode;
254 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
255 checkPreconditions();
257 final Iterable<PathArgument> elements = path.getPathArguments();
258 final StringBuilder builder = new StringBuilder();
259 final PathArgument head = elements.iterator().next();
260 final QName startQName = head.getNodeType();
261 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
262 startQName.getRevision());
263 DataNodeContainer node = initialModule;
264 for (final PathArgument element : elements) {
265 final QName _nodeType = element.getNodeType();
266 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
267 if (!ControllerContext.isListOrContainer(potentialNode)) {
270 node = ((DataNodeContainer) potentialNode);
271 builder.append(this.convertToRestconfIdentifier(element, node));
274 return builder.toString();
277 public String findModuleNameByNamespace(final URI namespace) {
278 checkPreconditions();
280 final Module module = this.findModuleByNamespace(namespace);
281 return module == null ? null : module.getName();
284 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
285 final Module module = this.findModuleByNamespace(mountPoint, namespace);
286 return module == null ? null : module.getName();
289 public URI findNamespaceByModuleName(final String moduleName) {
290 final Module module = this.findModuleByName(moduleName);
291 return module == null ? null : module.getNamespace();
294 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
295 final Module module = this.findModuleByName(mountPoint, moduleName);
296 return module == null ? null : module.getNamespace();
299 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
300 checkPreconditions();
302 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
303 return schemaContext == null ? null : schemaContext.getModules();
306 public Set<Module> getAllModules() {
307 checkPreconditions();
308 return globalSchema.getModules();
311 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
312 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
313 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
316 public CharSequence toRestconfIdentifier(final QName qname) {
317 checkPreconditions();
319 return toRestconfIdentifier(globalSchema, qname);
322 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
323 if (mountPoint == null) {
327 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
330 public Module getRestconfModule() {
331 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
334 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
336 public boolean apply(final GroupingDefinition g) {
337 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
341 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
342 final Module restconfModule = getRestconfModule();
343 if (restconfModule == null) {
347 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
349 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
351 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
353 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
354 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
355 return Iterables.getFirst(instanceDataChildrenByName, null);
358 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
360 public boolean apply(final GroupingDefinition g) {
361 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
365 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
366 Module restconfModule = inRestconfModule;
367 if (restconfModule == null) {
368 restconfModule = getRestconfModule();
371 if (restconfModule == null) {
375 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
376 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
377 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
379 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
380 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
381 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
383 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
384 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
385 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
386 return Iterables.getFirst(instances, null);
387 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
388 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
389 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
390 return Iterables.getFirst(instances, null);
391 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
392 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
393 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
394 final DataSchemaNode modules = Iterables.getFirst(instances, null);
395 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
396 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
397 return Iterables.getFirst(instances, null);
398 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
399 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
400 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
401 return Iterables.getFirst(instances, null);
402 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
403 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
404 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
405 final DataSchemaNode modules = Iterables.getFirst(instances, null);
406 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
407 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
408 return Iterables.getFirst(instances, null);
409 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
410 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
411 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
412 return Iterables.getFirst(instances, null);
418 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
419 for (final ChoiceCaseNode caze : container.getCases()) {
420 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
429 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
430 return container.getDataChildByName(name);
433 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
434 return ControllerContext.dataNodeChildByQName(container, name);
437 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
438 return ControllerContext.dataNodeChildByQName(container, name);
441 private static DataSchemaNode childByQName(final Module container, final QName name) {
442 return ControllerContext.dataNodeChildByQName(container, name);
445 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
449 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
450 final DataSchemaNode ret = container.getDataChildByName(name);
452 for (final DataSchemaNode node : container.getChildNodes()) {
453 if ((node instanceof ChoiceNode)) {
454 final ChoiceNode choiceNode = ((ChoiceNode) node);
455 final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
456 if (childByQName != null) {
465 private String toUriString(final Object object) throws UnsupportedEncodingException {
466 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
469 private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
470 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
471 final boolean returnJustMountPoint) {
472 Preconditions.<List<String>> checkNotNull(strings);
474 if (parentNode == null) {
478 if (strings.isEmpty()) {
479 return new InstanceIdentifierContext(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
482 final String head = strings.iterator().next();
483 final String nodeName = toNodeName(head);
484 final String moduleName = ControllerContext.toModuleName(head);
486 DataSchemaNode targetNode = null;
487 if (!Strings.isNullOrEmpty(moduleName)) {
488 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
489 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
490 if (mountPoint != null) {
491 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
492 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
495 if (mountService == null) {
496 throw new RestconfDocumentedException(
497 "MountService was not found. Finding behind mount points does not work.",
498 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
501 final YangInstanceIdentifier partialPath = builder.toInstance();
502 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
503 if (!mountOpt.isPresent()) {
504 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
505 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
506 ErrorTag.UNKNOWN_ELEMENT);
508 final DOMMountPoint mount = mountOpt.get();
510 final SchemaContext mountPointSchema = mount.getSchemaContext();
511 if (mountPointSchema == null) {
512 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
513 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
516 if (returnJustMountPoint) {
517 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
518 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
521 if (strings.size() == 1) {
522 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
523 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
526 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
527 if (moduleNameBehindMountPoint == null) {
528 throw new RestconfDocumentedException(
529 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
530 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
533 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
534 if (moduleBehindMountPoint == null) {
535 throw new RestconfDocumentedException("\"" + moduleName
536 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
539 final List<String> subList = strings.subList(1, strings.size());
540 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
541 returnJustMountPoint);
544 Module module = null;
545 if (mountPoint == null) {
546 checkPreconditions();
547 module = globalSchema.findModuleByName(moduleName, null);
548 if (module == null) {
549 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
550 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
553 final SchemaContext schemaContext = mountPoint.getSchemaContext();
554 if (schemaContext != null) {
555 module = schemaContext.findModuleByName(moduleName, null);
559 if (module == null) {
560 throw new RestconfDocumentedException("\"" + moduleName
561 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
565 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
566 if (targetNode == null) {
567 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
568 + "\" was not found in parent data node.\n" + " 2. \"" + head
569 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
570 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
573 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
574 if (potentialSchemaNodes.size() > 1) {
575 final StringBuilder strBuilder = new StringBuilder();
576 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
577 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
580 throw new RestconfDocumentedException(
581 "URI has bad format. Node \""
583 + "\" is added as augment from more than one module. "
584 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
585 + "\nThe node is added as augment from modules with namespaces:\n"
586 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
589 if (potentialSchemaNodes.isEmpty()) {
590 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
591 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
594 targetNode = potentialSchemaNodes.iterator().next();
597 if (!ControllerContext.isListOrContainer(targetNode)) {
598 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
599 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
603 if ((targetNode instanceof ListSchemaNode)) {
604 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
605 final int keysSize = listNode.getKeyDefinition().size();
606 if ((strings.size() - consumed) < keysSize) {
607 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
608 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
611 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
612 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
614 for (final QName key : listNode.getKeyDefinition()) {
616 final String uriKeyValue = uriKeyValues.get(i);
617 if (uriKeyValue.equals(NULL_VALUE)) {
618 throw new RestconfDocumentedException("URI has bad format. List \""
619 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
620 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
623 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
628 consumed = consumed + i;
629 builder.nodeWithKey(targetNode.getQName(), keyValues);
631 builder.node(targetNode.getQName());
634 if ((targetNode instanceof DataNodeContainer)) {
635 final List<String> remaining = strings.subList(consumed, strings.size());
636 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
637 returnJustMountPoint);
640 return new InstanceIdentifierContext(builder.toInstance(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
643 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
644 final URI namespace) {
645 Preconditions.<URI> checkNotNull(namespace);
647 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
649 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
651 public boolean apply(final DataSchemaNode node) {
652 return Objects.equal(node.getQName().getNamespace(), namespace);
656 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
657 return Iterables.getFirst(result, null);
660 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
661 Preconditions.<DataNodeContainer> checkNotNull(container);
662 Preconditions.<String> checkNotNull(name);
664 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
665 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
666 return instantiatedDataNodeContainers;
669 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
671 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
672 return node.getCases();
676 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
677 final DataNodeContainer container, final String name) {
679 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
681 public boolean apply(final DataSchemaNode node) {
682 return Objects.equal(node.getQName().getLocalName(), name);
686 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
688 // Can't combine this loop with the filter above because the filter is
689 // lazily-applied by Iterables.filter.
690 for (final DataSchemaNode potentialNode : nodes) {
691 if (isInstantiatedDataSchema(potentialNode)) {
692 potentialSchemaNodes.add(potentialNode);
696 final Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
697 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
699 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
700 for (final ChoiceCaseNode caze : allCases) {
701 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
705 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
706 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
707 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
708 || node instanceof AnyXmlSchemaNode;
711 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
712 final DOMMountPoint mountPoint) {
713 Preconditions.<String> checkNotNull(uriValue);
714 Preconditions.checkArgument((node instanceof LeafSchemaNode));
716 final String urlDecoded = urlPathArgDecode(uriValue);
717 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
718 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
720 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
721 String additionalInfo = "";
722 if (decoded == null) {
723 final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
724 if ((baseType instanceof IdentityrefTypeDefinition)) {
725 decoded = toQName(urlDecoded);
726 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
730 if (decoded == null) {
731 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
732 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
735 map.put(node.getQName(), decoded);
738 private static String toModuleName(final String str) {
739 final int idx = str.indexOf(':');
744 // Make sure there is only one occurrence
745 if (str.indexOf(':', idx + 1) != -1) {
749 return str.substring(0, idx);
752 private static String toNodeName(final String str) {
753 final int idx = str.indexOf(':');
758 // Make sure there is only one occurrence
759 if (str.indexOf(':', idx + 1) != -1) {
763 return str.substring(idx + 1);
766 private QName toQName(final String name) {
767 checkPreconditions();
768 final String module = toModuleName(name);
769 final String node = toNodeName(name);
770 final Module m = globalSchema.findModuleByName(module, null);
771 return m == null ? null : QName.create(m.getQNameModule(), node);
774 private static boolean isListOrContainer(final DataSchemaNode node) {
775 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
778 public RpcDefinition getRpcDefinition(final String name) {
779 final QName validName = toQName(name);
780 return validName == null ? null : qnameToRpc.get().get(validName);
784 public void onGlobalContextUpdated(final SchemaContext context) {
785 if (context != null) {
786 final Collection<RpcDefinition> defs = context.getOperations();
787 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
789 for (final RpcDefinition operation : defs) {
790 newMap.put(operation.getQName(), operation);
793 // FIXME: still not completely atomic
794 qnameToRpc.set(ImmutableMap.copyOf(newMap));
795 setGlobalSchema(context);
799 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
801 final List<String> decodedPathArgs = new ArrayList<String>();
802 for (final String pathArg : strings) {
803 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
804 decodedPathArgs.add(_decode);
806 return decodedPathArgs;
807 } catch (final UnsupportedEncodingException e) {
808 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
809 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
813 public String urlPathArgDecode(final String pathArg) {
814 if (pathArg != null) {
816 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
817 } catch (final UnsupportedEncodingException e) {
818 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
819 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
826 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
827 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
828 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
829 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
830 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
831 } else if (argument != null && node != null) {
832 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
834 throw new IllegalArgumentException("Unhandled parameter types: "
835 + Arrays.<Object> asList(argument, node).toString());
839 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
840 return "/" + this.toRestconfIdentifier(argument.getNodeType());
843 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
844 final ListSchemaNode node) {
845 final QName nodeType = argument.getNodeType();
846 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
847 final Map<QName, Object> keyValues = argument.getKeyValues();
849 final StringBuilder builder = new StringBuilder();
851 builder.append(nodeIdentifier);
854 final List<QName> keyDefinition = node.getKeyDefinition();
855 boolean hasElements = false;
856 for (final QName key : keyDefinition) {
864 builder.append(toUriString(keyValues.get(key)));
865 } catch (final UnsupportedEncodingException e) {
866 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
871 return builder.toString();
874 private static DataSchemaNode childByQName(final Object container, final QName name) {
875 if (container instanceof ChoiceCaseNode) {
876 return childByQName((ChoiceCaseNode) container, name);
877 } else if (container instanceof ChoiceNode) {
878 return childByQName((ChoiceNode) container, name);
879 } else if (container instanceof ContainerSchemaNode) {
880 return childByQName((ContainerSchemaNode) container, name);
881 } else if (container instanceof ListSchemaNode) {
882 return childByQName((ListSchemaNode) container, name);
883 } else if (container instanceof DataSchemaNode) {
884 return childByQName((DataSchemaNode) container, name);
885 } else if (container instanceof Module) {
886 return childByQName((Module) container, name);
888 throw new IllegalArgumentException("Unhandled parameter types: "
889 + Arrays.<Object> asList(container, name).toString());
893 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
894 final CompositeNode compositeNode) {
896 return dataNormalizer.toNormalized(legacy, compositeNode);
897 } catch (final NullPointerException e) {
898 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
902 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
904 return dataNormalizer.toNormalized(legacy);
905 } catch (final NullPointerException e) {
906 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
910 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
911 final NormalizedNode<?,?> normalizedNode) {
913 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
914 } catch (final NullPointerException e) {
915 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
919 public DataNormalizationOperation<?> getRootOperation() {
920 return dataNormalizer.getRootOperation();