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 InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
122 return this.toIdentifier(restconfInstance, false);
125 public SchemaContext getGlobalSchema() {
129 public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
130 return this.toIdentifier(restconfInstance, true);
133 private InstanceIdentifierContext toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
134 this.checkPreconditions();
136 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
137 omitFirstAndLastEmptyString(pathArgs);
138 if (pathArgs.isEmpty()) {
142 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 InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
150 Module latestModule = globalSchema.findModuleByName(startModule, null);
151 InstanceIdentifierContext iiWithSchemaNode = this.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 String head = list.iterator().next();
167 if (head.isEmpty()) {
171 if (list.isEmpty()) {
175 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 this.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 this.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 this.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 this.checkPreconditions();
225 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
226 && mountPoint != null);
228 SchemaContext schemaContext = mountPoint.getSchemaContext();
229 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
230 module.getRevision());
233 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
234 this.checkPreconditions();
236 final Iterable<PathArgument> elements = path.getPathArguments();
237 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 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 this.checkPreconditions();
257 final Iterable<PathArgument> elements = path.getPathArguments();
258 final StringBuilder builder = new StringBuilder();
259 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 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 this.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 this.checkPreconditions();
302 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
303 return schemaContext == null ? null : schemaContext.getModules();
306 public Set<Module> getAllModules() {
307 this.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 this.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 Module restconfModule = getRestconfModule();
343 if (restconfModule == null) {
347 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
349 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
351 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
353 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 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
376 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
377 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
379 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 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 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 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 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 DataSchemaNode ret = container.getDataChildByName(name);
452 for (final DataSchemaNode node : container.getChildNodes()) {
453 if ((node instanceof ChoiceNode)) {
454 final ChoiceNode choiceNode = ((ChoiceNode) node);
455 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 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 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 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
518 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
521 if (strings.size() == 1) {
522 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 List<String> subList = strings.subList(1, strings.size());
540 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
541 returnJustMountPoint);
544 Module module = null;
545 if (mountPoint == null) {
546 module = globalSchema.findModuleByName(moduleName, null);
547 if (module == null) {
548 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
549 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
552 SchemaContext schemaContext = mountPoint.getSchemaContext();
553 if (schemaContext != null) {
554 module = schemaContext.findModuleByName(moduleName, null);
558 if (module == null) {
559 throw new RestconfDocumentedException("\"" + moduleName
560 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
564 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
565 if (targetNode == null) {
566 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
567 + "\" was not found in parent data node.\n" + " 2. \"" + head
568 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
569 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
572 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
573 if (potentialSchemaNodes.size() > 1) {
574 final StringBuilder strBuilder = new StringBuilder();
575 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
576 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
579 throw new RestconfDocumentedException(
580 "URI has bad format. Node \""
582 + "\" is added as augment from more than one module. "
583 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
584 + "\nThe node is added as augment from modules with namespaces:\n"
585 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
588 if (potentialSchemaNodes.isEmpty()) {
589 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
590 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
593 targetNode = potentialSchemaNodes.iterator().next();
596 if (!ControllerContext.isListOrContainer(targetNode)) {
597 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
598 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
602 if ((targetNode instanceof ListSchemaNode)) {
603 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
604 final int keysSize = listNode.getKeyDefinition().size();
605 if ((strings.size() - consumed) < keysSize) {
606 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
607 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
610 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
611 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
613 for (final QName key : listNode.getKeyDefinition()) {
615 final String uriKeyValue = uriKeyValues.get(i);
616 if (uriKeyValue.equals(NULL_VALUE)) {
617 throw new RestconfDocumentedException("URI has bad format. List \""
618 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
619 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
622 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
627 consumed = consumed + i;
628 builder.nodeWithKey(targetNode.getQName(), keyValues);
630 builder.node(targetNode.getQName());
633 if ((targetNode instanceof DataNodeContainer)) {
634 final List<String> remaining = strings.subList(consumed, strings.size());
635 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
636 returnJustMountPoint);
639 return new InstanceIdentifierContext(builder.toInstance(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
642 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
643 final URI namespace) {
644 Preconditions.<URI> checkNotNull(namespace);
646 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
648 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
650 public boolean apply(final DataSchemaNode node) {
651 return Objects.equal(node.getQName().getNamespace(), namespace);
655 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
656 return Iterables.getFirst(result, null);
659 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
660 Preconditions.<DataNodeContainer> checkNotNull(container);
661 Preconditions.<String> checkNotNull(name);
663 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
664 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
665 return instantiatedDataNodeContainers;
668 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
670 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
671 return node.getCases();
675 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
676 final DataNodeContainer container, final String name) {
678 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
680 public boolean apply(final DataSchemaNode node) {
681 return Objects.equal(node.getQName().getLocalName(), name);
685 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
687 // Can't combine this loop with the filter above because the filter is
688 // lazily-applied by Iterables.filter.
689 for (final DataSchemaNode potentialNode : nodes) {
690 if (isInstantiatedDataSchema(potentialNode)) {
691 potentialSchemaNodes.add(potentialNode);
695 Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
696 Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
698 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
699 for (final ChoiceCaseNode caze : allCases) {
700 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
704 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
705 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
706 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
707 || node instanceof AnyXmlSchemaNode;
710 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
711 final DOMMountPoint mountPoint) {
712 Preconditions.<String> checkNotNull(uriValue);
713 Preconditions.checkArgument((node instanceof LeafSchemaNode));
715 final String urlDecoded = urlPathArgDecode(uriValue);
716 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
717 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
719 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
720 String additionalInfo = "";
721 if (decoded == null) {
722 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
723 if ((baseType instanceof IdentityrefTypeDefinition)) {
724 decoded = this.toQName(urlDecoded);
725 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
729 if (decoded == null) {
730 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
731 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
734 map.put(node.getQName(), decoded);
737 private static String toModuleName(final String str) {
738 final int idx = str.indexOf(':');
743 // Make sure there is only one occurrence
744 if (str.indexOf(':', idx + 1) != -1) {
748 return str.substring(0, idx);
751 private static String toNodeName(final String str) {
752 final int idx = str.indexOf(':');
757 // Make sure there is only one occurrence
758 if (str.indexOf(':', idx + 1) != -1) {
762 return str.substring(idx + 1);
765 private QName toQName(final String name) {
766 final String module = toModuleName(name);
767 final String node = toNodeName(name);
768 final Module m = globalSchema.findModuleByName(module, null);
769 return m == null ? null : QName.create(m.getQNameModule(), node);
772 private static boolean isListOrContainer(final DataSchemaNode node) {
773 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
776 public RpcDefinition getRpcDefinition(final String name) {
777 final QName validName = this.toQName(name);
778 return validName == null ? null : this.qnameToRpc.get().get(validName);
782 public void onGlobalContextUpdated(final SchemaContext context) {
783 if (context != null) {
784 final Collection<RpcDefinition> defs = context.getOperations();
785 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
787 for (final RpcDefinition operation : defs) {
788 newMap.put(operation.getQName(), operation);
791 // FIXME: still not completely atomic
792 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
793 this.setGlobalSchema(context);
797 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
799 List<String> decodedPathArgs = new ArrayList<String>();
800 for (final String pathArg : strings) {
801 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
802 decodedPathArgs.add(_decode);
804 return decodedPathArgs;
805 } catch (UnsupportedEncodingException e) {
806 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
807 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
811 public String urlPathArgDecode(final String pathArg) {
812 if (pathArg != null) {
814 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
815 } catch (UnsupportedEncodingException e) {
816 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
817 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
824 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
825 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
826 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
827 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
828 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
829 } else if (argument != null && node != null) {
830 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
832 throw new IllegalArgumentException("Unhandled parameter types: "
833 + Arrays.<Object> asList(argument, node).toString());
837 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
838 return "/" + this.toRestconfIdentifier(argument.getNodeType());
841 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
842 final ListSchemaNode node) {
843 QName nodeType = argument.getNodeType();
844 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
845 final Map<QName, Object> keyValues = argument.getKeyValues();
847 StringBuilder builder = new StringBuilder();
849 builder.append(nodeIdentifier);
852 List<QName> keyDefinition = node.getKeyDefinition();
853 boolean hasElements = false;
854 for (final QName key : keyDefinition) {
862 builder.append(this.toUriString(keyValues.get(key)));
863 } catch (UnsupportedEncodingException e) {
864 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
869 return builder.toString();
872 private static DataSchemaNode childByQName(final Object container, final QName name) {
873 if (container instanceof ChoiceCaseNode) {
874 return childByQName((ChoiceCaseNode) container, name);
875 } else if (container instanceof ChoiceNode) {
876 return childByQName((ChoiceNode) container, name);
877 } else if (container instanceof ContainerSchemaNode) {
878 return childByQName((ContainerSchemaNode) container, name);
879 } else if (container instanceof ListSchemaNode) {
880 return childByQName((ListSchemaNode) container, name);
881 } else if (container instanceof DataSchemaNode) {
882 return childByQName((DataSchemaNode) container, name);
883 } else if (container instanceof Module) {
884 return childByQName((Module) container, name);
886 throw new IllegalArgumentException("Unhandled parameter types: "
887 + Arrays.<Object> asList(container, name).toString());
891 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
892 final CompositeNode compositeNode) {
894 return dataNormalizer.toNormalized(legacy, compositeNode);
895 } catch (NullPointerException e) {
896 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
900 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
902 return dataNormalizer.toNormalized(legacy);
903 } catch (NullPointerException e) {
904 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
908 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
909 final NormalizedNode<?,?> normalizedNode) {
911 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
912 } catch (NullPointerException e) {
913 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
917 public DataNormalizationOperation<?> getRootOperation() {
918 return dataNormalizer.getRootOperation();