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.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.BiMap;
17 import com.google.common.collect.HashBiMap;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Iterables;
21 import java.io.UnsupportedEncodingException;
23 import java.net.URLDecoder;
24 import java.net.URLEncoder;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
33 import java.util.concurrent.atomic.AtomicReference;
35 import javax.ws.rs.core.Response.Status;
37 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
38 import org.opendaylight.controller.sal.core.api.mount.MountService;
39 import org.opendaylight.controller.sal.rest.api.Draft02;
40 import org.opendaylight.controller.sal.rest.impl.RestUtil;
41 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
43 import org.opendaylight.yangtools.concepts.Codec;
44 import org.opendaylight.yangtools.yang.common.QName;
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.model.api.AnyXmlSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
53 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class ControllerContext implements SchemaContextListener {
70 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
72 private final static ControllerContext INSTANCE = new ControllerContext();
74 private final static String NULL_VALUE = "null";
76 private final static String MOUNT_MODULE = "yang-ext";
78 private final static String MOUNT_NODE = "mount";
80 public final static String MOUNT = "yang-ext:mount";
82 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
84 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
86 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
88 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
90 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
91 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
93 private volatile SchemaContext globalSchema;
94 private volatile MountService mountService;
96 public void setGlobalSchema(final SchemaContext globalSchema) {
97 this.globalSchema = globalSchema;
100 public void setMountService(final MountService 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 MountInstance 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 MountInstance 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 MountInstance 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 String moduleName = this.uriToModuleName.get(namespace);
277 if (moduleName == null) {
278 final Module module = this.findModuleByNamespace(namespace);
279 if (module != null) {
280 moduleName = module.getName();
281 this.uriToModuleName.put(namespace, moduleName);
288 public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
289 final Module module = this.findModuleByNamespace(mountPoint, namespace);
290 return module == null ? null : module.getName();
293 public URI findNamespaceByModuleName(final String moduleName) {
294 URI namespace = this.moduleNameToUri.get(moduleName);
295 if (namespace == null) {
296 Module module = this.findModuleByName(moduleName);
297 if (module != null) {
298 URI _namespace = module.getNamespace();
299 namespace = _namespace;
300 this.uriToModuleName.put(namespace, moduleName);
306 public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
307 final Module module = this.findModuleByName(mountPoint, moduleName);
308 return module == null ? null : module.getNamespace();
311 public Set<Module> getAllModules(final MountInstance mountPoint) {
312 this.checkPreconditions();
314 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
315 return schemaContext == null ? null : schemaContext.getModules();
318 public Set<Module> getAllModules() {
319 this.checkPreconditions();
320 return globalSchema.getModules();
323 public CharSequence toRestconfIdentifier(final QName qname) {
324 this.checkPreconditions();
326 String module = this.uriToModuleName.get(qname.getNamespace());
327 if (module == null) {
328 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
329 qname.getRevision());
330 if (moduleSchema == null) {
334 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
335 module = moduleSchema.getName();
338 StringBuilder builder = new StringBuilder();
339 builder.append(module);
341 builder.append(qname.getLocalName());
342 return builder.toString();
345 public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
346 if (mountPoint == null) {
350 SchemaContext schemaContext = mountPoint.getSchemaContext();
352 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
353 qname.getRevision());
354 if (moduleSchema == null) {
358 StringBuilder builder = new StringBuilder();
359 builder.append(moduleSchema.getName());
361 builder.append(qname.getLocalName());
362 return builder.toString();
365 public Module getRestconfModule() {
366 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
369 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
370 Module restconfModule = getRestconfModule();
371 if (restconfModule == null) {
375 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
377 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
379 public boolean apply(final GroupingDefinition g) {
380 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
384 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
386 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
388 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
389 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
390 return Iterables.getFirst(instanceDataChildrenByName, null);
393 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
394 Module restconfModule = inRestconfModule;
395 if (restconfModule == null) {
396 restconfModule = getRestconfModule();
399 if (restconfModule == null) {
403 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
405 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
407 public boolean apply(final GroupingDefinition g) {
408 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
412 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
414 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
416 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
417 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
418 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
420 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
421 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
422 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
423 return Iterables.getFirst(instances, null);
424 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
425 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
426 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
427 return Iterables.getFirst(instances, null);
428 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
429 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
430 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
431 final DataSchemaNode modules = Iterables.getFirst(instances, null);
432 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
433 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
434 return Iterables.getFirst(instances, null);
435 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
436 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
437 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
438 return Iterables.getFirst(instances, null);
439 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
440 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
441 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
442 final DataSchemaNode modules = Iterables.getFirst(instances, null);
443 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
444 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
445 return Iterables.getFirst(instances, null);
446 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
447 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
448 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
449 return Iterables.getFirst(instances, null);
455 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
456 for (final ChoiceCaseNode caze : container.getCases()) {
457 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
466 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
467 return container.getDataChildByName(name);
470 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
471 return ControllerContext.dataNodeChildByQName(container, name);
474 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
475 return ControllerContext.dataNodeChildByQName(container, name);
478 private static DataSchemaNode childByQName(final Module container, final QName name) {
479 return ControllerContext.dataNodeChildByQName(container, name);
482 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
486 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
487 DataSchemaNode ret = container.getDataChildByName(name);
489 for (final DataSchemaNode node : container.getChildNodes()) {
490 if ((node instanceof ChoiceNode)) {
491 final ChoiceNode choiceNode = ((ChoiceNode) node);
492 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
493 if (childByQName != null) {
502 private String toUriString(final Object object) throws UnsupportedEncodingException {
503 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
506 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
507 final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
508 final boolean returnJustMountPoint) {
509 Preconditions.<List<String>> checkNotNull(strings);
511 if (parentNode == null) {
515 if (strings.isEmpty()) {
516 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
519 String head = strings.iterator().next();
520 final String nodeName = toNodeName(head);
521 final String moduleName = ControllerContext.toModuleName(head);
523 DataSchemaNode targetNode = null;
524 if (!Strings.isNullOrEmpty(moduleName)) {
525 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
526 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
527 if (mountPoint != null) {
528 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
529 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
532 if (mountService == null) {
533 throw new RestconfDocumentedException(
534 "MountService was not found. Finding behind mount points does not work.",
535 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
538 final YangInstanceIdentifier partialPath = builder.toInstance();
539 final MountInstance mount = mountService.getMountPoint(partialPath);
541 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
542 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
543 ErrorTag.UNKNOWN_ELEMENT);
546 final SchemaContext mountPointSchema = mount.getSchemaContext();
547 if (mountPointSchema == null) {
548 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
549 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
552 if (returnJustMountPoint) {
553 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
554 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
557 if (strings.size() == 1) {
558 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
559 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
562 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
563 if (moduleNameBehindMountPoint == null) {
564 throw new RestconfDocumentedException(
565 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
566 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
569 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
570 if (moduleBehindMountPoint == null) {
571 throw new RestconfDocumentedException("\"" + moduleName
572 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
575 List<String> subList = strings.subList(1, strings.size());
576 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
577 returnJustMountPoint);
580 Module module = null;
581 if (mountPoint == null) {
582 module = globalSchema.findModuleByName(moduleName, null);
583 if (module == null) {
584 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
585 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
588 SchemaContext schemaContext = mountPoint.getSchemaContext();
589 if (schemaContext != null) {
590 module = schemaContext.findModuleByName(moduleName, null);
594 if (module == null) {
595 throw new RestconfDocumentedException("\"" + moduleName
596 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
600 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
601 if (targetNode == null) {
602 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
603 + "\" was not found in parent data node.\n" + " 2. \"" + head
604 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
605 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
608 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
609 if (potentialSchemaNodes.size() > 1) {
610 final StringBuilder strBuilder = new StringBuilder();
611 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
612 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
615 throw new RestconfDocumentedException(
616 "URI has bad format. Node \""
618 + "\" is added as augment from more than one module. "
619 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
620 + "\nThe node is added as augment from modules with namespaces:\n"
621 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
624 if (potentialSchemaNodes.isEmpty()) {
625 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
626 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
629 targetNode = potentialSchemaNodes.iterator().next();
632 if (!ControllerContext.isListOrContainer(targetNode)) {
633 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
634 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
638 if ((targetNode instanceof ListSchemaNode)) {
639 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
640 final int keysSize = listNode.getKeyDefinition().size();
641 if ((strings.size() - consumed) < keysSize) {
642 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
643 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
646 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
647 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
649 for (final QName key : listNode.getKeyDefinition()) {
651 final String uriKeyValue = uriKeyValues.get(i);
652 if (uriKeyValue.equals(NULL_VALUE)) {
653 throw new RestconfDocumentedException("URI has bad format. List \""
654 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
655 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
658 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
663 consumed = consumed + i;
664 builder.nodeWithKey(targetNode.getQName(), keyValues);
666 builder.node(targetNode.getQName());
669 if ((targetNode instanceof DataNodeContainer)) {
670 final List<String> remaining = strings.subList(consumed, strings.size());
671 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
672 returnJustMountPoint);
675 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
678 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
679 final URI namespace) {
680 Preconditions.<URI> checkNotNull(namespace);
682 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
684 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
686 public boolean apply(final DataSchemaNode node) {
687 return Objects.equal(node.getQName().getNamespace(), namespace);
691 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
692 return Iterables.getFirst(result, null);
695 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
696 Preconditions.<DataNodeContainer> checkNotNull(container);
697 Preconditions.<String> checkNotNull(name);
699 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
700 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
701 return instantiatedDataNodeContainers;
704 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
705 final DataNodeContainer container, final String name) {
707 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
709 public boolean apply(final DataSchemaNode node) {
710 return Objects.equal(node.getQName().getLocalName(), name);
714 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
716 // Can't combine this loop with the filter above because the filter is
717 // lazily-applied by Iterables.filter.
718 for (final DataSchemaNode potentialNode : nodes) {
719 if (this.isInstantiatedDataSchema(potentialNode)) {
720 potentialSchemaNodes.add(potentialNode);
724 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
726 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
728 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
729 return node.getCases();
733 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
736 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
737 for (final ChoiceCaseNode caze : allCases) {
738 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
742 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
743 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
744 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
745 || node instanceof AnyXmlSchemaNode;
748 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
749 final MountInstance mountPoint) {
750 Preconditions.<String> checkNotNull(uriValue);
751 Preconditions.checkArgument((node instanceof LeafSchemaNode));
753 final String urlDecoded = urlPathArgDecode(uriValue);
754 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
755 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
757 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
758 String additionalInfo = "";
759 if (decoded == null) {
760 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
761 if ((baseType instanceof IdentityrefTypeDefinition)) {
762 decoded = this.toQName(urlDecoded);
763 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
767 if (decoded == null) {
768 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
769 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
772 map.put(node.getQName(), decoded);
775 private static String toModuleName(final String str) {
776 final int idx = str.indexOf(':');
781 // Make sure there is only one occurrence
782 if (str.indexOf(':', idx + 1) != -1) {
786 return str.substring(0, idx);
789 private static String toNodeName(final String str) {
790 final int idx = str.indexOf(':');
795 // Make sure there is only one occurrence
796 if (str.indexOf(':', idx + 1) != -1) {
800 return str.substring(idx + 1);
803 private QName toQName(final String name) {
804 final String module = toModuleName(name);
805 final String node = toNodeName(name);
806 final Module m = globalSchema.findModuleByName(module, null);
807 return m == null ? null : QName.create(m.getQNameModule(), node);
810 private static boolean isListOrContainer(final DataSchemaNode node) {
811 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
814 public RpcDefinition getRpcDefinition(final String name) {
815 final QName validName = this.toQName(name);
816 return validName == null ? null : this.qnameToRpc.get().get(validName);
820 public void onGlobalContextUpdated(final SchemaContext context) {
821 if (context != null) {
822 final Collection<RpcDefinition> defs = context.getOperations();
823 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
825 for (final RpcDefinition operation : defs) {
826 newMap.put(operation.getQName(), operation);
829 // FIXME: still not completely atomic
830 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
831 this.setGlobalSchema(context);
835 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
837 List<String> decodedPathArgs = new ArrayList<String>();
838 for (final String pathArg : strings) {
839 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
840 decodedPathArgs.add(_decode);
842 return decodedPathArgs;
843 } catch (UnsupportedEncodingException e) {
844 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
845 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
849 public String urlPathArgDecode(final String pathArg) {
850 if (pathArg != null) {
852 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
853 } catch (UnsupportedEncodingException e) {
854 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
855 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
862 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
863 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
864 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
865 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
866 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
867 } else if (argument != null && node != null) {
868 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
870 throw new IllegalArgumentException("Unhandled parameter types: "
871 + Arrays.<Object> asList(argument, node).toString());
875 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
876 StringBuilder builder = new StringBuilder();
878 QName nodeType = argument.getNodeType();
879 builder.append(this.toRestconfIdentifier(nodeType));
880 return builder.toString();
883 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
884 final ListSchemaNode node) {
885 QName nodeType = argument.getNodeType();
886 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
887 final Map<QName, Object> keyValues = argument.getKeyValues();
889 StringBuilder builder = new StringBuilder();
891 builder.append(nodeIdentifier);
894 List<QName> keyDefinition = node.getKeyDefinition();
895 boolean hasElements = false;
896 for (final QName key : keyDefinition) {
904 builder.append(this.toUriString(keyValues.get(key)));
905 } catch (UnsupportedEncodingException e) {
906 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
911 return builder.toString();
914 private static DataSchemaNode childByQName(final Object container, final QName name) {
915 if (container instanceof ChoiceCaseNode) {
916 return childByQName((ChoiceCaseNode) container, name);
917 } else if (container instanceof ChoiceNode) {
918 return childByQName((ChoiceNode) container, name);
919 } else if (container instanceof ContainerSchemaNode) {
920 return childByQName((ContainerSchemaNode) container, name);
921 } else if (container instanceof ListSchemaNode) {
922 return childByQName((ListSchemaNode) container, name);
923 } else if (container instanceof DataSchemaNode) {
924 return childByQName((DataSchemaNode) container, name);
925 } else if (container instanceof Module) {
926 return childByQName((Module) container, name);
928 throw new IllegalArgumentException("Unhandled parameter types: "
929 + Arrays.<Object> asList(container, name).toString());