2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.sal.restconf.impl;
10 import com.google.common.base.Function;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicate;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.BiMap;
18 import com.google.common.collect.HashBiMap;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Iterables;
21 import java.io.UnsupportedEncodingException;
23 import java.net.URLDecoder;
24 import java.net.URLEncoder;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
33 import java.util.concurrent.atomic.AtomicReference;
34 import javax.ws.rs.core.Response.Status;
35 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
36 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
37 import org.opendaylight.controller.sal.rest.api.Draft02;
38 import org.opendaylight.controller.sal.rest.impl.RestUtil;
39 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
40 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
41 import org.opendaylight.yangtools.concepts.Codec;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
50 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
55 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
62 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 public class ControllerContext implements SchemaContextListener {
68 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
70 private final static ControllerContext INSTANCE = new ControllerContext();
72 private final static String NULL_VALUE = "null";
74 private final static String MOUNT_MODULE = "yang-ext";
76 private final static String MOUNT_NODE = "mount";
78 public final static String MOUNT = "yang-ext:mount";
80 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
82 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
84 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
86 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
88 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
89 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
91 private volatile SchemaContext globalSchema;
92 private volatile DOMMountPointService mountService;
94 public void setGlobalSchema(final SchemaContext globalSchema) {
95 this.globalSchema = globalSchema;
98 public void setMountService(final DOMMountPointService mountService) {
99 this.mountService = mountService;
102 private ControllerContext() {
105 public static ControllerContext getInstance() {
106 return ControllerContext.INSTANCE;
109 private void checkPreconditions() {
110 if (globalSchema == null) {
111 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
115 public void setSchemas(final SchemaContext schemas) {
116 this.onGlobalContextUpdated(schemas);
119 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
120 return this.toIdentifier(restconfInstance, false);
123 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
124 return this.toIdentifier(restconfInstance, true);
127 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
128 this.checkPreconditions();
130 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
131 omitFirstAndLastEmptyString(pathArgs);
132 if (pathArgs.isEmpty()) {
136 String first = pathArgs.iterator().next();
137 final String startModule = ControllerContext.toModuleName(first);
138 if (startModule == null) {
139 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
140 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
143 InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
144 Module latestModule = globalSchema.findModuleByName(startModule, null);
145 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
146 toMountPointIdentifier);
148 if (iiWithSchemaNode == null) {
149 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
152 return iiWithSchemaNode;
155 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
156 if (list.isEmpty()) {
160 String head = list.iterator().next();
161 if (head.isEmpty()) {
165 if (list.isEmpty()) {
169 String last = list.get(list.size() - 1);
170 if (last.isEmpty()) {
171 list.remove(list.size() - 1);
176 public Module findModuleByName(final String moduleName) {
177 this.checkPreconditions();
178 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
179 return globalSchema.findModuleByName(moduleName, null);
182 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
183 Preconditions.checkArgument(moduleName != null && mountPoint != null);
185 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
186 if (mountPointSchema == null) {
190 return mountPointSchema.findModuleByName(moduleName, null);
193 public Module findModuleByNamespace(final URI namespace) {
194 this.checkPreconditions();
195 Preconditions.checkArgument(namespace != null);
196 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
199 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
200 Preconditions.checkArgument(namespace != null && mountPoint != null);
202 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
203 if (mountPointSchema == null) {
207 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
210 public Module findModuleByNameAndRevision(final QName module) {
211 this.checkPreconditions();
212 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
214 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
217 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
218 this.checkPreconditions();
219 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
220 && mountPoint != null);
222 SchemaContext schemaContext = mountPoint.getSchemaContext();
223 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
224 module.getRevision());
227 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
228 this.checkPreconditions();
230 final Iterable<PathArgument> elements = path.getPathArguments();
231 PathArgument head = elements.iterator().next();
232 final QName startQName = head.getNodeType();
233 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
234 startQName.getRevision());
235 DataNodeContainer node = initialModule;
236 for (final PathArgument element : elements) {
237 QName _nodeType = element.getNodeType();
238 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
239 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
242 node = (DataNodeContainer) potentialNode;
248 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
249 this.checkPreconditions();
251 final Iterable<PathArgument> elements = path.getPathArguments();
252 final StringBuilder builder = new StringBuilder();
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 (!ControllerContext.isListOrContainer(potentialNode)) {
264 node = ((DataNodeContainer) potentialNode);
265 builder.append(this.convertToRestconfIdentifier(element, node));
268 return builder.toString();
271 public String findModuleNameByNamespace(final URI namespace) {
272 this.checkPreconditions();
274 String moduleName = this.uriToModuleName.get(namespace);
275 if (moduleName == null) {
276 final Module module = this.findModuleByNamespace(namespace);
277 if (module != null) {
278 moduleName = module.getName();
279 this.uriToModuleName.put(namespace, moduleName);
286 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
287 final Module module = this.findModuleByNamespace(mountPoint, namespace);
288 return module == null ? null : module.getName();
291 public URI findNamespaceByModuleName(final String moduleName) {
292 URI namespace = this.moduleNameToUri.get(moduleName);
293 if (namespace == null) {
294 Module module = this.findModuleByName(moduleName);
295 if (module != null) {
296 URI _namespace = module.getNamespace();
297 namespace = _namespace;
298 this.uriToModuleName.put(namespace, moduleName);
304 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
305 final Module module = this.findModuleByName(mountPoint, moduleName);
306 return module == null ? null : module.getNamespace();
309 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
310 this.checkPreconditions();
312 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
313 return schemaContext == null ? null : schemaContext.getModules();
316 public Set<Module> getAllModules() {
317 this.checkPreconditions();
318 return globalSchema.getModules();
321 public CharSequence toRestconfIdentifier(final QName qname) {
322 this.checkPreconditions();
324 String module = this.uriToModuleName.get(qname.getNamespace());
325 if (module == null) {
326 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
327 qname.getRevision());
328 if (moduleSchema == null) {
332 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
333 module = moduleSchema.getName();
336 StringBuilder builder = new StringBuilder();
337 builder.append(module);
339 builder.append(qname.getLocalName());
340 return builder.toString();
343 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
344 if (mountPoint == null) {
348 SchemaContext schemaContext = mountPoint.getSchemaContext();
350 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
351 qname.getRevision());
352 if (moduleSchema == null) {
356 StringBuilder builder = new StringBuilder();
357 builder.append(moduleSchema.getName());
359 builder.append(qname.getLocalName());
360 return builder.toString();
363 public Module getRestconfModule() {
364 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
367 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
369 public boolean apply(final GroupingDefinition g) {
370 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
374 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
375 Module restconfModule = getRestconfModule();
376 if (restconfModule == null) {
380 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
382 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
384 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
386 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
387 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
388 return Iterables.getFirst(instanceDataChildrenByName, null);
391 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
393 public boolean apply(final GroupingDefinition g) {
394 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
398 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
399 Module restconfModule = inRestconfModule;
400 if (restconfModule == null) {
401 restconfModule = getRestconfModule();
404 if (restconfModule == null) {
408 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
409 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
410 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
412 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
413 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
414 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
416 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
417 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
418 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
419 return Iterables.getFirst(instances, null);
420 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
421 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
422 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
423 return Iterables.getFirst(instances, null);
424 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
425 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
426 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
427 final DataSchemaNode modules = Iterables.getFirst(instances, null);
428 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
429 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
430 return Iterables.getFirst(instances, null);
431 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
432 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
433 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
434 return Iterables.getFirst(instances, null);
435 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
436 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
437 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
438 final DataSchemaNode modules = Iterables.getFirst(instances, null);
439 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
440 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
441 return Iterables.getFirst(instances, null);
442 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
443 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
444 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
445 return Iterables.getFirst(instances, null);
451 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
452 for (final ChoiceCaseNode caze : container.getCases()) {
453 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
462 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
463 return container.getDataChildByName(name);
466 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
467 return ControllerContext.dataNodeChildByQName(container, name);
470 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
471 return ControllerContext.dataNodeChildByQName(container, name);
474 private static DataSchemaNode childByQName(final Module container, final QName name) {
475 return ControllerContext.dataNodeChildByQName(container, name);
478 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
482 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
483 DataSchemaNode ret = container.getDataChildByName(name);
485 for (final DataSchemaNode node : container.getChildNodes()) {
486 if ((node instanceof ChoiceNode)) {
487 final ChoiceNode choiceNode = ((ChoiceNode) node);
488 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
489 if (childByQName != null) {
498 private String toUriString(final Object object) throws UnsupportedEncodingException {
499 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
502 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
503 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
504 final boolean returnJustMountPoint) {
505 Preconditions.<List<String>> checkNotNull(strings);
507 if (parentNode == null) {
511 if (strings.isEmpty()) {
512 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
515 String head = strings.iterator().next();
516 final String nodeName = toNodeName(head);
517 final String moduleName = ControllerContext.toModuleName(head);
519 DataSchemaNode targetNode = null;
520 if (!Strings.isNullOrEmpty(moduleName)) {
521 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
522 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
523 if (mountPoint != null) {
524 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
525 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
528 if (mountService == null) {
529 throw new RestconfDocumentedException(
530 "MountService was not found. Finding behind mount points does not work.",
531 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
534 final YangInstanceIdentifier partialPath = builder.toInstance();
535 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
536 if (!mountOpt.isPresent()) {
537 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
538 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
539 ErrorTag.UNKNOWN_ELEMENT);
541 DOMMountPoint mount = mountOpt.get();
543 final SchemaContext mountPointSchema = mount.getSchemaContext();
544 if (mountPointSchema == null) {
545 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
546 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
549 if (returnJustMountPoint) {
550 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
551 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
554 if (strings.size() == 1) {
555 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
556 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
559 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
560 if (moduleNameBehindMountPoint == null) {
561 throw new RestconfDocumentedException(
562 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
563 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
566 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
567 if (moduleBehindMountPoint == null) {
568 throw new RestconfDocumentedException("\"" + moduleName
569 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
572 List<String> subList = strings.subList(1, strings.size());
573 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
574 returnJustMountPoint);
577 Module module = null;
578 if (mountPoint == null) {
579 module = globalSchema.findModuleByName(moduleName, null);
580 if (module == null) {
581 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
582 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
585 SchemaContext schemaContext = mountPoint.getSchemaContext();
586 if (schemaContext != null) {
587 module = schemaContext.findModuleByName(moduleName, null);
591 if (module == null) {
592 throw new RestconfDocumentedException("\"" + moduleName
593 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
597 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
598 if (targetNode == null) {
599 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
600 + "\" was not found in parent data node.\n" + " 2. \"" + head
601 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
602 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
605 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
606 if (potentialSchemaNodes.size() > 1) {
607 final StringBuilder strBuilder = new StringBuilder();
608 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
609 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
612 throw new RestconfDocumentedException(
613 "URI has bad format. Node \""
615 + "\" is added as augment from more than one module. "
616 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
617 + "\nThe node is added as augment from modules with namespaces:\n"
618 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
621 if (potentialSchemaNodes.isEmpty()) {
622 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
623 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
626 targetNode = potentialSchemaNodes.iterator().next();
629 if (!ControllerContext.isListOrContainer(targetNode)) {
630 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
631 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
635 if ((targetNode instanceof ListSchemaNode)) {
636 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
637 final int keysSize = listNode.getKeyDefinition().size();
638 if ((strings.size() - consumed) < keysSize) {
639 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
640 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
643 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
644 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
646 for (final QName key : listNode.getKeyDefinition()) {
648 final String uriKeyValue = uriKeyValues.get(i);
649 if (uriKeyValue.equals(NULL_VALUE)) {
650 throw new RestconfDocumentedException("URI has bad format. List \""
651 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
652 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
655 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
660 consumed = consumed + i;
661 builder.nodeWithKey(targetNode.getQName(), keyValues);
663 builder.node(targetNode.getQName());
666 if ((targetNode instanceof DataNodeContainer)) {
667 final List<String> remaining = strings.subList(consumed, strings.size());
668 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
669 returnJustMountPoint);
672 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
675 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
676 final URI namespace) {
677 Preconditions.<URI> checkNotNull(namespace);
679 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
681 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
683 public boolean apply(final DataSchemaNode node) {
684 return Objects.equal(node.getQName().getNamespace(), namespace);
688 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
689 return Iterables.getFirst(result, null);
692 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
693 Preconditions.<DataNodeContainer> checkNotNull(container);
694 Preconditions.<String> checkNotNull(name);
696 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
697 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
698 return instantiatedDataNodeContainers;
701 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
703 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
704 return node.getCases();
708 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
709 final DataNodeContainer container, final String name) {
711 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
713 public boolean apply(final DataSchemaNode node) {
714 return Objects.equal(node.getQName().getLocalName(), name);
718 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
720 // Can't combine this loop with the filter above because the filter is
721 // lazily-applied by Iterables.filter.
722 for (final DataSchemaNode potentialNode : nodes) {
723 if (this.isInstantiatedDataSchema(potentialNode)) {
724 potentialSchemaNodes.add(potentialNode);
728 Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
729 Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
731 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
732 for (final ChoiceCaseNode caze : allCases) {
733 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
737 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
738 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
739 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
740 || node instanceof AnyXmlSchemaNode;
743 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
744 final DOMMountPoint mountPoint) {
745 Preconditions.<String> checkNotNull(uriValue);
746 Preconditions.checkArgument((node instanceof LeafSchemaNode));
748 final String urlDecoded = urlPathArgDecode(uriValue);
749 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
750 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
752 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
753 String additionalInfo = "";
754 if (decoded == null) {
755 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
756 if ((baseType instanceof IdentityrefTypeDefinition)) {
757 decoded = this.toQName(urlDecoded);
758 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
762 if (decoded == null) {
763 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
764 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
767 map.put(node.getQName(), decoded);
770 private static String toModuleName(final String str) {
771 final int idx = str.indexOf(':');
776 // Make sure there is only one occurrence
777 if (str.indexOf(':', idx + 1) != -1) {
781 return str.substring(0, idx);
784 private static String toNodeName(final String str) {
785 final int idx = str.indexOf(':');
790 // Make sure there is only one occurrence
791 if (str.indexOf(':', idx + 1) != -1) {
795 return str.substring(idx + 1);
798 private QName toQName(final String name) {
799 final String module = toModuleName(name);
800 final String node = toNodeName(name);
801 final Module m = globalSchema.findModuleByName(module, null);
802 return m == null ? null : QName.create(m.getQNameModule(), node);
805 private static boolean isListOrContainer(final DataSchemaNode node) {
806 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
809 public RpcDefinition getRpcDefinition(final String name) {
810 final QName validName = this.toQName(name);
811 return validName == null ? null : this.qnameToRpc.get().get(validName);
815 public void onGlobalContextUpdated(final SchemaContext context) {
816 if (context != null) {
817 final Collection<RpcDefinition> defs = context.getOperations();
818 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
820 for (final RpcDefinition operation : defs) {
821 newMap.put(operation.getQName(), operation);
824 // FIXME: still not completely atomic
825 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
826 this.setGlobalSchema(context);
830 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
832 List<String> decodedPathArgs = new ArrayList<String>();
833 for (final String pathArg : strings) {
834 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
835 decodedPathArgs.add(_decode);
837 return decodedPathArgs;
838 } catch (UnsupportedEncodingException e) {
839 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
840 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
844 public String urlPathArgDecode(final String pathArg) {
845 if (pathArg != null) {
847 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
848 } catch (UnsupportedEncodingException e) {
849 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
850 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
857 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
858 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
859 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
860 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
861 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
862 } else if (argument != null && node != null) {
863 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
865 throw new IllegalArgumentException("Unhandled parameter types: "
866 + Arrays.<Object> asList(argument, node).toString());
870 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
871 StringBuilder builder = new StringBuilder();
873 QName nodeType = argument.getNodeType();
874 builder.append(this.toRestconfIdentifier(nodeType));
875 return builder.toString();
878 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
879 final ListSchemaNode node) {
880 QName nodeType = argument.getNodeType();
881 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
882 final Map<QName, Object> keyValues = argument.getKeyValues();
884 StringBuilder builder = new StringBuilder();
886 builder.append(nodeIdentifier);
889 List<QName> keyDefinition = node.getKeyDefinition();
890 boolean hasElements = false;
891 for (final QName key : keyDefinition) {
899 builder.append(this.toUriString(keyValues.get(key)));
900 } catch (UnsupportedEncodingException e) {
901 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
906 return builder.toString();
909 private static DataSchemaNode childByQName(final Object container, final QName name) {
910 if (container instanceof ChoiceCaseNode) {
911 return childByQName((ChoiceCaseNode) container, name);
912 } else if (container instanceof ChoiceNode) {
913 return childByQName((ChoiceNode) container, name);
914 } else if (container instanceof ContainerSchemaNode) {
915 return childByQName((ContainerSchemaNode) container, name);
916 } else if (container instanceof ListSchemaNode) {
917 return childByQName((ListSchemaNode) container, name);
918 } else if (container instanceof DataSchemaNode) {
919 return childByQName((DataSchemaNode) container, name);
920 } else if (container instanceof Module) {
921 return childByQName((Module) container, name);
923 throw new IllegalArgumentException("Unhandled parameter types: "
924 + Arrays.<Object> asList(container, name).toString());