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 static final Splitter COLON_SPLITTER = Splitter.on(':');
91 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
93 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
95 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
96 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
98 private volatile SchemaContext globalSchema;
99 private volatile MountService mountService;
101 public void setGlobalSchema(final SchemaContext globalSchema) {
102 this.globalSchema = globalSchema;
105 public void setMountService(final MountService mountService) {
106 this.mountService = mountService;
109 private ControllerContext() {
112 public static ControllerContext getInstance() {
113 return ControllerContext.INSTANCE;
116 private void checkPreconditions() {
117 if (globalSchema == null) {
118 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
122 public void setSchemas(final SchemaContext schemas) {
123 this.onGlobalContextUpdated(schemas);
126 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
127 return this.toIdentifier(restconfInstance, false);
130 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
131 return this.toIdentifier(restconfInstance, true);
134 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
135 this.checkPreconditions();
137 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
138 omitFirstAndLastEmptyString(pathArgs);
139 if (pathArgs.isEmpty()) {
143 String first = pathArgs.iterator().next();
144 final String startModule = ControllerContext.toModuleName(first);
145 if (startModule == null) {
146 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
147 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
150 InstanceIdentifierBuilder builder = InstanceIdentifier.builder();
151 Module latestModule = this.getLatestModule(globalSchema, startModule);
152 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
153 toMountPointIdentifier);
155 if (iiWithSchemaNode == null) {
156 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
159 return iiWithSchemaNode;
162 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
163 if (list.isEmpty()) {
167 String head = list.iterator().next();
168 if (head.isEmpty()) {
172 if (list.isEmpty()) {
176 String last = list.get(list.size() - 1);
177 if (last.isEmpty()) {
178 list.remove(list.size() - 1);
184 private Module getLatestModule(final SchemaContext schema, final String moduleName) {
185 Preconditions.checkArgument(schema != null);
186 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
188 Predicate<Module> filter = new Predicate<Module>() {
190 public boolean apply(final Module m) {
191 return Objects.equal(m.getName(), moduleName);
195 Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
196 return this.filterLatestModule(modules);
199 private Module filterLatestModule(final Iterable<Module> modules) {
200 Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
201 for (final Module module : modules) {
202 if (module.getRevision().after(latestModule.getRevision())) {
203 latestModule = module;
209 public Module findModuleByName(final String moduleName) {
210 this.checkPreconditions();
211 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
212 return this.getLatestModule(globalSchema, moduleName);
215 public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
216 Preconditions.checkArgument(moduleName != null && mountPoint != null);
218 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
219 return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
222 public Module findModuleByNamespace(final URI namespace) {
223 this.checkPreconditions();
224 Preconditions.checkArgument(namespace != null);
226 final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
227 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
230 public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
231 Preconditions.checkArgument(namespace != null && mountPoint != null);
233 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
234 Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
235 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
238 public Module findModuleByNameAndRevision(final QName module) {
239 this.checkPreconditions();
240 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
242 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
245 public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
246 this.checkPreconditions();
247 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
248 && mountPoint != null);
250 SchemaContext schemaContext = mountPoint.getSchemaContext();
251 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
252 module.getRevision());
255 public DataNodeContainer getDataNodeContainerFor(final InstanceIdentifier path) {
256 this.checkPreconditions();
258 final Iterable<PathArgument> elements = path.getPathArguments();
259 PathArgument head = elements.iterator().next();
260 final QName startQName = head.getNodeType();
261 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
262 startQName.getRevision());
263 DataNodeContainer node = initialModule;
264 for (final PathArgument element : elements) {
265 QName _nodeType = element.getNodeType();
266 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
267 if (potentialNode == null || !this.isListOrContainer(potentialNode)) {
270 node = (DataNodeContainer) potentialNode;
276 public String toFullRestconfIdentifier(final InstanceIdentifier path) {
277 this.checkPreconditions();
279 final Iterable<PathArgument> elements = path.getPathArguments();
280 final StringBuilder builder = new StringBuilder();
281 PathArgument head = elements.iterator().next();
282 final QName startQName = head.getNodeType();
283 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
284 startQName.getRevision());
285 DataNodeContainer node = initialModule;
286 for (final PathArgument element : elements) {
287 QName _nodeType = element.getNodeType();
288 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
289 if (!this.isListOrContainer(potentialNode)) {
292 node = ((DataNodeContainer) potentialNode);
293 builder.append(this.convertToRestconfIdentifier(element, node));
296 return builder.toString();
299 public String findModuleNameByNamespace(final URI namespace) {
300 this.checkPreconditions();
302 String moduleName = this.uriToModuleName.get(namespace);
303 if (moduleName == null) {
304 final Module module = this.findModuleByNamespace(namespace);
305 if (module != null) {
306 moduleName = module.getName();
307 this.uriToModuleName.put(namespace, moduleName);
314 public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
315 final Module module = this.findModuleByNamespace(mountPoint, namespace);
316 return module == null ? null : module.getName();
319 public URI findNamespaceByModuleName(final String moduleName) {
320 URI namespace = this.moduleNameToUri.get(moduleName);
321 if (namespace == null) {
322 Module module = this.findModuleByName(moduleName);
323 if (module != null) {
324 URI _namespace = module.getNamespace();
325 namespace = _namespace;
326 this.uriToModuleName.put(namespace, moduleName);
332 public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
333 final Module module = this.findModuleByName(mountPoint, moduleName);
334 return module == null ? null : module.getNamespace();
337 public Set<Module> getAllModules(final MountInstance mountPoint) {
338 this.checkPreconditions();
340 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
341 return schemaContext == null ? null : schemaContext.getModules();
344 public Set<Module> getAllModules() {
345 this.checkPreconditions();
346 return globalSchema.getModules();
349 public CharSequence toRestconfIdentifier(final QName qname) {
350 this.checkPreconditions();
352 String module = this.uriToModuleName.get(qname.getNamespace());
353 if (module == null) {
354 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
355 qname.getRevision());
356 if (moduleSchema == null) {
360 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
361 module = moduleSchema.getName();
364 StringBuilder builder = new StringBuilder();
365 builder.append(module);
367 builder.append(qname.getLocalName());
368 return builder.toString();
371 public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
372 if (mountPoint == null) {
376 SchemaContext schemaContext = mountPoint.getSchemaContext();
378 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
379 qname.getRevision());
380 if (moduleSchema == null) {
384 StringBuilder builder = new StringBuilder();
385 builder.append(moduleSchema.getName());
387 builder.append(qname.getLocalName());
388 return builder.toString();
391 public Module getRestconfModule() {
392 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
395 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
396 Module restconfModule = getRestconfModule();
397 if (restconfModule == null) {
401 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
403 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
405 public boolean apply(final GroupingDefinition g) {
406 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
410 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
412 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
414 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
415 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
416 return Iterables.getFirst(instanceDataChildrenByName, null);
419 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
420 Module restconfModule = inRestconfModule;
421 if (restconfModule == null) {
422 restconfModule = getRestconfModule();
425 if (restconfModule == null) {
429 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
431 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
433 public boolean apply(final GroupingDefinition g) {
434 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
438 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
440 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
442 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
443 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
444 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
446 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
447 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
448 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
449 return Iterables.getFirst(instances, null);
450 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
451 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
452 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
453 return Iterables.getFirst(instances, null);
454 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
455 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
456 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
457 final DataSchemaNode modules = Iterables.getFirst(instances, null);
458 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
459 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
460 return Iterables.getFirst(instances, null);
461 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
462 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
463 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
464 return Iterables.getFirst(instances, null);
465 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
466 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
467 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
468 final DataSchemaNode modules = Iterables.getFirst(instances, null);
469 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
470 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
471 return Iterables.getFirst(instances, null);
472 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
473 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
474 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
475 return Iterables.getFirst(instances, null);
481 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
482 for (final ChoiceCaseNode caze : container.getCases()) {
483 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
492 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
493 return container.getDataChildByName(name);
496 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
497 return ControllerContext.dataNodeChildByQName(container, name);
500 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
501 return ControllerContext.dataNodeChildByQName(container, name);
504 private static DataSchemaNode childByQName(final Module container, final QName name) {
505 return ControllerContext.dataNodeChildByQName(container, name);
508 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
512 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
513 DataSchemaNode ret = container.getDataChildByName(name);
515 for (final DataSchemaNode node : container.getChildNodes()) {
516 if ((node instanceof ChoiceCaseNode)) {
517 final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node);
518 DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
519 if (childByQName != null) {
528 private String toUriString(final Object object) throws UnsupportedEncodingException {
529 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
532 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
533 final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
534 final boolean returnJustMountPoint) {
535 Preconditions.<List<String>> checkNotNull(strings);
537 if (parentNode == null) {
541 if (strings.isEmpty()) {
542 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
545 String head = strings.iterator().next();
546 final String nodeName = toNodeName(head);
547 final String moduleName = ControllerContext.toModuleName(head);
549 DataSchemaNode targetNode = null;
550 if (!Strings.isNullOrEmpty(moduleName)) {
551 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
552 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
553 if (mountPoint != null) {
554 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
555 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
558 if (mountService == null) {
559 throw new RestconfDocumentedException(
560 "MountService was not found. Finding behind mount points does not work.",
561 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
564 final InstanceIdentifier partialPath = builder.toInstance();
565 final MountInstance mount = mountService.getMountPoint(partialPath);
567 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
568 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
569 ErrorTag.UNKNOWN_ELEMENT);
572 final SchemaContext mountPointSchema = mount.getSchemaContext();
573 if (mountPointSchema == null) {
574 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
575 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
578 if (returnJustMountPoint) {
579 InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
580 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
583 if (strings.size() == 1) {
584 InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
585 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
588 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
589 if (moduleNameBehindMountPoint == null) {
590 throw new RestconfDocumentedException(
591 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
592 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
595 final Module moduleBehindMountPoint = this
596 .getLatestModule(mountPointSchema, moduleNameBehindMountPoint);
597 if (moduleBehindMountPoint == null) {
598 throw new RestconfDocumentedException("\"" + moduleName
599 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
602 List<String> subList = strings.subList(1, strings.size());
603 return this.collectPathArguments(InstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
604 returnJustMountPoint);
607 Module module = null;
608 if (mountPoint == null) {
609 module = this.getLatestModule(globalSchema, moduleName);
610 if (module == null) {
611 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
612 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
615 SchemaContext schemaContext = mountPoint.getSchemaContext();
616 module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName);
617 if (module == null) {
618 throw new RestconfDocumentedException("\"" + moduleName
619 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
623 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
624 if (targetNode == null) {
625 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
626 + "\" was not found in parent data node.\n" + " 2. \"" + head
627 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
628 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
631 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
632 if (potentialSchemaNodes.size() > 1) {
633 final StringBuilder strBuilder = new StringBuilder();
634 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
635 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
638 throw new RestconfDocumentedException(
639 "URI has bad format. Node \""
641 + "\" is added as augment from more than one module. "
642 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
643 + "\nThe node is added as augment from modules with namespaces:\n"
644 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
647 if (potentialSchemaNodes.isEmpty()) {
648 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
649 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
652 targetNode = potentialSchemaNodes.iterator().next();
655 if (!this.isListOrContainer(targetNode)) {
656 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
657 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
661 if ((targetNode instanceof ListSchemaNode)) {
662 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
663 final int keysSize = listNode.getKeyDefinition().size();
664 if ((strings.size() - consumed) < keysSize) {
665 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
666 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
669 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
670 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
672 for (final QName key : listNode.getKeyDefinition()) {
674 final String uriKeyValue = uriKeyValues.get(i);
675 if (uriKeyValue.equals(NULL_VALUE)) {
676 throw new RestconfDocumentedException("URI has bad format. List \""
677 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
678 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
681 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
686 consumed = consumed + i;
687 builder.nodeWithKey(targetNode.getQName(), keyValues);
689 builder.node(targetNode.getQName());
692 if ((targetNode instanceof DataNodeContainer)) {
693 final List<String> remaining = strings.subList(consumed, strings.size());
694 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
695 returnJustMountPoint);
698 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
701 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
702 final URI namespace) {
703 Preconditions.<URI> checkNotNull(namespace);
705 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
707 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
709 public boolean apply(final DataSchemaNode node) {
710 return Objects.equal(node.getQName().getNamespace(), namespace);
714 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
715 return Iterables.getFirst(result, null);
718 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
719 Preconditions.<DataNodeContainer> checkNotNull(container);
720 Preconditions.<String> checkNotNull(name);
722 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
723 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
724 return instantiatedDataNodeContainers;
727 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
728 final DataNodeContainer container, final String name) {
730 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
732 public boolean apply(final DataSchemaNode node) {
733 return Objects.equal(node.getQName().getLocalName(), name);
737 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
739 // Can't combine this loop with the filter above because the filter is
740 // lazily-applied by Iterables.filter.
741 for (final DataSchemaNode potentialNode : nodes) {
742 if (this.isInstantiatedDataSchema(potentialNode)) {
743 potentialSchemaNodes.add(potentialNode);
747 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
749 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
751 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
752 return node.getCases();
756 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
759 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
760 for (final ChoiceCaseNode caze : allCases) {
761 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
765 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
766 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
767 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
768 || node instanceof AnyXmlSchemaNode;
771 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
772 final MountInstance mountPoint) {
773 Preconditions.<String> checkNotNull(uriValue);
774 Preconditions.checkArgument((node instanceof LeafSchemaNode));
776 final String urlDecoded = urlPathArgDecode(uriValue);
777 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
778 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
780 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
781 String additionalInfo = "";
782 if (decoded == null) {
783 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
784 if ((baseType instanceof IdentityrefTypeDefinition)) {
785 decoded = this.toQName(urlDecoded);
786 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
790 if (decoded == null) {
791 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
792 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
795 map.put(node.getQName(), decoded);
798 private static String toModuleName(final String str) {
799 Preconditions.<String> checkNotNull(str);
800 if (str.indexOf(':') != -1) {
801 final Iterable<String> args = COLON_SPLITTER.split(str);
802 if (Iterables.size(args) == 2) {
803 return args.iterator().next();
809 private static String toNodeName(final String str) {
810 if (str.indexOf(':') != -1) {
811 final Iterable<String> args = COLON_SPLITTER.split(str);
812 if (Iterables.size(args) == 2) {
813 return Iterables.get(args, 1);
819 private QName toQName(final String name) {
820 final String module = toModuleName(name);
821 final String node = toNodeName(name);
822 Set<Module> modules = globalSchema.getModules();
824 final Comparator<Module> comparator = new Comparator<Module>() {
826 public int compare(final Module o1, final Module o2) {
827 return o1.getRevision().compareTo(o2.getRevision());
831 List<Module> sorted = new ArrayList<Module>(modules);
832 Collections.<Module> sort(new ArrayList<Module>(modules), comparator);
834 final Function<Module, QName> transform = new Function<Module, QName>() {
836 public QName apply(final Module m) {
837 return QName.create(m.getNamespace(), m.getRevision(), m.getName());
841 final Predicate<QName> findFirst = new Predicate<QName>() {
843 public boolean apply(final QName qn) {
844 return Objects.equal(module, qn.getLocalName());
848 Optional<QName> namespace = FluentIterable.from(sorted).transform(transform).firstMatch(findFirst);
849 return namespace.isPresent() ? QName.create(namespace.get(), node) : null;
852 private boolean isListOrContainer(final DataSchemaNode node) {
853 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
856 public RpcDefinition getRpcDefinition(final String name) {
857 final QName validName = this.toQName(name);
858 return validName == null ? null : this.qnameToRpc.get().get(validName);
862 public void onGlobalContextUpdated(final SchemaContext context) {
863 if (context != null) {
864 final Collection<RpcDefinition> defs = context.getOperations();
865 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
867 for (final RpcDefinition operation : defs) {
868 newMap.put(operation.getQName(), operation);
871 // FIXME: still not completely atomic
872 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
873 this.setGlobalSchema(context);
877 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
879 List<String> decodedPathArgs = new ArrayList<String>();
880 for (final String pathArg : strings) {
881 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
882 decodedPathArgs.add(_decode);
884 return decodedPathArgs;
885 } catch (UnsupportedEncodingException e) {
886 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
887 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
891 public String urlPathArgDecode(final String pathArg) {
892 if (pathArg != null) {
894 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
895 } catch (UnsupportedEncodingException e) {
896 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
897 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
904 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
905 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
906 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
907 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
908 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
909 } else if (argument != null && node != null) {
910 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
912 throw new IllegalArgumentException("Unhandled parameter types: "
913 + Arrays.<Object> asList(argument, node).toString());
917 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
918 StringBuilder builder = new StringBuilder();
920 QName nodeType = argument.getNodeType();
921 builder.append(this.toRestconfIdentifier(nodeType));
922 return builder.toString();
925 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
926 final ListSchemaNode node) {
927 QName nodeType = argument.getNodeType();
928 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
929 final Map<QName, Object> keyValues = argument.getKeyValues();
931 StringBuilder builder = new StringBuilder();
933 builder.append(nodeIdentifier);
936 List<QName> keyDefinition = node.getKeyDefinition();
937 boolean hasElements = false;
938 for (final QName key : keyDefinition) {
946 builder.append(this.toUriString(keyValues.get(key)));
947 } catch (UnsupportedEncodingException e) {
948 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
953 return builder.toString();
956 private static DataSchemaNode childByQName(final Object container, final QName name) {
957 if (container instanceof ChoiceCaseNode) {
958 return childByQName((ChoiceCaseNode) container, name);
959 } else if (container instanceof ChoiceNode) {
960 return childByQName((ChoiceNode) container, name);
961 } else if (container instanceof ContainerSchemaNode) {
962 return childByQName((ContainerSchemaNode) container, name);
963 } else if (container instanceof ListSchemaNode) {
964 return childByQName((ListSchemaNode) container, name);
965 } else if (container instanceof DataSchemaNode) {
966 return childByQName((DataSchemaNode) container, name);
967 } else if (container instanceof Module) {
968 return childByQName((Module) container, name);
970 throw new IllegalArgumentException("Unhandled parameter types: "
971 + Arrays.<Object> asList(container, name).toString());