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 = this.getLatestModule(globalSchema, startModule);
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);
179 private Module getLatestModule(final SchemaContext schema, final String moduleName) {
180 Preconditions.checkArgument(schema != null);
181 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
183 Predicate<Module> filter = new Predicate<Module>() {
185 public boolean apply(final Module m) {
186 return Objects.equal(m.getName(), moduleName);
190 Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
191 return this.filterLatestModule(modules);
194 private Module filterLatestModule(final Iterable<Module> modules) {
195 Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
196 for (final Module module : modules) {
197 if (module.getRevision().after(latestModule.getRevision())) {
198 latestModule = module;
204 public Module findModuleByName(final String moduleName) {
205 this.checkPreconditions();
206 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
207 return this.getLatestModule(globalSchema, moduleName);
210 public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
211 Preconditions.checkArgument(moduleName != null && mountPoint != null);
213 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
214 return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
217 public Module findModuleByNamespace(final URI namespace) {
218 this.checkPreconditions();
219 Preconditions.checkArgument(namespace != null);
221 final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
222 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
225 public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
226 Preconditions.checkArgument(namespace != null && mountPoint != null);
228 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
229 Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
230 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
233 public Module findModuleByNameAndRevision(final QName module) {
234 this.checkPreconditions();
235 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
237 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
240 public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
241 this.checkPreconditions();
242 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
243 && mountPoint != null);
245 SchemaContext schemaContext = mountPoint.getSchemaContext();
246 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
247 module.getRevision());
250 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
251 this.checkPreconditions();
253 final Iterable<PathArgument> elements = path.getPathArguments();
254 PathArgument head = elements.iterator().next();
255 final QName startQName = head.getNodeType();
256 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
257 startQName.getRevision());
258 DataNodeContainer node = initialModule;
259 for (final PathArgument element : elements) {
260 QName _nodeType = element.getNodeType();
261 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
262 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
265 node = (DataNodeContainer) potentialNode;
271 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
272 this.checkPreconditions();
274 final Iterable<PathArgument> elements = path.getPathArguments();
275 final StringBuilder builder = new StringBuilder();
276 PathArgument head = elements.iterator().next();
277 final QName startQName = head.getNodeType();
278 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
279 startQName.getRevision());
280 DataNodeContainer node = initialModule;
281 for (final PathArgument element : elements) {
282 QName _nodeType = element.getNodeType();
283 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
284 if (!ControllerContext.isListOrContainer(potentialNode)) {
287 node = ((DataNodeContainer) potentialNode);
288 builder.append(this.convertToRestconfIdentifier(element, node));
291 return builder.toString();
294 public String findModuleNameByNamespace(final URI namespace) {
295 this.checkPreconditions();
297 String moduleName = this.uriToModuleName.get(namespace);
298 if (moduleName == null) {
299 final Module module = this.findModuleByNamespace(namespace);
300 if (module != null) {
301 moduleName = module.getName();
302 this.uriToModuleName.put(namespace, moduleName);
309 public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
310 final Module module = this.findModuleByNamespace(mountPoint, namespace);
311 return module == null ? null : module.getName();
314 public URI findNamespaceByModuleName(final String moduleName) {
315 URI namespace = this.moduleNameToUri.get(moduleName);
316 if (namespace == null) {
317 Module module = this.findModuleByName(moduleName);
318 if (module != null) {
319 URI _namespace = module.getNamespace();
320 namespace = _namespace;
321 this.uriToModuleName.put(namespace, moduleName);
327 public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
328 final Module module = this.findModuleByName(mountPoint, moduleName);
329 return module == null ? null : module.getNamespace();
332 public Set<Module> getAllModules(final MountInstance mountPoint) {
333 this.checkPreconditions();
335 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
336 return schemaContext == null ? null : schemaContext.getModules();
339 public Set<Module> getAllModules() {
340 this.checkPreconditions();
341 return globalSchema.getModules();
344 public CharSequence toRestconfIdentifier(final QName qname) {
345 this.checkPreconditions();
347 String module = this.uriToModuleName.get(qname.getNamespace());
348 if (module == null) {
349 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
350 qname.getRevision());
351 if (moduleSchema == null) {
355 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
356 module = moduleSchema.getName();
359 StringBuilder builder = new StringBuilder();
360 builder.append(module);
362 builder.append(qname.getLocalName());
363 return builder.toString();
366 public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
367 if (mountPoint == null) {
371 SchemaContext schemaContext = mountPoint.getSchemaContext();
373 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
374 qname.getRevision());
375 if (moduleSchema == null) {
379 StringBuilder builder = new StringBuilder();
380 builder.append(moduleSchema.getName());
382 builder.append(qname.getLocalName());
383 return builder.toString();
386 public Module getRestconfModule() {
387 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
390 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
391 Module restconfModule = getRestconfModule();
392 if (restconfModule == null) {
396 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
398 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
400 public boolean apply(final GroupingDefinition g) {
401 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
405 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
407 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
409 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
410 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
411 return Iterables.getFirst(instanceDataChildrenByName, null);
414 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
415 Module restconfModule = inRestconfModule;
416 if (restconfModule == null) {
417 restconfModule = getRestconfModule();
420 if (restconfModule == null) {
424 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
426 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
428 public boolean apply(final GroupingDefinition g) {
429 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
433 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
435 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
437 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
438 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
439 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
441 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
442 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
443 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
444 return Iterables.getFirst(instances, null);
445 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
446 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
447 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
448 return Iterables.getFirst(instances, null);
449 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
450 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
451 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
452 final DataSchemaNode modules = Iterables.getFirst(instances, null);
453 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
454 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
455 return Iterables.getFirst(instances, null);
456 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
457 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
458 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
459 return Iterables.getFirst(instances, null);
460 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
461 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
462 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
463 final DataSchemaNode modules = Iterables.getFirst(instances, null);
464 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
465 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
466 return Iterables.getFirst(instances, null);
467 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
468 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
469 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
470 return Iterables.getFirst(instances, null);
476 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
477 for (final ChoiceCaseNode caze : container.getCases()) {
478 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
487 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
488 return container.getDataChildByName(name);
491 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
492 return ControllerContext.dataNodeChildByQName(container, name);
495 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
496 return ControllerContext.dataNodeChildByQName(container, name);
499 private static DataSchemaNode childByQName(final Module container, final QName name) {
500 return ControllerContext.dataNodeChildByQName(container, name);
503 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
507 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
508 DataSchemaNode ret = container.getDataChildByName(name);
510 for (final DataSchemaNode node : container.getChildNodes()) {
511 if ((node instanceof ChoiceNode)) {
512 final ChoiceNode choiceNode = ((ChoiceNode) node);
513 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
514 if (childByQName != null) {
523 private String toUriString(final Object object) throws UnsupportedEncodingException {
524 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
527 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
528 final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
529 final boolean returnJustMountPoint) {
530 Preconditions.<List<String>> checkNotNull(strings);
532 if (parentNode == null) {
536 if (strings.isEmpty()) {
537 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
540 String head = strings.iterator().next();
541 final String nodeName = toNodeName(head);
542 final String moduleName = ControllerContext.toModuleName(head);
544 DataSchemaNode targetNode = null;
545 if (!Strings.isNullOrEmpty(moduleName)) {
546 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
547 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
548 if (mountPoint != null) {
549 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
550 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
553 if (mountService == null) {
554 throw new RestconfDocumentedException(
555 "MountService was not found. Finding behind mount points does not work.",
556 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
559 final YangInstanceIdentifier partialPath = builder.toInstance();
560 final MountInstance mount = mountService.getMountPoint(partialPath);
562 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
563 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
564 ErrorTag.UNKNOWN_ELEMENT);
567 final SchemaContext mountPointSchema = mount.getSchemaContext();
568 if (mountPointSchema == null) {
569 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
570 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
573 if (returnJustMountPoint) {
574 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
575 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
578 if (strings.size() == 1) {
579 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
580 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
583 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
584 if (moduleNameBehindMountPoint == null) {
585 throw new RestconfDocumentedException(
586 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
587 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
590 final Module moduleBehindMountPoint = this
591 .getLatestModule(mountPointSchema, moduleNameBehindMountPoint);
592 if (moduleBehindMountPoint == null) {
593 throw new RestconfDocumentedException("\"" + moduleName
594 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
597 List<String> subList = strings.subList(1, strings.size());
598 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
599 returnJustMountPoint);
602 Module module = null;
603 if (mountPoint == null) {
604 module = this.getLatestModule(globalSchema, moduleName);
605 if (module == null) {
606 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
607 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
610 SchemaContext schemaContext = mountPoint.getSchemaContext();
611 module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName);
612 if (module == null) {
613 throw new RestconfDocumentedException("\"" + moduleName
614 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
618 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
619 if (targetNode == null) {
620 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
621 + "\" was not found in parent data node.\n" + " 2. \"" + head
622 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
623 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
626 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
627 if (potentialSchemaNodes.size() > 1) {
628 final StringBuilder strBuilder = new StringBuilder();
629 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
630 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
633 throw new RestconfDocumentedException(
634 "URI has bad format. Node \""
636 + "\" is added as augment from more than one module. "
637 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
638 + "\nThe node is added as augment from modules with namespaces:\n"
639 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
642 if (potentialSchemaNodes.isEmpty()) {
643 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
644 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
647 targetNode = potentialSchemaNodes.iterator().next();
650 if (!ControllerContext.isListOrContainer(targetNode)) {
651 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
652 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
656 if ((targetNode instanceof ListSchemaNode)) {
657 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
658 final int keysSize = listNode.getKeyDefinition().size();
659 if ((strings.size() - consumed) < keysSize) {
660 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
661 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
664 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
665 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
667 for (final QName key : listNode.getKeyDefinition()) {
669 final String uriKeyValue = uriKeyValues.get(i);
670 if (uriKeyValue.equals(NULL_VALUE)) {
671 throw new RestconfDocumentedException("URI has bad format. List \""
672 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
673 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
676 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
681 consumed = consumed + i;
682 builder.nodeWithKey(targetNode.getQName(), keyValues);
684 builder.node(targetNode.getQName());
687 if ((targetNode instanceof DataNodeContainer)) {
688 final List<String> remaining = strings.subList(consumed, strings.size());
689 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
690 returnJustMountPoint);
693 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
696 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
697 final URI namespace) {
698 Preconditions.<URI> checkNotNull(namespace);
700 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
702 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
704 public boolean apply(final DataSchemaNode node) {
705 return Objects.equal(node.getQName().getNamespace(), namespace);
709 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
710 return Iterables.getFirst(result, null);
713 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
714 Preconditions.<DataNodeContainer> checkNotNull(container);
715 Preconditions.<String> checkNotNull(name);
717 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
718 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
719 return instantiatedDataNodeContainers;
722 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
723 final DataNodeContainer container, final String name) {
725 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
727 public boolean apply(final DataSchemaNode node) {
728 return Objects.equal(node.getQName().getLocalName(), name);
732 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
734 // Can't combine this loop with the filter above because the filter is
735 // lazily-applied by Iterables.filter.
736 for (final DataSchemaNode potentialNode : nodes) {
737 if (this.isInstantiatedDataSchema(potentialNode)) {
738 potentialSchemaNodes.add(potentialNode);
742 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
744 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
746 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
747 return node.getCases();
751 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
754 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
755 for (final ChoiceCaseNode caze : allCases) {
756 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
760 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
761 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
762 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
763 || node instanceof AnyXmlSchemaNode;
766 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
767 final MountInstance mountPoint) {
768 Preconditions.<String> checkNotNull(uriValue);
769 Preconditions.checkArgument((node instanceof LeafSchemaNode));
771 final String urlDecoded = urlPathArgDecode(uriValue);
772 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
773 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
775 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
776 String additionalInfo = "";
777 if (decoded == null) {
778 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
779 if ((baseType instanceof IdentityrefTypeDefinition)) {
780 decoded = this.toQName(urlDecoded);
781 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
785 if (decoded == null) {
786 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
787 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
790 map.put(node.getQName(), decoded);
793 private static String toModuleName(final String str) {
794 final int idx = str.indexOf(':');
799 // Make sure there is only one occurrence
800 if (str.indexOf(':', idx + 1) != -1) {
804 return str.substring(0, idx);
807 private static String toNodeName(final String str) {
808 final int idx = str.indexOf(':');
813 // Make sure there is only one occurrence
814 if (str.indexOf(':', idx + 1) != -1) {
818 return str.substring(idx + 1);
821 private QName toQName(final String name) {
822 final String module = toModuleName(name);
823 final String node = toNodeName(name);
824 final Module m = globalSchema.findModuleByName(module, null);
825 return m == null ? null : QName.create(m.getQNameModule(), node);
828 private static boolean isListOrContainer(final DataSchemaNode node) {
829 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
832 public RpcDefinition getRpcDefinition(final String name) {
833 final QName validName = this.toQName(name);
834 return validName == null ? null : this.qnameToRpc.get().get(validName);
838 public void onGlobalContextUpdated(final SchemaContext context) {
839 if (context != null) {
840 final Collection<RpcDefinition> defs = context.getOperations();
841 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
843 for (final RpcDefinition operation : defs) {
844 newMap.put(operation.getQName(), operation);
847 // FIXME: still not completely atomic
848 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
849 this.setGlobalSchema(context);
853 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
855 List<String> decodedPathArgs = new ArrayList<String>();
856 for (final String pathArg : strings) {
857 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
858 decodedPathArgs.add(_decode);
860 return decodedPathArgs;
861 } catch (UnsupportedEncodingException e) {
862 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
863 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
867 public String urlPathArgDecode(final String pathArg) {
868 if (pathArg != null) {
870 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
871 } catch (UnsupportedEncodingException e) {
872 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
873 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
880 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
881 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
882 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
883 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
884 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
885 } else if (argument != null && node != null) {
886 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
888 throw new IllegalArgumentException("Unhandled parameter types: "
889 + Arrays.<Object> asList(argument, node).toString());
893 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
894 StringBuilder builder = new StringBuilder();
896 QName nodeType = argument.getNodeType();
897 builder.append(this.toRestconfIdentifier(nodeType));
898 return builder.toString();
901 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
902 final ListSchemaNode node) {
903 QName nodeType = argument.getNodeType();
904 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
905 final Map<QName, Object> keyValues = argument.getKeyValues();
907 StringBuilder builder = new StringBuilder();
909 builder.append(nodeIdentifier);
912 List<QName> keyDefinition = node.getKeyDefinition();
913 boolean hasElements = false;
914 for (final QName key : keyDefinition) {
922 builder.append(this.toUriString(keyValues.get(key)));
923 } catch (UnsupportedEncodingException e) {
924 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
929 return builder.toString();
932 private static DataSchemaNode childByQName(final Object container, final QName name) {
933 if (container instanceof ChoiceCaseNode) {
934 return childByQName((ChoiceCaseNode) container, name);
935 } else if (container instanceof ChoiceNode) {
936 return childByQName((ChoiceNode) container, name);
937 } else if (container instanceof ContainerSchemaNode) {
938 return childByQName((ContainerSchemaNode) container, name);
939 } else if (container instanceof ListSchemaNode) {
940 return childByQName((ListSchemaNode) container, name);
941 } else if (container instanceof DataSchemaNode) {
942 return childByQName((DataSchemaNode) container, name);
943 } else if (container instanceof Module) {
944 return childByQName((Module) container, name);
946 throw new IllegalArgumentException("Unhandled parameter types: "
947 + Arrays.<Object> asList(container, name).toString());