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 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
371 public boolean apply(final GroupingDefinition g) {
372 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
376 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
377 Module restconfModule = getRestconfModule();
378 if (restconfModule == null) {
382 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
384 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_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 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
395 public boolean apply(final GroupingDefinition g) {
396 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
400 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
401 Module restconfModule = inRestconfModule;
402 if (restconfModule == null) {
403 restconfModule = getRestconfModule();
406 if (restconfModule == null) {
410 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
411 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
412 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
414 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
415 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
416 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
418 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
419 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
420 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
421 return Iterables.getFirst(instances, null);
422 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
423 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
424 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
425 return Iterables.getFirst(instances, null);
426 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
427 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
428 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
429 final DataSchemaNode modules = Iterables.getFirst(instances, null);
430 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
431 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
432 return Iterables.getFirst(instances, null);
433 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
434 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
435 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
436 return Iterables.getFirst(instances, null);
437 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
438 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
439 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
440 final DataSchemaNode modules = Iterables.getFirst(instances, null);
441 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
442 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
443 return Iterables.getFirst(instances, null);
444 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
445 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
446 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
453 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
454 for (final ChoiceCaseNode caze : container.getCases()) {
455 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
464 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
465 return container.getDataChildByName(name);
468 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
469 return ControllerContext.dataNodeChildByQName(container, name);
472 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
473 return ControllerContext.dataNodeChildByQName(container, name);
476 private static DataSchemaNode childByQName(final Module container, final QName name) {
477 return ControllerContext.dataNodeChildByQName(container, name);
480 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
484 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
485 DataSchemaNode ret = container.getDataChildByName(name);
487 for (final DataSchemaNode node : container.getChildNodes()) {
488 if ((node instanceof ChoiceNode)) {
489 final ChoiceNode choiceNode = ((ChoiceNode) node);
490 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
491 if (childByQName != null) {
500 private String toUriString(final Object object) throws UnsupportedEncodingException {
501 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
504 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
505 final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
506 final boolean returnJustMountPoint) {
507 Preconditions.<List<String>> checkNotNull(strings);
509 if (parentNode == null) {
513 if (strings.isEmpty()) {
514 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
517 String head = strings.iterator().next();
518 final String nodeName = toNodeName(head);
519 final String moduleName = ControllerContext.toModuleName(head);
521 DataSchemaNode targetNode = null;
522 if (!Strings.isNullOrEmpty(moduleName)) {
523 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
524 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
525 if (mountPoint != null) {
526 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
527 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
530 if (mountService == null) {
531 throw new RestconfDocumentedException(
532 "MountService was not found. Finding behind mount points does not work.",
533 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
536 final YangInstanceIdentifier partialPath = builder.toInstance();
537 final MountInstance mount = mountService.getMountPoint(partialPath);
539 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
540 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
541 ErrorTag.UNKNOWN_ELEMENT);
544 final SchemaContext mountPointSchema = mount.getSchemaContext();
545 if (mountPointSchema == null) {
546 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
547 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
550 if (returnJustMountPoint) {
551 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
552 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
555 if (strings.size() == 1) {
556 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
557 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
560 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
561 if (moduleNameBehindMountPoint == null) {
562 throw new RestconfDocumentedException(
563 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
564 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
567 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
568 if (moduleBehindMountPoint == null) {
569 throw new RestconfDocumentedException("\"" + moduleName
570 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
573 List<String> subList = strings.subList(1, strings.size());
574 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
575 returnJustMountPoint);
578 Module module = null;
579 if (mountPoint == null) {
580 module = globalSchema.findModuleByName(moduleName, null);
581 if (module == null) {
582 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
583 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
586 SchemaContext schemaContext = mountPoint.getSchemaContext();
587 if (schemaContext != null) {
588 module = schemaContext.findModuleByName(moduleName, null);
592 if (module == null) {
593 throw new RestconfDocumentedException("\"" + moduleName
594 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
598 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
599 if (targetNode == null) {
600 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
601 + "\" was not found in parent data node.\n" + " 2. \"" + head
602 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
603 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
606 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
607 if (potentialSchemaNodes.size() > 1) {
608 final StringBuilder strBuilder = new StringBuilder();
609 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
610 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
613 throw new RestconfDocumentedException(
614 "URI has bad format. Node \""
616 + "\" is added as augment from more than one module. "
617 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
618 + "\nThe node is added as augment from modules with namespaces:\n"
619 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
622 if (potentialSchemaNodes.isEmpty()) {
623 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
624 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
627 targetNode = potentialSchemaNodes.iterator().next();
630 if (!ControllerContext.isListOrContainer(targetNode)) {
631 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
632 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
636 if ((targetNode instanceof ListSchemaNode)) {
637 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
638 final int keysSize = listNode.getKeyDefinition().size();
639 if ((strings.size() - consumed) < keysSize) {
640 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
641 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
644 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
645 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
647 for (final QName key : listNode.getKeyDefinition()) {
649 final String uriKeyValue = uriKeyValues.get(i);
650 if (uriKeyValue.equals(NULL_VALUE)) {
651 throw new RestconfDocumentedException("URI has bad format. List \""
652 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
653 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
656 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
661 consumed = consumed + i;
662 builder.nodeWithKey(targetNode.getQName(), keyValues);
664 builder.node(targetNode.getQName());
667 if ((targetNode instanceof DataNodeContainer)) {
668 final List<String> remaining = strings.subList(consumed, strings.size());
669 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
670 returnJustMountPoint);
673 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
676 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
677 final URI namespace) {
678 Preconditions.<URI> checkNotNull(namespace);
680 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
682 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
684 public boolean apply(final DataSchemaNode node) {
685 return Objects.equal(node.getQName().getNamespace(), namespace);
689 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
690 return Iterables.getFirst(result, null);
693 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
694 Preconditions.<DataNodeContainer> checkNotNull(container);
695 Preconditions.<String> checkNotNull(name);
697 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
698 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
699 return instantiatedDataNodeContainers;
702 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
704 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
705 return node.getCases();
709 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
710 final DataNodeContainer container, final String name) {
712 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
714 public boolean apply(final DataSchemaNode node) {
715 return Objects.equal(node.getQName().getLocalName(), name);
719 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
721 // Can't combine this loop with the filter above because the filter is
722 // lazily-applied by Iterables.filter.
723 for (final DataSchemaNode potentialNode : nodes) {
724 if (this.isInstantiatedDataSchema(potentialNode)) {
725 potentialSchemaNodes.add(potentialNode);
729 Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
730 Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
732 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
733 for (final ChoiceCaseNode caze : allCases) {
734 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
738 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
739 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
740 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
741 || node instanceof AnyXmlSchemaNode;
744 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
745 final MountInstance mountPoint) {
746 Preconditions.<String> checkNotNull(uriValue);
747 Preconditions.checkArgument((node instanceof LeafSchemaNode));
749 final String urlDecoded = urlPathArgDecode(uriValue);
750 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
751 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
753 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
754 String additionalInfo = "";
755 if (decoded == null) {
756 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
757 if ((baseType instanceof IdentityrefTypeDefinition)) {
758 decoded = this.toQName(urlDecoded);
759 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
763 if (decoded == null) {
764 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
765 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
768 map.put(node.getQName(), decoded);
771 private static String toModuleName(final String str) {
772 final int idx = str.indexOf(':');
777 // Make sure there is only one occurrence
778 if (str.indexOf(':', idx + 1) != -1) {
782 return str.substring(0, idx);
785 private static String toNodeName(final String str) {
786 final int idx = str.indexOf(':');
791 // Make sure there is only one occurrence
792 if (str.indexOf(':', idx + 1) != -1) {
796 return str.substring(idx + 1);
799 private QName toQName(final String name) {
800 final String module = toModuleName(name);
801 final String node = toNodeName(name);
802 final Module m = globalSchema.findModuleByName(module, null);
803 return m == null ? null : QName.create(m.getQNameModule(), node);
806 private static boolean isListOrContainer(final DataSchemaNode node) {
807 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
810 public RpcDefinition getRpcDefinition(final String name) {
811 final QName validName = this.toQName(name);
812 return validName == null ? null : this.qnameToRpc.get().get(validName);
816 public void onGlobalContextUpdated(final SchemaContext context) {
817 if (context != null) {
818 final Collection<RpcDefinition> defs = context.getOperations();
819 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
821 for (final RpcDefinition operation : defs) {
822 newMap.put(operation.getQName(), operation);
825 // FIXME: still not completely atomic
826 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
827 this.setGlobalSchema(context);
831 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
833 List<String> decodedPathArgs = new ArrayList<String>();
834 for (final String pathArg : strings) {
835 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
836 decodedPathArgs.add(_decode);
838 return decodedPathArgs;
839 } catch (UnsupportedEncodingException e) {
840 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
841 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
845 public String urlPathArgDecode(final String pathArg) {
846 if (pathArg != null) {
848 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
849 } catch (UnsupportedEncodingException e) {
850 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
851 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
858 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
859 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
860 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
861 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
862 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
863 } else if (argument != null && node != null) {
864 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
866 throw new IllegalArgumentException("Unhandled parameter types: "
867 + Arrays.<Object> asList(argument, node).toString());
871 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
872 StringBuilder builder = new StringBuilder();
874 QName nodeType = argument.getNodeType();
875 builder.append(this.toRestconfIdentifier(nodeType));
876 return builder.toString();
879 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
880 final ListSchemaNode node) {
881 QName nodeType = argument.getNodeType();
882 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
883 final Map<QName, Object> keyValues = argument.getKeyValues();
885 StringBuilder builder = new StringBuilder();
887 builder.append(nodeIdentifier);
890 List<QName> keyDefinition = node.getKeyDefinition();
891 boolean hasElements = false;
892 for (final QName key : keyDefinition) {
900 builder.append(this.toUriString(keyValues.get(key)));
901 } catch (UnsupportedEncodingException e) {
902 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
907 return builder.toString();
910 private static DataSchemaNode childByQName(final Object container, final QName name) {
911 if (container instanceof ChoiceCaseNode) {
912 return childByQName((ChoiceCaseNode) container, name);
913 } else if (container instanceof ChoiceNode) {
914 return childByQName((ChoiceNode) container, name);
915 } else if (container instanceof ContainerSchemaNode) {
916 return childByQName((ContainerSchemaNode) container, name);
917 } else if (container instanceof ListSchemaNode) {
918 return childByQName((ListSchemaNode) container, name);
919 } else if (container instanceof DataSchemaNode) {
920 return childByQName((DataSchemaNode) container, name);
921 } else if (container instanceof Module) {
922 return childByQName((Module) container, name);
924 throw new IllegalArgumentException("Unhandled parameter types: "
925 + Arrays.<Object> asList(container, name).toString());