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.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.Collections;
28 import java.util.Comparator;
29 import java.util.HashMap;
30 import java.util.List;
33 import java.util.concurrent.ConcurrentHashMap;
34 import javax.ws.rs.core.Response.Status;
35 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
36 import org.opendaylight.controller.sal.core.api.mount.MountService;
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.InstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder;
45 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.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 static final Splitter COLON_SPLITTER = Splitter.on(':');
86 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
88 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
90 private final Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap<>();
92 private volatile SchemaContext globalSchema;
93 private volatile MountService mountService;
95 public void setGlobalSchema(final SchemaContext globalSchema) {
96 this.globalSchema = globalSchema;
99 public void setMountService(final MountService mountService) {
100 this.mountService = mountService;
103 private ControllerContext() {
106 public static ControllerContext getInstance() {
107 return ControllerContext.INSTANCE;
110 private void checkPreconditions() {
111 if (globalSchema == null) {
112 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
116 public void setSchemas(final SchemaContext schemas) {
117 this.onGlobalContextUpdated(schemas);
120 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
121 return this.toIdentifier(restconfInstance, false);
124 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
125 return this.toIdentifier(restconfInstance, true);
128 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
129 this.checkPreconditions();
131 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
132 omitFirstAndLastEmptyString(pathArgs);
133 if (pathArgs.isEmpty()) {
137 String first = pathArgs.iterator().next();
138 final String startModule = ControllerContext.toModuleName(first);
139 if (startModule == null) {
140 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
141 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
144 InstanceIdentifierBuilder builder = InstanceIdentifier.builder();
145 Module latestModule = this.getLatestModule(globalSchema, startModule);
146 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
147 toMountPointIdentifier);
149 if (iiWithSchemaNode == null) {
150 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
153 return iiWithSchemaNode;
156 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
157 if (list.isEmpty()) {
161 String head = list.iterator().next();
162 if (head.isEmpty()) {
166 if (list.isEmpty()) {
170 String last = list.get(list.size() - 1);
171 if (last.isEmpty()) {
172 list.remove(list.size() - 1);
178 private Module getLatestModule(final SchemaContext schema, final String moduleName) {
179 Preconditions.checkArgument(schema != null);
180 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
182 Predicate<Module> filter = new Predicate<Module>() {
184 public boolean apply(final Module m) {
185 return Objects.equal(m.getName(), moduleName);
189 Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
190 return this.filterLatestModule(modules);
193 private Module filterLatestModule(final Iterable<Module> modules) {
194 Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
195 for (final Module module : modules) {
196 if (module.getRevision().after(latestModule.getRevision())) {
197 latestModule = module;
203 public Module findModuleByName(final String moduleName) {
204 this.checkPreconditions();
205 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
206 return this.getLatestModule(globalSchema, moduleName);
209 public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
210 Preconditions.checkArgument(moduleName != null && mountPoint != null);
212 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
213 return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
216 public Module findModuleByNamespace(final URI namespace) {
217 this.checkPreconditions();
218 Preconditions.checkArgument(namespace != null);
220 final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
221 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
224 public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
225 Preconditions.checkArgument(namespace != null && mountPoint != null);
227 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
228 Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
229 return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
232 public Module findModuleByNameAndRevision(final QName module) {
233 this.checkPreconditions();
234 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
236 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
239 public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
240 this.checkPreconditions();
241 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
242 && mountPoint != null);
244 SchemaContext schemaContext = mountPoint.getSchemaContext();
245 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
246 module.getRevision());
249 public DataNodeContainer getDataNodeContainerFor(final InstanceIdentifier path) {
250 this.checkPreconditions();
252 final Iterable<PathArgument> elements = path.getPathArguments();
253 PathArgument head = elements.iterator().next();
254 final QName startQName = head.getNodeType();
255 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
256 startQName.getRevision());
257 DataNodeContainer node = initialModule;
258 for (final PathArgument element : elements) {
259 QName _nodeType = element.getNodeType();
260 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
261 if (potentialNode == null || !this.isListOrContainer(potentialNode)) {
264 node = (DataNodeContainer) potentialNode;
270 public String toFullRestconfIdentifier(final InstanceIdentifier path) {
271 this.checkPreconditions();
273 final Iterable<PathArgument> elements = path.getPathArguments();
274 final StringBuilder builder = new StringBuilder();
275 PathArgument head = elements.iterator().next();
276 final QName startQName = head.getNodeType();
277 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
278 startQName.getRevision());
279 DataNodeContainer node = initialModule;
280 for (final PathArgument element : elements) {
281 QName _nodeType = element.getNodeType();
282 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
283 if (!this.isListOrContainer(potentialNode)) {
286 node = ((DataNodeContainer) potentialNode);
287 builder.append(this.convertToRestconfIdentifier(element, node));
290 return builder.toString();
293 public String findModuleNameByNamespace(final URI namespace) {
294 this.checkPreconditions();
296 String moduleName = this.uriToModuleName.get(namespace);
297 if (moduleName == null) {
298 final Module module = this.findModuleByNamespace(namespace);
299 if (module != null) {
300 moduleName = module.getName();
301 this.uriToModuleName.put(namespace, moduleName);
308 public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
309 final Module module = this.findModuleByNamespace(mountPoint, namespace);
310 return module == null ? null : module.getName();
313 public URI findNamespaceByModuleName(final String moduleName) {
314 URI namespace = this.moduleNameToUri.get(moduleName);
315 if (namespace == null) {
316 Module module = this.findModuleByName(moduleName);
317 if (module != null) {
318 URI _namespace = module.getNamespace();
319 namespace = _namespace;
320 this.uriToModuleName.put(namespace, moduleName);
326 public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
327 final Module module = this.findModuleByName(mountPoint, moduleName);
328 return module == null ? null : module.getNamespace();
331 public Set<Module> getAllModules(final MountInstance mountPoint) {
332 this.checkPreconditions();
334 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
335 return schemaContext == null ? null : schemaContext.getModules();
338 public Set<Module> getAllModules() {
339 this.checkPreconditions();
340 return globalSchema.getModules();
343 public CharSequence toRestconfIdentifier(final QName qname) {
344 this.checkPreconditions();
346 String module = this.uriToModuleName.get(qname.getNamespace());
347 if (module == null) {
348 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
349 qname.getRevision());
350 if (moduleSchema == null) {
354 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
355 module = moduleSchema.getName();
358 StringBuilder builder = new StringBuilder();
359 builder.append(module);
361 builder.append(qname.getLocalName());
362 return builder.toString();
365 public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
366 if (mountPoint == null) {
370 SchemaContext schemaContext = mountPoint.getSchemaContext();
372 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
373 qname.getRevision());
374 if (moduleSchema == null) {
378 StringBuilder builder = new StringBuilder();
379 builder.append(moduleSchema.getName());
381 builder.append(qname.getLocalName());
382 return builder.toString();
385 public Module getRestconfModule() {
386 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
389 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
390 Module restconfModule = getRestconfModule();
391 if (restconfModule == null) {
395 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
397 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
399 public boolean apply(final GroupingDefinition g) {
400 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
404 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
406 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
408 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
409 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
410 return Iterables.getFirst(instanceDataChildrenByName, null);
413 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
414 Module restconfModule = inRestconfModule;
415 if (restconfModule == null) {
416 restconfModule = getRestconfModule();
419 if (restconfModule == null) {
423 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
425 final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
427 public boolean apply(final GroupingDefinition g) {
428 return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
432 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, filter);
434 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
436 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
437 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
438 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
440 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
441 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
442 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
443 return Iterables.getFirst(instances, null);
444 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
445 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
446 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
447 return Iterables.getFirst(instances, null);
448 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
449 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
450 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
451 final DataSchemaNode modules = Iterables.getFirst(instances, null);
452 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
453 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
454 return Iterables.getFirst(instances, null);
455 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
456 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
457 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
458 return Iterables.getFirst(instances, null);
459 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
460 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
461 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
462 final DataSchemaNode modules = Iterables.getFirst(instances, null);
463 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
464 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
465 return Iterables.getFirst(instances, null);
466 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
467 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
468 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
469 return Iterables.getFirst(instances, null);
475 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
476 for (final ChoiceCaseNode caze : container.getCases()) {
477 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
486 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
487 return container.getDataChildByName(name);
490 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
491 return ControllerContext.dataNodeChildByQName(container, name);
494 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
495 return ControllerContext.dataNodeChildByQName(container, name);
498 private static DataSchemaNode childByQName(final Module container, final QName name) {
499 return ControllerContext.dataNodeChildByQName(container, name);
502 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
506 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
507 DataSchemaNode ret = container.getDataChildByName(name);
509 for (final DataSchemaNode node : container.getChildNodes()) {
510 if ((node instanceof ChoiceCaseNode)) {
511 final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node);
512 DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
513 if (childByQName != null) {
522 private String toUriString(final Object object) throws UnsupportedEncodingException {
523 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
526 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
527 final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
528 final boolean returnJustMountPoint) {
529 Preconditions.<List<String>> checkNotNull(strings);
531 if (parentNode == null) {
535 if (strings.isEmpty()) {
536 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
539 String head = strings.iterator().next();
540 final String nodeName = toNodeName(head);
541 final String moduleName = ControllerContext.toModuleName(head);
543 DataSchemaNode targetNode = null;
544 if (!Strings.isNullOrEmpty(moduleName)) {
545 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
546 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
547 if (mountPoint != null) {
548 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
549 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
552 if (mountService == null) {
553 throw new RestconfDocumentedException(
554 "MountService was not found. Finding behind mount points does not work.",
555 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
558 final InstanceIdentifier partialPath = builder.toInstance();
559 final MountInstance mount = mountService.getMountPoint(partialPath);
561 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
562 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
563 ErrorTag.UNKNOWN_ELEMENT);
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 InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
574 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
577 if (strings.size() == 1) {
578 InstanceIdentifier instance = InstanceIdentifier.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(InstanceIdentifier.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 (!this.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 Set<DataSchemaNode> childNodes = container.getChildNodes();
726 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
728 public boolean apply(final DataSchemaNode node) {
729 return Objects.equal(node.getQName().getLocalName(), name);
733 Iterable<DataSchemaNode> nodes = Iterables.filter(childNodes, filter);
735 // Can't combine this loop with the filter above because the filter is
736 // lazily-applied by Iterables.filter.
737 for (final DataSchemaNode potentialNode : nodes) {
738 if (this.isInstantiatedDataSchema(potentialNode)) {
739 potentialSchemaNodes.add(potentialNode);
743 Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
745 final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
747 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
748 return node.getCases();
752 Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
755 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
756 for (final ChoiceCaseNode caze : allCases) {
757 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
761 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
762 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
763 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
764 || node instanceof AnyXmlSchemaNode;
767 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
768 final MountInstance mountPoint) {
769 Preconditions.<String> checkNotNull(uriValue);
770 Preconditions.checkArgument((node instanceof LeafSchemaNode));
772 final String urlDecoded = urlPathArgDecode(uriValue);
773 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
774 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
776 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
777 String additionalInfo = "";
778 if (decoded == null) {
779 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
780 if ((baseType instanceof IdentityrefTypeDefinition)) {
781 decoded = this.toQName(urlDecoded);
782 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
786 if (decoded == null) {
787 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
788 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
791 map.put(node.getQName(), decoded);
794 private static String toModuleName(final String str) {
795 Preconditions.<String> checkNotNull(str);
796 if (str.indexOf(':') != -1) {
797 final Iterable<String> args = COLON_SPLITTER.split(str);
798 if (Iterables.size(args) == 2) {
799 return args.iterator().next();
805 private static String toNodeName(final String str) {
806 if (str.indexOf(':') != -1) {
807 final Iterable<String> args = COLON_SPLITTER.split(str);
808 if (Iterables.size(args) == 2) {
809 return Iterables.get(args, 1);
815 private QName toQName(final String name) {
816 final String module = toModuleName(name);
817 final String node = toNodeName(name);
818 Set<Module> modules = globalSchema.getModules();
820 final Comparator<Module> comparator = new Comparator<Module>() {
822 public int compare(final Module o1, final Module o2) {
823 return o1.getRevision().compareTo(o2.getRevision());
827 List<Module> sorted = new ArrayList<Module>(modules);
828 Collections.<Module> sort(new ArrayList<Module>(modules), comparator);
830 final Function<Module, QName> transform = new Function<Module, QName>() {
832 public QName apply(final Module m) {
833 return QName.create(m.getNamespace(), m.getRevision(), m.getName());
837 final Predicate<QName> findFirst = new Predicate<QName>() {
839 public boolean apply(final QName qn) {
840 return Objects.equal(module, qn.getLocalName());
844 Optional<QName> namespace = FluentIterable.from(sorted).transform(transform).firstMatch(findFirst);
845 return namespace.isPresent() ? QName.create(namespace.get(), node) : null;
848 private boolean isListOrContainer(final DataSchemaNode node) {
849 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
852 public RpcDefinition getRpcDefinition(final String name) {
853 final QName validName = this.toQName(name);
854 return validName == null ? null : this.qnameToRpc.get(validName);
858 public void onGlobalContextUpdated(final SchemaContext context) {
859 if (context != null) {
860 this.qnameToRpc.clear();
861 this.setGlobalSchema(context);
862 Set<RpcDefinition> _operations = context.getOperations();
863 for (final RpcDefinition operation : _operations) {
865 this.qnameToRpc.put(operation.getQName(), operation);
871 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
873 List<String> decodedPathArgs = new ArrayList<String>();
874 for (final String pathArg : strings) {
875 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
876 decodedPathArgs.add(_decode);
878 return decodedPathArgs;
879 } catch (UnsupportedEncodingException e) {
880 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
881 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
885 public String urlPathArgDecode(final String pathArg) {
886 if (pathArg != null) {
888 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
889 } catch (UnsupportedEncodingException e) {
890 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
891 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
898 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
899 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
900 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
901 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
902 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
903 } else if (argument != null && node != null) {
904 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
906 throw new IllegalArgumentException("Unhandled parameter types: "
907 + Arrays.<Object> asList(argument, node).toString());
911 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
912 StringBuilder builder = new StringBuilder();
914 QName nodeType = argument.getNodeType();
915 builder.append(this.toRestconfIdentifier(nodeType));
916 return builder.toString();
919 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
920 final ListSchemaNode node) {
921 QName nodeType = argument.getNodeType();
922 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
923 final Map<QName, Object> keyValues = argument.getKeyValues();
925 StringBuilder builder = new StringBuilder();
927 builder.append(nodeIdentifier);
930 List<QName> keyDefinition = node.getKeyDefinition();
931 boolean hasElements = false;
932 for (final QName key : keyDefinition) {
940 builder.append(this.toUriString(keyValues.get(key)));
941 } catch (UnsupportedEncodingException e) {
942 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
947 return builder.toString();
950 private static DataSchemaNode childByQName(final Object container, final QName name) {
951 if (container instanceof ChoiceCaseNode) {
952 return childByQName((ChoiceCaseNode) container, name);
953 } else if (container instanceof ChoiceNode) {
954 return childByQName((ChoiceNode) container, name);
955 } else if (container instanceof ContainerSchemaNode) {
956 return childByQName((ContainerSchemaNode) container, name);
957 } else if (container instanceof ListSchemaNode) {
958 return childByQName((ListSchemaNode) container, name);
959 } else if (container instanceof DataSchemaNode) {
960 return childByQName((DataSchemaNode) container, name);
961 } else if (container instanceof Module) {
962 return childByQName((Module) container, name);
964 throw new IllegalArgumentException("Unhandled parameter types: "
965 + Arrays.<Object> asList(container, name).toString());