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.FluentIterable;
19 import com.google.common.collect.HashBiMap;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.Iterables;
23 import java.io.UnsupportedEncodingException;
25 import java.net.URLDecoder;
26 import java.net.URLEncoder;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.List;
36 import java.util.concurrent.atomic.AtomicReference;
38 import javax.ws.rs.core.Response.Status;
40 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
41 import org.opendaylight.controller.sal.core.api.mount.MountService;
42 import org.opendaylight.controller.sal.rest.api.Draft02;
43 import org.opendaylight.controller.sal.rest.impl.RestUtil;
44 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
45 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
46 import org.opendaylight.yangtools.concepts.Codec;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder;
50 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class ControllerContext implements SchemaContextListener {
73 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
75 private final static ControllerContext INSTANCE = new ControllerContext();
77 private final static String NULL_VALUE = "null";
79 private final static String MOUNT_MODULE = "yang-ext";
81 private final static String MOUNT_NODE = "mount";
83 public final static String MOUNT = "yang-ext:mount";
85 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
87 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
89 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
91 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
93 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
94 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
96 private volatile SchemaContext globalSchema;
97 private volatile MountService mountService;
99 public void setGlobalSchema(final SchemaContext globalSchema) {
100 this.globalSchema = globalSchema;
103 public void setMountService(final MountService mountService) {
104 this.mountService = mountService;
107 private ControllerContext() {
110 public static ControllerContext getInstance() {
111 return ControllerContext.INSTANCE;
114 private void checkPreconditions() {
115 if (globalSchema == null) {
116 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
120 public void setSchemas(final SchemaContext schemas) {
121 this.onGlobalContextUpdated(schemas);
124 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
125 return this.toIdentifier(restconfInstance, false);
128 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
129 return this.toIdentifier(restconfInstance, true);
132 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
133 this.checkPreconditions();
135 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
136 omitFirstAndLastEmptyString(pathArgs);
137 if (pathArgs.isEmpty()) {
141 String first = pathArgs.iterator().next();
142 final String startModule = ControllerContext.toModuleName(first);
143 if (startModule == null) {
144 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
145 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
148 InstanceIdentifierBuilder builder = InstanceIdentifier.builder();
149 Module latestModule = this.getLatestModule(globalSchema, startModule);
150 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
151 toMountPointIdentifier);
153 if (iiWithSchemaNode == null) {
154 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
157 return iiWithSchemaNode;
160 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
161 if (list.isEmpty()) {
165 String head = list.iterator().next();
166 if (head.isEmpty()) {
170 if (list.isEmpty()) {
174 String last = list.get(list.size() - 1);
175 if (last.isEmpty()) {
176 list.remove(list.size() - 1);
182 private Module getLatestModule(final SchemaContext schema, final String moduleName) {
183 Preconditions.checkArgument(schema != null);
184 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
186 Predicate<Module> filter = new Predicate<Module>() {
188 public boolean apply(final Module m) {
189 return Objects.equal(m.getName(), moduleName);
193 Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
194 return this.filterLatestModule(modules);
197 private Module filterLatestModule(final Iterable<Module> modules) {
198 Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
199 for (final Module module : modules) {
200 if (module.getRevision().after(latestModule.getRevision())) {
201 latestModule = module;
207 public Module findModuleByName(final String moduleName) {
208 this.checkPreconditions();
209 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
210 return this.getLatestModule(globalSchema, moduleName);
213 public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
214 Preconditions.checkArgument(moduleName != null && mountPoint != null);
216 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
217 return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
220 public Module findModuleByNamespace(final URI namespace) {
221 this.checkPreconditions();
222 Preconditions.checkArgument(namespace != null);
224 final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
225 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
228 public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
229 Preconditions.checkArgument(namespace != null && mountPoint != null);
231 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
232 Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
233 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
236 public Module findModuleByNameAndRevision(final QName module) {
237 this.checkPreconditions();
238 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
240 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
243 public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
244 this.checkPreconditions();
245 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
246 && mountPoint != null);
248 SchemaContext schemaContext = mountPoint.getSchemaContext();
249 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
250 module.getRevision());
253 public DataNodeContainer getDataNodeContainerFor(final InstanceIdentifier path) {
254 this.checkPreconditions();
256 final Iterable<PathArgument> elements = path.getPathArguments();
257 PathArgument head = elements.iterator().next();
258 final QName startQName = head.getNodeType();
259 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
260 startQName.getRevision());
261 DataNodeContainer node = initialModule;
262 for (final PathArgument element : elements) {
263 QName _nodeType = element.getNodeType();
264 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
265 if (potentialNode == null || !this.isListOrContainer(potentialNode)) {
268 node = (DataNodeContainer) potentialNode;
274 public String toFullRestconfIdentifier(final InstanceIdentifier path) {
275 this.checkPreconditions();
277 final Iterable<PathArgument> elements = path.getPathArguments();
278 final StringBuilder builder = new StringBuilder();
279 PathArgument head = elements.iterator().next();
280 final QName startQName = head.getNodeType();
281 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
282 startQName.getRevision());
283 DataNodeContainer node = initialModule;
284 for (final PathArgument element : elements) {
285 QName _nodeType = element.getNodeType();
286 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
287 if (!this.isListOrContainer(potentialNode)) {
290 node = ((DataNodeContainer) potentialNode);
291 builder.append(this.convertToRestconfIdentifier(element, node));
294 return builder.toString();
297 public String findModuleNameByNamespace(final URI namespace) {
298 this.checkPreconditions();
300 String moduleName = this.uriToModuleName.get(namespace);
301 if (moduleName == null) {
302 final Module module = this.findModuleByNamespace(namespace);
303 if (module != null) {
304 moduleName = module.getName();
305 this.uriToModuleName.put(namespace, moduleName);
312 public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
313 final Module module = this.findModuleByNamespace(mountPoint, namespace);
314 return module == null ? null : module.getName();
317 public URI findNamespaceByModuleName(final String moduleName) {
318 URI namespace = this.moduleNameToUri.get(moduleName);
319 if (namespace == null) {
320 Module module = this.findModuleByName(moduleName);
321 if (module != null) {
322 URI _namespace = module.getNamespace();
323 namespace = _namespace;
324 this.uriToModuleName.put(namespace, moduleName);
330 public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
331 final Module module = this.findModuleByName(mountPoint, moduleName);
332 return module == null ? null : module.getNamespace();
335 public Set<Module> getAllModules(final MountInstance mountPoint) {
336 this.checkPreconditions();
338 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
339 return schemaContext == null ? null : schemaContext.getModules();
342 public Set<Module> getAllModules() {
343 this.checkPreconditions();
344 return globalSchema.getModules();
347 public CharSequence toRestconfIdentifier(final QName qname) {
348 this.checkPreconditions();
350 String module = this.uriToModuleName.get(qname.getNamespace());
351 if (module == null) {
352 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
353 qname.getRevision());
354 if (moduleSchema == null) {
358 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
359 module = moduleSchema.getName();
362 StringBuilder builder = new StringBuilder();
363 builder.append(module);
365 builder.append(qname.getLocalName());
366 return builder.toString();
369 public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
370 if (mountPoint == null) {
374 SchemaContext schemaContext = mountPoint.getSchemaContext();
376 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
377 qname.getRevision());
378 if (moduleSchema == null) {
382 StringBuilder builder = new StringBuilder();
383 builder.append(moduleSchema.getName());
385 builder.append(qname.getLocalName());
386 return builder.toString();
389 public Module getRestconfModule() {
390 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
393 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
394 Module restconfModule = getRestconfModule();
395 if (restconfModule == null) {
399 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
401 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
403 public boolean apply(final GroupingDefinition g) {
404 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
408 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
410 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
412 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
413 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
414 return Iterables.getFirst(instanceDataChildrenByName, null);
417 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
418 Module restconfModule = inRestconfModule;
419 if (restconfModule == null) {
420 restconfModule = getRestconfModule();
423 if (restconfModule == null) {
427 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
429 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
431 public boolean apply(final GroupingDefinition g) {
432 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
436 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
438 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
440 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
441 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
442 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
444 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
445 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
446 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
448 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
449 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
450 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
451 return Iterables.getFirst(instances, null);
452 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
453 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
454 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
455 final DataSchemaNode modules = Iterables.getFirst(instances, null);
456 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
457 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
458 return Iterables.getFirst(instances, null);
459 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
460 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
461 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
462 return Iterables.getFirst(instances, null);
463 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
464 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
465 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
466 final DataSchemaNode modules = Iterables.getFirst(instances, null);
467 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
468 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
469 return Iterables.getFirst(instances, null);
470 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
471 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
472 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
473 return Iterables.getFirst(instances, null);
479 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
480 for (final ChoiceCaseNode caze : container.getCases()) {
481 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
490 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
491 return container.getDataChildByName(name);
494 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
495 return ControllerContext.dataNodeChildByQName(container, name);
498 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
499 return ControllerContext.dataNodeChildByQName(container, name);
502 private static DataSchemaNode childByQName(final Module container, final QName name) {
503 return ControllerContext.dataNodeChildByQName(container, name);
506 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
510 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
511 DataSchemaNode ret = container.getDataChildByName(name);
513 for (final DataSchemaNode node : container.getChildNodes()) {
514 if ((node instanceof ChoiceCaseNode)) {
515 final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node);
516 DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
517 if (childByQName != null) {
526 private String toUriString(final Object object) throws UnsupportedEncodingException {
527 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
530 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
531 final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
532 final boolean returnJustMountPoint) {
533 Preconditions.<List<String>> checkNotNull(strings);
535 if (parentNode == null) {
539 if (strings.isEmpty()) {
540 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
543 String head = strings.iterator().next();
544 final String nodeName = toNodeName(head);
545 final String moduleName = ControllerContext.toModuleName(head);
547 DataSchemaNode targetNode = null;
548 if (!Strings.isNullOrEmpty(moduleName)) {
549 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
550 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
551 if (mountPoint != null) {
552 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
553 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
556 if (mountService == null) {
557 throw new RestconfDocumentedException(
558 "MountService was not found. Finding behind mount points does not work.",
559 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
562 final InstanceIdentifier partialPath = builder.toInstance();
563 final MountInstance mount = mountService.getMountPoint(partialPath);
565 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
566 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
567 ErrorTag.UNKNOWN_ELEMENT);
570 final SchemaContext mountPointSchema = mount.getSchemaContext();
571 if (mountPointSchema == null) {
572 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
573 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
576 if (returnJustMountPoint) {
577 InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
578 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
581 if (strings.size() == 1) {
582 InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
583 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
586 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
587 if (moduleNameBehindMountPoint == null) {
588 throw new RestconfDocumentedException(
589 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
590 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
593 final Module moduleBehindMountPoint = this
594 .getLatestModule(mountPointSchema, moduleNameBehindMountPoint);
595 if (moduleBehindMountPoint == null) {
596 throw new RestconfDocumentedException("\"" + moduleName
597 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
600 List<String> subList = strings.subList(1, strings.size());
601 return this.collectPathArguments(InstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
602 returnJustMountPoint);
605 Module module = null;
606 if (mountPoint == null) {
607 module = this.getLatestModule(globalSchema, moduleName);
608 if (module == null) {
609 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
610 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
613 SchemaContext schemaContext = mountPoint.getSchemaContext();
614 module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName);
615 if (module == null) {
616 throw new RestconfDocumentedException("\"" + moduleName
617 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
621 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
622 if (targetNode == null) {
623 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
624 + "\" was not found in parent data node.\n" + " 2. \"" + head
625 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
626 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
629 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
630 if (potentialSchemaNodes.size() > 1) {
631 final StringBuilder strBuilder = new StringBuilder();
632 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
633 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
636 throw new RestconfDocumentedException(
637 "URI has bad format. Node \""
639 + "\" is added as augment from more than one module. "
640 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
641 + "\nThe node is added as augment from modules with namespaces:\n"
642 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
645 if (potentialSchemaNodes.isEmpty()) {
646 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
647 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
650 targetNode = potentialSchemaNodes.iterator().next();
653 if (!this.isListOrContainer(targetNode)) {
654 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
655 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
659 if ((targetNode instanceof ListSchemaNode)) {
660 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
661 final int keysSize = listNode.getKeyDefinition().size();
662 if ((strings.size() - consumed) < keysSize) {
663 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
664 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
667 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
668 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
670 for (final QName key : listNode.getKeyDefinition()) {
672 final String uriKeyValue = uriKeyValues.get(i);
673 if (uriKeyValue.equals(NULL_VALUE)) {
674 throw new RestconfDocumentedException("URI has bad format. List \""
675 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
676 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
679 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
684 consumed = consumed + i;
685 builder.nodeWithKey(targetNode.getQName(), keyValues);
687 builder.node(targetNode.getQName());
690 if ((targetNode instanceof DataNodeContainer)) {
691 final List<String> remaining = strings.subList(consumed, strings.size());
692 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
693 returnJustMountPoint);
696 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
699 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
700 final URI namespace) {
701 Preconditions.<URI> checkNotNull(namespace);
703 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
705 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
707 public boolean apply(final DataSchemaNode node) {
708 return Objects.equal(node.getQName().getNamespace(), namespace);
712 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
713 return Iterables.getFirst(result, null);
716 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
717 Preconditions.<DataNodeContainer> checkNotNull(container);
718 Preconditions.<String> checkNotNull(name);
720 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
721 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
722 return instantiatedDataNodeContainers;
725 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
726 final DataNodeContainer container, final String name) {
728 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
730 public boolean apply(final DataSchemaNode node) {
731 return Objects.equal(node.getQName().getLocalName(), name);
735 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
737 // Can't combine this loop with the filter above because the filter is
738 // lazily-applied by Iterables.filter.
739 for (final DataSchemaNode potentialNode : nodes) {
740 if (this.isInstantiatedDataSchema(potentialNode)) {
741 potentialSchemaNodes.add(potentialNode);
745 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
747 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
749 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
750 return node.getCases();
754 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
757 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
758 for (final ChoiceCaseNode caze : allCases) {
759 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
763 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
764 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
765 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
766 || node instanceof AnyXmlSchemaNode;
769 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
770 final MountInstance mountPoint) {
771 Preconditions.<String> checkNotNull(uriValue);
772 Preconditions.checkArgument((node instanceof LeafSchemaNode));
774 final String urlDecoded = urlPathArgDecode(uriValue);
775 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
776 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
778 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
779 String additionalInfo = "";
780 if (decoded == null) {
781 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
782 if ((baseType instanceof IdentityrefTypeDefinition)) {
783 decoded = this.toQName(urlDecoded);
784 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
788 if (decoded == null) {
789 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
790 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
793 map.put(node.getQName(), decoded);
796 private static String toModuleName(final String str) {
797 final int idx = str.indexOf(':');
802 // Make sure there is only one occurrence
803 if (str.indexOf(':', idx + 1) != -1) {
807 return str.substring(0, idx);
810 private static String toNodeName(final String str) {
811 final int idx = str.indexOf(':');
816 // Make sure there is only one occurrence
817 if (str.indexOf(':', idx + 1) != -1) {
821 return str.substring(idx + 1);
824 private QName toQName(final String name) {
825 final String module = toModuleName(name);
826 final String node = toNodeName(name);
827 Set<Module> modules = globalSchema.getModules();
829 final Comparator<Module> comparator = new Comparator<Module>() {
831 public int compare(final Module o1, final Module o2) {
832 return o1.getRevision().compareTo(o2.getRevision());
836 List<Module> sorted = new ArrayList<Module>(modules);
837 Collections.<Module> sort(new ArrayList<Module>(modules), comparator);
839 final Function<Module, QName> transform = new Function<Module, QName>() {
841 public QName apply(final Module m) {
842 return QName.create(m.getNamespace(), m.getRevision(), m.getName());
846 final Predicate<QName> findFirst = new Predicate<QName>() {
848 public boolean apply(final QName qn) {
849 return Objects.equal(module, qn.getLocalName());
853 Optional<QName> namespace = FluentIterable.from(sorted).transform(transform).firstMatch(findFirst);
854 return namespace.isPresent() ? QName.create(namespace.get(), node) : null;
857 private static boolean isListOrContainer(final DataSchemaNode node) {
858 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
861 public RpcDefinition getRpcDefinition(final String name) {
862 final QName validName = this.toQName(name);
863 return validName == null ? null : this.qnameToRpc.get().get(validName);
867 public void onGlobalContextUpdated(final SchemaContext context) {
868 if (context != null) {
869 final Collection<RpcDefinition> defs = context.getOperations();
870 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
872 for (final RpcDefinition operation : defs) {
873 newMap.put(operation.getQName(), operation);
876 // FIXME: still not completely atomic
877 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
878 this.setGlobalSchema(context);
882 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
884 List<String> decodedPathArgs = new ArrayList<String>();
885 for (final String pathArg : strings) {
886 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
887 decodedPathArgs.add(_decode);
889 return decodedPathArgs;
890 } catch (UnsupportedEncodingException e) {
891 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
892 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
896 public String urlPathArgDecode(final String pathArg) {
897 if (pathArg != null) {
899 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
900 } catch (UnsupportedEncodingException e) {
901 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
902 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
909 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
910 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
911 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
912 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
913 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
914 } else if (argument != null && node != null) {
915 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
917 throw new IllegalArgumentException("Unhandled parameter types: "
918 + Arrays.<Object> asList(argument, node).toString());
922 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
923 StringBuilder builder = new StringBuilder();
925 QName nodeType = argument.getNodeType();
926 builder.append(this.toRestconfIdentifier(nodeType));
927 return builder.toString();
930 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
931 final ListSchemaNode node) {
932 QName nodeType = argument.getNodeType();
933 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
934 final Map<QName, Object> keyValues = argument.getKeyValues();
936 StringBuilder builder = new StringBuilder();
938 builder.append(nodeIdentifier);
941 List<QName> keyDefinition = node.getKeyDefinition();
942 boolean hasElements = false;
943 for (final QName key : keyDefinition) {
951 builder.append(this.toUriString(keyValues.get(key)));
952 } catch (UnsupportedEncodingException e) {
953 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
958 return builder.toString();
961 private static DataSchemaNode childByQName(final Object container, final QName name) {
962 if (container instanceof ChoiceCaseNode) {
963 return childByQName((ChoiceCaseNode) container, name);
964 } else if (container instanceof ChoiceNode) {
965 return childByQName((ChoiceNode) container, name);
966 } else if (container instanceof ContainerSchemaNode) {
967 return childByQName((ContainerSchemaNode) container, name);
968 } else if (container instanceof ListSchemaNode) {
969 return childByQName((ListSchemaNode) container, name);
970 } else if (container instanceof DataSchemaNode) {
971 return childByQName((DataSchemaNode) container, name);
972 } else if (container instanceof Module) {
973 return childByQName((Module) container, name);
975 throw new IllegalArgumentException("Unhandled parameter types: "
976 + Arrays.<Object> asList(container, name).toString());