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;
32 import java.util.Map.Entry;
34 import java.util.concurrent.atomic.AtomicReference;
35 import javax.ws.rs.core.Response.Status;
36 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
37 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
38 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
39 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
40 import org.opendaylight.controller.sal.rest.api.Draft02;
41 import org.opendaylight.controller.sal.rest.impl.RestUtil;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
43 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
44 import org.opendaylight.yangtools.concepts.Codec;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class ControllerContext implements SchemaContextListener {
73 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
75 private final static ControllerContext INSTANCE = new ControllerContext();
77 private final static String NULL_VALUE = "null";
79 private final static String MOUNT_MODULE = "yang-ext";
81 private final static String MOUNT_NODE = "mount";
83 public final static String MOUNT = "yang-ext:mount";
85 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
87 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
89 private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
91 private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
93 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
94 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
96 private volatile SchemaContext globalSchema;
97 private volatile DOMMountPointService mountService;
99 private DataNormalizer dataNormalizer;
101 public void setGlobalSchema(final SchemaContext globalSchema) {
102 this.globalSchema = globalSchema;
103 this.dataNormalizer = new DataNormalizer(globalSchema);
106 public void setMountService(final DOMMountPointService mountService) {
107 this.mountService = mountService;
110 private ControllerContext() {
113 public static ControllerContext getInstance() {
114 return ControllerContext.INSTANCE;
117 private void checkPreconditions() {
118 if (globalSchema == null) {
119 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
123 public void setSchemas(final SchemaContext schemas) {
124 this.onGlobalContextUpdated(schemas);
127 public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
128 return this.toIdentifier(restconfInstance, false);
131 public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
132 return this.toIdentifier(restconfInstance, true);
135 private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
136 this.checkPreconditions();
138 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
139 omitFirstAndLastEmptyString(pathArgs);
140 if (pathArgs.isEmpty()) {
144 String first = pathArgs.iterator().next();
145 final String startModule = ControllerContext.toModuleName(first);
146 if (startModule == null) {
147 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
148 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
151 InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
152 Module latestModule = globalSchema.findModuleByName(startModule, null);
153 InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
154 toMountPointIdentifier);
156 if (iiWithSchemaNode == null) {
157 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
160 return iiWithSchemaNode;
163 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
164 if (list.isEmpty()) {
168 String head = list.iterator().next();
169 if (head.isEmpty()) {
173 if (list.isEmpty()) {
177 String last = list.get(list.size() - 1);
178 if (last.isEmpty()) {
179 list.remove(list.size() - 1);
184 public Module findModuleByName(final String moduleName) {
185 this.checkPreconditions();
186 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
187 return globalSchema.findModuleByName(moduleName, null);
190 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
191 Preconditions.checkArgument(moduleName != null && mountPoint != null);
193 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
194 if (mountPointSchema == null) {
198 return mountPointSchema.findModuleByName(moduleName, null);
201 public Module findModuleByNamespace(final URI namespace) {
202 this.checkPreconditions();
203 Preconditions.checkArgument(namespace != null);
204 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
207 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
208 Preconditions.checkArgument(namespace != null && mountPoint != null);
210 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
211 if (mountPointSchema == null) {
215 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
218 public Module findModuleByNameAndRevision(final QName module) {
219 this.checkPreconditions();
220 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
222 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
225 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
226 this.checkPreconditions();
227 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
228 && mountPoint != null);
230 SchemaContext schemaContext = mountPoint.getSchemaContext();
231 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
232 module.getRevision());
235 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
236 this.checkPreconditions();
238 final Iterable<PathArgument> elements = path.getPathArguments();
239 PathArgument head = elements.iterator().next();
240 final QName startQName = head.getNodeType();
241 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
242 startQName.getRevision());
243 DataNodeContainer node = initialModule;
244 for (final PathArgument element : elements) {
245 QName _nodeType = element.getNodeType();
246 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
247 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
250 node = (DataNodeContainer) potentialNode;
256 public String toFullRestconfIdentifier(final YangInstanceIdentifier path) {
257 this.checkPreconditions();
259 final Iterable<PathArgument> elements = path.getPathArguments();
260 final StringBuilder builder = new StringBuilder();
261 PathArgument head = elements.iterator().next();
262 final QName startQName = head.getNodeType();
263 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
264 startQName.getRevision());
265 DataNodeContainer node = initialModule;
266 for (final PathArgument element : elements) {
267 QName _nodeType = element.getNodeType();
268 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
269 if (!ControllerContext.isListOrContainer(potentialNode)) {
272 node = ((DataNodeContainer) potentialNode);
273 builder.append(this.convertToRestconfIdentifier(element, node));
276 return builder.toString();
279 public String findModuleNameByNamespace(final URI namespace) {
280 this.checkPreconditions();
282 String moduleName = this.uriToModuleName.get(namespace);
283 if (moduleName == null) {
284 final Module module = this.findModuleByNamespace(namespace);
285 if (module != null) {
286 moduleName = module.getName();
287 this.uriToModuleName.put(namespace, moduleName);
294 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
295 final Module module = this.findModuleByNamespace(mountPoint, namespace);
296 return module == null ? null : module.getName();
299 public URI findNamespaceByModuleName(final String moduleName) {
300 URI namespace = this.moduleNameToUri.get(moduleName);
301 if (namespace == null) {
302 Module module = this.findModuleByName(moduleName);
303 if (module != null) {
304 URI _namespace = module.getNamespace();
305 namespace = _namespace;
306 this.uriToModuleName.put(namespace, moduleName);
312 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
313 final Module module = this.findModuleByName(mountPoint, moduleName);
314 return module == null ? null : module.getNamespace();
317 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
318 this.checkPreconditions();
320 SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
321 return schemaContext == null ? null : schemaContext.getModules();
324 public Set<Module> getAllModules() {
325 this.checkPreconditions();
326 return globalSchema.getModules();
329 public CharSequence toRestconfIdentifier(final QName qname) {
330 this.checkPreconditions();
332 String module = this.uriToModuleName.get(qname.getNamespace());
333 if (module == null) {
334 final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
335 qname.getRevision());
336 if (moduleSchema == null) {
340 this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
341 module = moduleSchema.getName();
344 StringBuilder builder = new StringBuilder();
345 builder.append(module);
347 builder.append(qname.getLocalName());
348 return builder.toString();
351 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
352 if (mountPoint == null) {
356 SchemaContext schemaContext = mountPoint.getSchemaContext();
358 final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
359 qname.getRevision());
360 if (moduleSchema == null) {
364 StringBuilder builder = new StringBuilder();
365 builder.append(moduleSchema.getName());
367 builder.append(qname.getLocalName());
368 return builder.toString();
371 public Module getRestconfModule() {
372 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
375 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
377 public boolean apply(final GroupingDefinition g) {
378 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
382 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
383 Module restconfModule = getRestconfModule();
384 if (restconfModule == null) {
388 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
390 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
392 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
394 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
395 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
396 return Iterables.getFirst(instanceDataChildrenByName, null);
399 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
401 public boolean apply(final GroupingDefinition g) {
402 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
406 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
407 Module restconfModule = inRestconfModule;
408 if (restconfModule == null) {
409 restconfModule = getRestconfModule();
412 if (restconfModule == null) {
416 Set<GroupingDefinition> groupings = restconfModule.getGroupings();
417 Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
418 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
420 List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
421 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
422 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
424 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
425 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
426 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
427 return Iterables.getFirst(instances, null);
428 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
429 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
430 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
431 return Iterables.getFirst(instances, null);
432 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
433 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
434 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
435 final DataSchemaNode modules = Iterables.getFirst(instances, null);
436 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
437 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
438 return Iterables.getFirst(instances, null);
439 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
440 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
441 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
442 return Iterables.getFirst(instances, null);
443 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
444 List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
445 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
446 final DataSchemaNode modules = Iterables.getFirst(instances, null);
447 instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
448 Draft02.RestConfModule.MODULE_LIST_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);
459 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
460 for (final ChoiceCaseNode caze : container.getCases()) {
461 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
470 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
471 return container.getDataChildByName(name);
474 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
475 return ControllerContext.dataNodeChildByQName(container, name);
478 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
479 return ControllerContext.dataNodeChildByQName(container, name);
482 private static DataSchemaNode childByQName(final Module container, final QName name) {
483 return ControllerContext.dataNodeChildByQName(container, name);
486 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
490 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
491 DataSchemaNode ret = container.getDataChildByName(name);
493 for (final DataSchemaNode node : container.getChildNodes()) {
494 if ((node instanceof ChoiceNode)) {
495 final ChoiceNode choiceNode = ((ChoiceNode) node);
496 DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
497 if (childByQName != null) {
506 private String toUriString(final Object object) throws UnsupportedEncodingException {
507 return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
510 private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
511 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
512 final boolean returnJustMountPoint) {
513 Preconditions.<List<String>> checkNotNull(strings);
515 if (parentNode == null) {
519 if (strings.isEmpty()) {
520 return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
523 String head = strings.iterator().next();
524 final String nodeName = toNodeName(head);
525 final String moduleName = ControllerContext.toModuleName(head);
527 DataSchemaNode targetNode = null;
528 if (!Strings.isNullOrEmpty(moduleName)) {
529 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
530 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
531 if (mountPoint != null) {
532 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
533 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
536 if (mountService == null) {
537 throw new RestconfDocumentedException(
538 "MountService was not found. Finding behind mount points does not work.",
539 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
542 final YangInstanceIdentifier partialPath = builder.toInstance();
543 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
544 if (!mountOpt.isPresent()) {
545 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
546 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
547 ErrorTag.UNKNOWN_ELEMENT);
549 DOMMountPoint mount = mountOpt.get();
551 final SchemaContext mountPointSchema = mount.getSchemaContext();
552 if (mountPointSchema == null) {
553 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
554 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
557 if (returnJustMountPoint) {
558 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
559 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
562 if (strings.size() == 1) {
563 YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
564 return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
567 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
568 if (moduleNameBehindMountPoint == null) {
569 throw new RestconfDocumentedException(
570 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
571 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
574 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
575 if (moduleBehindMountPoint == null) {
576 throw new RestconfDocumentedException("\"" + moduleName
577 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
580 List<String> subList = strings.subList(1, strings.size());
581 return this.collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
582 returnJustMountPoint);
585 Module module = null;
586 if (mountPoint == null) {
587 module = globalSchema.findModuleByName(moduleName, null);
588 if (module == null) {
589 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
590 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
593 SchemaContext schemaContext = mountPoint.getSchemaContext();
594 if (schemaContext != null) {
595 module = schemaContext.findModuleByName(moduleName, null);
599 if (module == null) {
600 throw new RestconfDocumentedException("\"" + moduleName
601 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
605 targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
606 if (targetNode == null) {
607 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
608 + "\" was not found in parent data node.\n" + " 2. \"" + head
609 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
610 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
613 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
614 if (potentialSchemaNodes.size() > 1) {
615 final StringBuilder strBuilder = new StringBuilder();
616 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
617 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
620 throw new RestconfDocumentedException(
621 "URI has bad format. Node \""
623 + "\" is added as augment from more than one module. "
624 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
625 + "\nThe node is added as augment from modules with namespaces:\n"
626 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
629 if (potentialSchemaNodes.isEmpty()) {
630 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
631 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
634 targetNode = potentialSchemaNodes.iterator().next();
637 if (!ControllerContext.isListOrContainer(targetNode)) {
638 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
639 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
643 if ((targetNode instanceof ListSchemaNode)) {
644 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
645 final int keysSize = listNode.getKeyDefinition().size();
646 if ((strings.size() - consumed) < keysSize) {
647 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
648 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
651 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
652 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
654 for (final QName key : listNode.getKeyDefinition()) {
656 final String uriKeyValue = uriKeyValues.get(i);
657 if (uriKeyValue.equals(NULL_VALUE)) {
658 throw new RestconfDocumentedException("URI has bad format. List \""
659 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
660 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
663 this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
668 consumed = consumed + i;
669 builder.nodeWithKey(targetNode.getQName(), keyValues);
671 builder.node(targetNode.getQName());
674 if ((targetNode instanceof DataNodeContainer)) {
675 final List<String> remaining = strings.subList(consumed, strings.size());
676 return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
677 returnJustMountPoint);
680 return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
683 public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
684 final URI namespace) {
685 Preconditions.<URI> checkNotNull(namespace);
687 final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
689 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
691 public boolean apply(final DataSchemaNode node) {
692 return Objects.equal(node.getQName().getNamespace(), namespace);
696 Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
697 return Iterables.getFirst(result, null);
700 public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
701 Preconditions.<DataNodeContainer> checkNotNull(container);
702 Preconditions.<String> checkNotNull(name);
704 List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
705 this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
706 return instantiatedDataNodeContainers;
709 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
711 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
712 return node.getCases();
716 private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
717 final DataNodeContainer container, final String name) {
719 Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
721 public boolean apply(final DataSchemaNode node) {
722 return Objects.equal(node.getQName().getLocalName(), name);
726 Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
728 // Can't combine this loop with the filter above because the filter is
729 // lazily-applied by Iterables.filter.
730 for (final DataSchemaNode potentialNode : nodes) {
731 if (this.isInstantiatedDataSchema(potentialNode)) {
732 potentialSchemaNodes.add(potentialNode);
736 Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
737 Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
739 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
740 for (final ChoiceCaseNode caze : allCases) {
741 this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
745 public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
746 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
747 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
748 || node instanceof AnyXmlSchemaNode;
751 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
752 final DOMMountPoint mountPoint) {
753 Preconditions.<String> checkNotNull(uriValue);
754 Preconditions.checkArgument((node instanceof LeafSchemaNode));
756 final String urlDecoded = urlPathArgDecode(uriValue);
757 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
758 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
760 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
761 String additionalInfo = "";
762 if (decoded == null) {
763 TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
764 if ((baseType instanceof IdentityrefTypeDefinition)) {
765 decoded = this.toQName(urlDecoded);
766 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
770 if (decoded == null) {
771 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
772 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
775 map.put(node.getQName(), decoded);
778 private static String toModuleName(final String str) {
779 final int idx = str.indexOf(':');
784 // Make sure there is only one occurrence
785 if (str.indexOf(':', idx + 1) != -1) {
789 return str.substring(0, idx);
792 private static String toNodeName(final String str) {
793 final int idx = str.indexOf(':');
798 // Make sure there is only one occurrence
799 if (str.indexOf(':', idx + 1) != -1) {
803 return str.substring(idx + 1);
806 private QName toQName(final String name) {
807 final String module = toModuleName(name);
808 final String node = toNodeName(name);
809 final Module m = globalSchema.findModuleByName(module, null);
810 return m == null ? null : QName.create(m.getQNameModule(), node);
813 private static boolean isListOrContainer(final DataSchemaNode node) {
814 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
817 public RpcDefinition getRpcDefinition(final String name) {
818 final QName validName = this.toQName(name);
819 return validName == null ? null : this.qnameToRpc.get().get(validName);
823 public void onGlobalContextUpdated(final SchemaContext context) {
824 if (context != null) {
825 final Collection<RpcDefinition> defs = context.getOperations();
826 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
828 for (final RpcDefinition operation : defs) {
829 newMap.put(operation.getQName(), operation);
832 // FIXME: still not completely atomic
833 this.qnameToRpc.set(ImmutableMap.copyOf(newMap));
834 this.setGlobalSchema(context);
838 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
840 List<String> decodedPathArgs = new ArrayList<String>();
841 for (final String pathArg : strings) {
842 String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
843 decodedPathArgs.add(_decode);
845 return decodedPathArgs;
846 } catch (UnsupportedEncodingException e) {
847 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
848 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
852 public String urlPathArgDecode(final String pathArg) {
853 if (pathArg != null) {
855 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
856 } catch (UnsupportedEncodingException e) {
857 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
858 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
865 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
866 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
867 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
868 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
869 return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
870 } else if (argument != null && node != null) {
871 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
873 throw new IllegalArgumentException("Unhandled parameter types: "
874 + Arrays.<Object> asList(argument, node).toString());
878 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
879 StringBuilder builder = new StringBuilder();
881 QName nodeType = argument.getNodeType();
882 builder.append(this.toRestconfIdentifier(nodeType));
883 return builder.toString();
886 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
887 final ListSchemaNode node) {
888 QName nodeType = argument.getNodeType();
889 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
890 final Map<QName, Object> keyValues = argument.getKeyValues();
892 StringBuilder builder = new StringBuilder();
894 builder.append(nodeIdentifier);
897 List<QName> keyDefinition = node.getKeyDefinition();
898 boolean hasElements = false;
899 for (final QName key : keyDefinition) {
907 builder.append(this.toUriString(keyValues.get(key)));
908 } catch (UnsupportedEncodingException e) {
909 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
914 return builder.toString();
917 private static DataSchemaNode childByQName(final Object container, final QName name) {
918 if (container instanceof ChoiceCaseNode) {
919 return childByQName((ChoiceCaseNode) container, name);
920 } else if (container instanceof ChoiceNode) {
921 return childByQName((ChoiceNode) container, name);
922 } else if (container instanceof ContainerSchemaNode) {
923 return childByQName((ContainerSchemaNode) container, name);
924 } else if (container instanceof ListSchemaNode) {
925 return childByQName((ListSchemaNode) container, name);
926 } else if (container instanceof DataSchemaNode) {
927 return childByQName((DataSchemaNode) container, name);
928 } else if (container instanceof Module) {
929 return childByQName((Module) container, name);
931 throw new IllegalArgumentException("Unhandled parameter types: "
932 + Arrays.<Object> asList(container, name).toString());
936 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
937 final CompositeNode compositeNode) {
939 return dataNormalizer.toNormalized(legacy, compositeNode);
940 } catch (NullPointerException e) {
941 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
945 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
947 return dataNormalizer.toNormalized(legacy);
948 } catch (NullPointerException e) {
949 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
953 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
954 final NormalizedNode<?,?> normalizedNode) {
956 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
957 } catch (NullPointerException e) {
958 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
962 public DataNormalizationOperation<?> getRootOperation() {
963 return dataNormalizer.getRootOperation();