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 = this.getLatestModule(globalSchema, startModule);
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);
177 private Module getLatestModule(final SchemaContext schema, final String moduleName) {
178 Preconditions.checkArgument(schema != null);
179 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
181 Predicate<Module> filter = new Predicate<Module>() {
183 public boolean apply(final Module m) {
184 return Objects.equal(m.getName(), moduleName);
188 Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
189 return this.filterLatestModule(modules);
192 private Module filterLatestModule(final Iterable<Module> modules) {
193 Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
194 for (final Module module : modules) {
195 if (module.getRevision().after(latestModule.getRevision())) {
196 latestModule = module;
202 public Module findModuleByName(final String moduleName) {
203 this.checkPreconditions();
204 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
205 return this.getLatestModule(globalSchema, moduleName);
208 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
209 Preconditions.checkArgument(moduleName != null && mountPoint != null);
211 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
212 return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
215 public Module findModuleByNamespace(final URI namespace) {
216 this.checkPreconditions();
217 Preconditions.checkArgument(namespace != null);
219 final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
220 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
223 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
224 Preconditions.checkArgument(namespace != null && mountPoint != null);
226 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
227 Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
228 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
231 public Module findModuleByNameAndRevision(final QName module) {
232 this.checkPreconditions();
233 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
235 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
238 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
239 this.checkPreconditions();
240 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
241 && mountPoint != null);
243 SchemaContext schemaContext = mountPoint.getSchemaContext();
244 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
245 module.getRevision());
248 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
249 this.checkPreconditions();
251 final Iterable<PathArgument> elements = path.getPathArguments();
252 PathArgument head = elements.iterator().next();
253 final QName startQName = head.getNodeType();
254 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
255 startQName.getRevision());
256 DataNodeContainer node = initialModule;
257 for (final PathArgument element : elements) {
258 QName _nodeType = element.getNodeType();
259 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
260 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
263 node = (DataNodeContainer) potentialNode;
269 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
270 this.checkPreconditions();
272 final Iterable<PathArgument> elements = path.getPathArguments();
273 final StringBuilder builder = new StringBuilder();
274 PathArgument head = elements.iterator().next();
275 final QName startQName = head.getNodeType();
276 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
277 startQName.getRevision());
278 DataNodeContainer node = initialModule;
279 for (final PathArgument element : elements) {
280 QName _nodeType = element.getNodeType();
281 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
282 if (!ControllerContext.isListOrContainer(potentialNode)) {
285 node = ((DataNodeContainer) potentialNode);
286 builder.append(this.convertToRestconfIdentifier(element, node));
289 return builder.toString();
292 public String findModuleNameByNamespace(final URI namespace) {
293 this.checkPreconditions();
295 String moduleName = this.uriToModuleName.get(namespace);
296 if (moduleName == null) {
297 final Module module = this.findModuleByNamespace(namespace);
298 if (module != null) {
299 moduleName = module.getName();
300 this.uriToModuleName.put(namespace, moduleName);
307 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
308 final Module module = this.findModuleByNamespace(mountPoint, namespace);
309 return module == null ? null : module.getName();
312 public URI findNamespaceByModuleName(final String moduleName) {
313 URI namespace = this.moduleNameToUri.get(moduleName);
314 if (namespace == null) {
315 Module module = this.findModuleByName(moduleName);
316 if (module != null) {
317 URI _namespace = module.getNamespace();
318 namespace = _namespace;
319 this.uriToModuleName.put(namespace, moduleName);
325 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
326 final Module module = this.findModuleByName(mountPoint, moduleName);
327 return module == null ? null : module.getNamespace();
330 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
331 this.checkPreconditions();
333 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
334 return schemaContext == null ? null : schemaContext.getModules();
337 public Set<Module> getAllModules() {
338 this.checkPreconditions();
339 return globalSchema.getModules();
342 public CharSequence toRestconfIdentifier(final QName qname) {
343 this.checkPreconditions();
345 String module = this.uriToModuleName.get(qname.getNamespace());
346 if (module == null) {
347 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
348 qname.getRevision());
349 if (moduleSchema == null) {
353 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
354 module = moduleSchema.getName();
357 StringBuilder builder = new StringBuilder();
358 builder.append(module);
360 builder.append(qname.getLocalName());
361 return builder.toString();
364 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
365 if (mountPoint == null) {
369 SchemaContext schemaContext = mountPoint.getSchemaContext();
371 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
372 qname.getRevision());
373 if (moduleSchema == null) {
377 StringBuilder builder = new StringBuilder();
378 builder.append(moduleSchema.getName());
380 builder.append(qname.getLocalName());
381 return builder.toString();
384 public Module getRestconfModule() {
385 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
388 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
389 Module restconfModule = getRestconfModule();
390 if (restconfModule == null) {
394 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
396 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
398 public boolean apply(final GroupingDefinition g) {
399 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
403 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
405 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
407 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
408 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
409 return Iterables.getFirst(instanceDataChildrenByName, null);
412 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
413 Module restconfModule = inRestconfModule;
414 if (restconfModule == null) {
415 restconfModule = getRestconfModule();
418 if (restconfModule == null) {
422 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
424 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
426 public boolean apply(final GroupingDefinition g) {
427 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
431 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
433 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
435 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
436 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
437 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
439 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
440 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
441 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
442 return Iterables.getFirst(instances, null);
443 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
444 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
445 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
446 return Iterables.getFirst(instances, null);
447 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
448 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
449 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
450 final DataSchemaNode modules = Iterables.getFirst(instances, null);
451 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
452 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
453 return Iterables.getFirst(instances, null);
454 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
455 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
456 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
457 return Iterables.getFirst(instances, null);
458 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
459 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
460 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
461 final DataSchemaNode modules = Iterables.getFirst(instances, null);
462 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
463 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
464 return Iterables.getFirst(instances, null);
465 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
466 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
467 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
468 return Iterables.getFirst(instances, null);
474 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
475 for (final ChoiceCaseNode caze : container.getCases()) {
476 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
485 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
486 return container.getDataChildByName(name);
489 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
490 return ControllerContext.dataNodeChildByQName(container, name);
493 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
494 return ControllerContext.dataNodeChildByQName(container, name);
497 private static DataSchemaNode childByQName(final Module container, final QName name) {
498 return ControllerContext.dataNodeChildByQName(container, name);
501 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
505 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
506 DataSchemaNode ret = container.getDataChildByName(name);
508 for (final DataSchemaNode node : container.getChildNodes()) {
509 if ((node instanceof ChoiceNode)) {
510 final ChoiceNode choiceNode = ((ChoiceNode) node);
511 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
512 if (childByQName != null) {
521 private String toUriString(final Object object) throws UnsupportedEncodingException {
522 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
525 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
526 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
527 final boolean returnJustMountPoint) {
528 Preconditions.<List<String>> checkNotNull(strings);
530 if (parentNode == null) {
534 if (strings.isEmpty()) {
535 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
538 String head = strings.iterator().next();
539 final String nodeName = toNodeName(head);
540 final String moduleName = ControllerContext.toModuleName(head);
542 DataSchemaNode targetNode = null;
543 if (!Strings.isNullOrEmpty(moduleName)) {
544 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
545 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
546 if (mountPoint != null) {
547 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
548 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
551 if (mountService == null) {
552 throw new RestconfDocumentedException(
553 "MountService was not found. Finding behind mount points does not work.",
554 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
557 final YangInstanceIdentifier partialPath = builder.toInstance();
558 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
559 if (!mountOpt.isPresent()) {
560 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
561 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
562 ErrorTag.UNKNOWN_ELEMENT);
564 DOMMountPoint mount = mountOpt.get();
566 final SchemaContext mountPointSchema = mount.getSchemaContext();
567 if (mountPointSchema == null) {
568 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
569 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
572 if (returnJustMountPoint) {
573 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
574 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
577 if (strings.size() == 1) {
578 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
579 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
582 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
583 if (moduleNameBehindMountPoint == null) {
584 throw new RestconfDocumentedException(
585 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
586 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
589 final Module moduleBehindMountPoint = this
590 .getLatestModule(mountPointSchema, moduleNameBehindMountPoint);
591 if (moduleBehindMountPoint == null) {
592 throw new RestconfDocumentedException("\"" + moduleName
593 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
596 List<String> subList = strings.subList(1, strings.size());
597 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
598 returnJustMountPoint);
601 Module module = null;
602 if (mountPoint == null) {
603 module = this.getLatestModule(globalSchema, moduleName);
604 if (module == null) {
605 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
606 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
609 SchemaContext schemaContext = mountPoint.getSchemaContext();
610 module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName);
611 if (module == null) {
612 throw new RestconfDocumentedException("\"" + moduleName
613 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
617 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
618 if (targetNode == null) {
619 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
620 + "\" was not found in parent data node.\n" + " 2. \"" + head
621 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
622 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
625 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
626 if (potentialSchemaNodes.size() > 1) {
627 final StringBuilder strBuilder = new StringBuilder();
628 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
629 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
632 throw new RestconfDocumentedException(
633 "URI has bad format. Node \""
635 + "\" is added as augment from more than one module. "
636 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
637 + "\nThe node is added as augment from modules with namespaces:\n"
638 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
641 if (potentialSchemaNodes.isEmpty()) {
642 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
643 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
646 targetNode = potentialSchemaNodes.iterator().next();
649 if (!ControllerContext.isListOrContainer(targetNode)) {
650 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
651 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
655 if ((targetNode instanceof ListSchemaNode)) {
656 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
657 final int keysSize = listNode.getKeyDefinition().size();
658 if ((strings.size() - consumed) < keysSize) {
659 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
660 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
663 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
664 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
666 for (final QName key : listNode.getKeyDefinition()) {
668 final String uriKeyValue = uriKeyValues.get(i);
669 if (uriKeyValue.equals(NULL_VALUE)) {
670 throw new RestconfDocumentedException("URI has bad format. List \""
671 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
672 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
675 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
680 consumed = consumed + i;
681 builder.nodeWithKey(targetNode.getQName(), keyValues);
683 builder.node(targetNode.getQName());
686 if ((targetNode instanceof DataNodeContainer)) {
687 final List<String> remaining = strings.subList(consumed, strings.size());
688 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
689 returnJustMountPoint);
692 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
695 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
696 final URI namespace) {
697 Preconditions.<URI> checkNotNull(namespace);
699 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
701 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
703 public boolean apply(final DataSchemaNode node) {
704 return Objects.equal(node.getQName().getNamespace(), namespace);
708 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
709 return Iterables.getFirst(result, null);
712 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
713 Preconditions.<DataNodeContainer> checkNotNull(container);
714 Preconditions.<String> checkNotNull(name);
716 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
717 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
718 return instantiatedDataNodeContainers;
721 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
722 final DataNodeContainer container, final String name) {
724 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
726 public boolean apply(final DataSchemaNode node) {
727 return Objects.equal(node.getQName().getLocalName(), name);
731 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
733 // Can't combine this loop with the filter above because the filter is
734 // lazily-applied by Iterables.filter.
735 for (final DataSchemaNode potentialNode : nodes) {
736 if (this.isInstantiatedDataSchema(potentialNode)) {
737 potentialSchemaNodes.add(potentialNode);
741 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
743 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
745 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
746 return node.getCases();
750 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
753 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
754 for (final ChoiceCaseNode caze : allCases) {
755 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
759 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
760 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
761 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
762 || node instanceof AnyXmlSchemaNode;
765 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
766 final DOMMountPoint mountPoint) {
767 Preconditions.<String> checkNotNull(uriValue);
768 Preconditions.checkArgument((node instanceof LeafSchemaNode));
770 final String urlDecoded = urlPathArgDecode(uriValue);
771 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
772 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
774 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
775 String additionalInfo = "";
776 if (decoded == null) {
777 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
778 if ((baseType instanceof IdentityrefTypeDefinition)) {
779 decoded = this.toQName(urlDecoded);
780 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
784 if (decoded == null) {
785 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
786 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
789 map.put(node.getQName(), decoded);
792 private static String toModuleName(final String str) {
793 final int idx = str.indexOf(':');
798 // Make sure there is only one occurrence
799 if (str.indexOf(':', idx + 1) != -1) {
803 return str.substring(0, idx);
806 private static String toNodeName(final String str) {
807 final int idx = str.indexOf(':');
812 // Make sure there is only one occurrence
813 if (str.indexOf(':', idx + 1) != -1) {
817 return str.substring(idx + 1);
820 private QName toQName(final String name) {
821 final String module = toModuleName(name);
822 final String node = toNodeName(name);
823 final Module m = globalSchema.findModuleByName(module, null);
824 return m == null ? null : QName.create(m.getQNameModule(), node);
827 private static boolean isListOrContainer(final DataSchemaNode node) {
828 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
831 public RpcDefinition getRpcDefinition(final String name) {
832 final QName validName = this.toQName(name);
833 return validName == null ? null : this.qnameToRpc.get().get(validName);
837 public void onGlobalContextUpdated(final SchemaContext context) {
838 if (context != null) {
839 final Collection<RpcDefinition> defs = context.getOperations();
840 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
842 for (final RpcDefinition operation : defs) {
843 newMap.put(operation.getQName(), operation);
846 // FIXME: still not completely atomic
847 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
848 this.setGlobalSchema(context);
852 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
854 List<String> decodedPathArgs = new ArrayList<String>();
855 for (final String pathArg : strings) {
856 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
857 decodedPathArgs.add(_decode);
859 return decodedPathArgs;
860 } catch (UnsupportedEncodingException e) {
861 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
862 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
866 public String urlPathArgDecode(final String pathArg) {
867 if (pathArg != null) {
869 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
870 } catch (UnsupportedEncodingException e) {
871 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
872 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
879 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
880 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
881 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
882 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
883 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
884 } else if (argument != null && node != null) {
885 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
887 throw new IllegalArgumentException("Unhandled parameter types: "
888 + Arrays.<Object> asList(argument, node).toString());
892 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
893 StringBuilder builder = new StringBuilder();
895 QName nodeType = argument.getNodeType();
896 builder.append(this.toRestconfIdentifier(nodeType));
897 return builder.toString();
900 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
901 final ListSchemaNode node) {
902 QName nodeType = argument.getNodeType();
903 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
904 final Map<QName, Object> keyValues = argument.getKeyValues();
906 StringBuilder builder = new StringBuilder();
908 builder.append(nodeIdentifier);
911 List<QName> keyDefinition = node.getKeyDefinition();
912 boolean hasElements = false;
913 for (final QName key : keyDefinition) {
921 builder.append(this.toUriString(keyValues.get(key)));
922 } catch (UnsupportedEncodingException e) {
923 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
928 return builder.toString();
931 private static DataSchemaNode childByQName(final Object container, final QName name) {
932 if (container instanceof ChoiceCaseNode) {
933 return childByQName((ChoiceCaseNode) container, name);
934 } else if (container instanceof ChoiceNode) {
935 return childByQName((ChoiceNode) container, name);
936 } else if (container instanceof ContainerSchemaNode) {
937 return childByQName((ContainerSchemaNode) container, name);
938 } else if (container instanceof ListSchemaNode) {
939 return childByQName((ListSchemaNode) container, name);
940 } else if (container instanceof DataSchemaNode) {
941 return childByQName((DataSchemaNode) container, name);
942 } else if (container instanceof Module) {
943 return childByQName((Module) container, name);
945 throw new IllegalArgumentException("Unhandled parameter types: "
946 + Arrays.<Object> asList(container, name).toString());