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.BiMap;
18 import com.google.common.collect.HashBiMap;
19 import com.google.common.collect.ImmutableMap;
20 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;
34 import javax.ws.rs.core.Response.Status;
35 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
36 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
37 import org.opendaylight.controller.sal.rest.api.Draft02;
38 import org.opendaylight.controller.sal.rest.impl.RestUtil;
39 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
40 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
41 import org.opendaylight.yangtools.concepts.Codec;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
50 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
55 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
62 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 public class ControllerContext implements SchemaContextListener {
68 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
70 private final static ControllerContext INSTANCE = new ControllerContext();
72 private final static String NULL_VALUE = "null";
74 private final static String MOUNT_MODULE = "yang-ext";
76 private final static String MOUNT_NODE = "mount";
78 public final static String MOUNT = "yang-ext:mount";
80 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
82 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
84 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
86 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
88 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
89 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
91 private volatile SchemaContext globalSchema;
92 private volatile DOMMountPointService mountService;
94 public void setGlobalSchema(final SchemaContext globalSchema) {
95 this.globalSchema = globalSchema;
98 public void setMountService(final DOMMountPointService mountService) {
99 this.mountService = mountService;
102 private ControllerContext() {
105 public static ControllerContext getInstance() {
106 return ControllerContext.INSTANCE;
109 private void checkPreconditions() {
110 if (globalSchema == null) {
111 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
115 public void setSchemas(final SchemaContext schemas) {
116 this.onGlobalContextUpdated(schemas);
119 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
120 return this.toIdentifier(restconfInstance, false);
123 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
124 return this.toIdentifier(restconfInstance, true);
127 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
128 this.checkPreconditions();
130 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
131 omitFirstAndLastEmptyString(pathArgs);
132 if (pathArgs.isEmpty()) {
136 String first = pathArgs.iterator().next();
137 final String startModule = ControllerContext.toModuleName(first);
138 if (startModule == null) {
139 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
140 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
143 InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
144 Module latestModule = globalSchema.findModuleByName(startModule, null);
145 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
146 toMountPointIdentifier);
148 if (iiWithSchemaNode == null) {
149 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
152 return iiWithSchemaNode;
155 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
156 if (list.isEmpty()) {
160 String head = list.iterator().next();
161 if (head.isEmpty()) {
165 if (list.isEmpty()) {
169 String last = list.get(list.size() - 1);
170 if (last.isEmpty()) {
171 list.remove(list.size() - 1);
176 public Module findModuleByName(final String moduleName) {
177 this.checkPreconditions();
178 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
179 return globalSchema.findModuleByName(moduleName, null);
182 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
183 Preconditions.checkArgument(moduleName != null && mountPoint != null);
185 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
186 if (mountPointSchema == null) {
190 return mountPointSchema.findModuleByName(moduleName, null);
193 public Module findModuleByNamespace(final URI namespace) {
194 this.checkPreconditions();
195 Preconditions.checkArgument(namespace != null);
196 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
199 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
200 Preconditions.checkArgument(namespace != null && mountPoint != null);
202 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
203 if (mountPointSchema == null) {
207 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
210 public Module findModuleByNameAndRevision(final QName module) {
211 this.checkPreconditions();
212 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
214 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
217 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
218 this.checkPreconditions();
219 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
220 && mountPoint != null);
222 SchemaContext schemaContext = mountPoint.getSchemaContext();
223 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
224 module.getRevision());
227 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
228 this.checkPreconditions();
230 final Iterable<PathArgument> elements = path.getPathArguments();
231 PathArgument head = elements.iterator().next();
232 final QName startQName = head.getNodeType();
233 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
234 startQName.getRevision());
235 DataNodeContainer node = initialModule;
236 for (final PathArgument element : elements) {
237 QName _nodeType = element.getNodeType();
238 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
239 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
242 node = (DataNodeContainer) potentialNode;
248 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
249 this.checkPreconditions();
251 final Iterable<PathArgument> elements = path.getPathArguments();
252 final StringBuilder builder = new StringBuilder();
253 PathArgument head = elements.iterator().next();
254 final QName startQName = head.getNodeType();
255 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
256 startQName.getRevision());
257 DataNodeContainer node = initialModule;
258 for (final PathArgument element : elements) {
259 QName _nodeType = element.getNodeType();
260 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
261 if (!ControllerContext.isListOrContainer(potentialNode)) {
264 node = ((DataNodeContainer) potentialNode);
265 builder.append(this.convertToRestconfIdentifier(element, node));
268 return builder.toString();
271 public String findModuleNameByNamespace(final URI namespace) {
272 this.checkPreconditions();
274 String moduleName = this.uriToModuleName.get(namespace);
275 if (moduleName == null) {
276 final Module module = this.findModuleByNamespace(namespace);
277 if (module != null) {
278 moduleName = module.getName();
279 this.uriToModuleName.put(namespace, moduleName);
286 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
287 final Module module = this.findModuleByNamespace(mountPoint, namespace);
288 return module == null ? null : module.getName();
291 public URI findNamespaceByModuleName(final String moduleName) {
292 URI namespace = this.moduleNameToUri.get(moduleName);
293 if (namespace == null) {
294 Module module = this.findModuleByName(moduleName);
295 if (module != null) {
296 URI _namespace = module.getNamespace();
297 namespace = _namespace;
298 this.uriToModuleName.put(namespace, moduleName);
304 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
305 final Module module = this.findModuleByName(mountPoint, moduleName);
306 return module == null ? null : module.getNamespace();
309 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
310 this.checkPreconditions();
312 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
313 return schemaContext == null ? null : schemaContext.getModules();
316 public Set<Module> getAllModules() {
317 this.checkPreconditions();
318 return globalSchema.getModules();
321 public CharSequence toRestconfIdentifier(final QName qname) {
322 this.checkPreconditions();
324 String module = this.uriToModuleName.get(qname.getNamespace());
325 if (module == null) {
326 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
327 qname.getRevision());
328 if (moduleSchema == null) {
332 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
333 module = moduleSchema.getName();
336 StringBuilder builder = new StringBuilder();
337 builder.append(module);
339 builder.append(qname.getLocalName());
340 return builder.toString();
343 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
344 if (mountPoint == null) {
348 SchemaContext schemaContext = mountPoint.getSchemaContext();
350 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
351 qname.getRevision());
352 if (moduleSchema == null) {
356 StringBuilder builder = new StringBuilder();
357 builder.append(moduleSchema.getName());
359 builder.append(qname.getLocalName());
360 return builder.toString();
363 public Module getRestconfModule() {
364 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
367 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
368 Module restconfModule = getRestconfModule();
369 if (restconfModule == null) {
373 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
375 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
377 public boolean apply(final GroupingDefinition g) {
378 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
382 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
384 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
386 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
387 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
388 return Iterables.getFirst(instanceDataChildrenByName, null);
391 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
392 Module restconfModule = inRestconfModule;
393 if (restconfModule == null) {
394 restconfModule = getRestconfModule();
397 if (restconfModule == null) {
401 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
403 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
405 public boolean apply(final GroupingDefinition g) {
406 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
410 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, 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 DOMMountPoint 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 Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
538 if (!mountOpt.isPresent()) {
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);
543 DOMMountPoint mount = mountOpt.get();
545 final SchemaContext mountPointSchema = mount.getSchemaContext();
546 if (mountPointSchema == null) {
547 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
548 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
551 if (returnJustMountPoint) {
552 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
553 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
556 if (strings.size() == 1) {
557 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
558 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
561 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
562 if (moduleNameBehindMountPoint == null) {
563 throw new RestconfDocumentedException(
564 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
565 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
568 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
569 if (moduleBehindMountPoint == null) {
570 throw new RestconfDocumentedException("\"" + moduleName
571 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
574 List<String> subList = strings.subList(1, strings.size());
575 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
576 returnJustMountPoint);
579 Module module = null;
580 if (mountPoint == null) {
581 module = globalSchema.findModuleByName(moduleName, null);
582 if (module == null) {
583 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
584 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
587 SchemaContext schemaContext = mountPoint.getSchemaContext();
588 if (schemaContext != null) {
589 module = schemaContext.findModuleByName(moduleName, null);
593 if (module == null) {
594 throw new RestconfDocumentedException("\"" + moduleName
595 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
599 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
600 if (targetNode == null) {
601 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
602 + "\" was not found in parent data node.\n" + " 2. \"" + head
603 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
604 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
607 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
608 if (potentialSchemaNodes.size() > 1) {
609 final StringBuilder strBuilder = new StringBuilder();
610 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
611 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
614 throw new RestconfDocumentedException(
615 "URI has bad format. Node \""
617 + "\" is added as augment from more than one module. "
618 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
619 + "\nThe node is added as augment from modules with namespaces:\n"
620 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
623 if (potentialSchemaNodes.isEmpty()) {
624 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
625 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
628 targetNode = potentialSchemaNodes.iterator().next();
631 if (!ControllerContext.isListOrContainer(targetNode)) {
632 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
633 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
637 if ((targetNode instanceof ListSchemaNode)) {
638 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
639 final int keysSize = listNode.getKeyDefinition().size();
640 if ((strings.size() - consumed) < keysSize) {
641 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
642 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
645 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
646 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
648 for (final QName key : listNode.getKeyDefinition()) {
650 final String uriKeyValue = uriKeyValues.get(i);
651 if (uriKeyValue.equals(NULL_VALUE)) {
652 throw new RestconfDocumentedException("URI has bad format. List \""
653 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
654 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
657 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
662 consumed = consumed + i;
663 builder.nodeWithKey(targetNode.getQName(), keyValues);
665 builder.node(targetNode.getQName());
668 if ((targetNode instanceof DataNodeContainer)) {
669 final List<String> remaining = strings.subList(consumed, strings.size());
670 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
671 returnJustMountPoint);
674 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
677 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
678 final URI namespace) {
679 Preconditions.<URI> checkNotNull(namespace);
681 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
683 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
685 public boolean apply(final DataSchemaNode node) {
686 return Objects.equal(node.getQName().getNamespace(), namespace);
690 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
691 return Iterables.getFirst(result, null);
694 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
695 Preconditions.<DataNodeContainer> checkNotNull(container);
696 Preconditions.<String> checkNotNull(name);
698 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
699 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
700 return instantiatedDataNodeContainers;
703 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
704 final DataNodeContainer container, final String name) {
706 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
708 public boolean apply(final DataSchemaNode node) {
709 return Objects.equal(node.getQName().getLocalName(), name);
713 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
715 // Can't combine this loop with the filter above because the filter is
716 // lazily-applied by Iterables.filter.
717 for (final DataSchemaNode potentialNode : nodes) {
718 if (this.isInstantiatedDataSchema(potentialNode)) {
719 potentialSchemaNodes.add(potentialNode);
723 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
725 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
727 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
728 return node.getCases();
732 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
735 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
736 for (final ChoiceCaseNode caze : allCases) {
737 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
741 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
742 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
743 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
744 || node instanceof AnyXmlSchemaNode;
747 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
748 final DOMMountPoint mountPoint) {
749 Preconditions.<String> checkNotNull(uriValue);
750 Preconditions.checkArgument((node instanceof LeafSchemaNode));
752 final String urlDecoded = urlPathArgDecode(uriValue);
753 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
754 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
756 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
757 String additionalInfo = "";
758 if (decoded == null) {
759 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
760 if ((baseType instanceof IdentityrefTypeDefinition)) {
761 decoded = this.toQName(urlDecoded);
762 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
766 if (decoded == null) {
767 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
768 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
771 map.put(node.getQName(), decoded);
774 private static String toModuleName(final String str) {
775 final int idx = str.indexOf(':');
780 // Make sure there is only one occurrence
781 if (str.indexOf(':', idx + 1) != -1) {
785 return str.substring(0, idx);
788 private static String toNodeName(final String str) {
789 final int idx = str.indexOf(':');
794 // Make sure there is only one occurrence
795 if (str.indexOf(':', idx + 1) != -1) {
799 return str.substring(idx + 1);
802 private QName toQName(final String name) {
803 final String module = toModuleName(name);
804 final String node = toNodeName(name);
805 final Module m = globalSchema.findModuleByName(module, null);
806 return m == null ? null : QName.create(m.getQNameModule(), node);
809 private static boolean isListOrContainer(final DataSchemaNode node) {
810 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
813 public RpcDefinition getRpcDefinition(final String name) {
814 final QName validName = this.toQName(name);
815 return validName == null ? null : this.qnameToRpc.get().get(validName);
819 public void onGlobalContextUpdated(final SchemaContext context) {
820 if (context != null) {
821 final Collection<RpcDefinition> defs = context.getOperations();
822 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
824 for (final RpcDefinition operation : defs) {
825 newMap.put(operation.getQName(), operation);
828 // FIXME: still not completely atomic
829 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
830 this.setGlobalSchema(context);
834 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
836 List<String> decodedPathArgs = new ArrayList<String>();
837 for (final String pathArg : strings) {
838 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
839 decodedPathArgs.add(_decode);
841 return decodedPathArgs;
842 } catch (UnsupportedEncodingException e) {
843 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
844 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
848 public String urlPathArgDecode(final String pathArg) {
849 if (pathArg != null) {
851 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
852 } catch (UnsupportedEncodingException e) {
853 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
854 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
861 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
862 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
863 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
864 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
865 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
866 } else if (argument != null && node != null) {
867 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
869 throw new IllegalArgumentException("Unhandled parameter types: "
870 + Arrays.<Object> asList(argument, node).toString());
874 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
875 StringBuilder builder = new StringBuilder();
877 QName nodeType = argument.getNodeType();
878 builder.append(this.toRestconfIdentifier(nodeType));
879 return builder.toString();
882 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
883 final ListSchemaNode node) {
884 QName nodeType = argument.getNodeType();
885 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
886 final Map<QName, Object> keyValues = argument.getKeyValues();
888 StringBuilder builder = new StringBuilder();
890 builder.append(nodeIdentifier);
893 List<QName> keyDefinition = node.getKeyDefinition();
894 boolean hasElements = false;
895 for (final QName key : keyDefinition) {
903 builder.append(this.toUriString(keyValues.get(key)));
904 } catch (UnsupportedEncodingException e) {
905 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
910 return builder.toString();
913 private static DataSchemaNode childByQName(final Object container, final QName name) {
914 if (container instanceof ChoiceCaseNode) {
915 return childByQName((ChoiceCaseNode) container, name);
916 } else if (container instanceof ChoiceNode) {
917 return childByQName((ChoiceNode) container, name);
918 } else if (container instanceof ContainerSchemaNode) {
919 return childByQName((ContainerSchemaNode) container, name);
920 } else if (container instanceof ListSchemaNode) {
921 return childByQName((ListSchemaNode) container, name);
922 } else if (container instanceof DataSchemaNode) {
923 return childByQName((DataSchemaNode) container, name);
924 } else if (container instanceof Module) {
925 return childByQName((Module) container, name);
927 throw new IllegalArgumentException("Unhandled parameter types: "
928 + Arrays.<Object> asList(container, name).toString());