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.ImmutableMap;
18 import com.google.common.collect.Iterables;
19 import java.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import java.util.concurrent.atomic.AtomicReference;
33 import javax.ws.rs.core.Response.Status;
34 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
36 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
38 import org.opendaylight.controller.sal.rest.api.Draft02;
39 import org.opendaylight.controller.sal.rest.impl.RestUtil;
40 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
41 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
42 import org.opendaylight.yangtools.concepts.Codec;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
59 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
66 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class ControllerContext implements SchemaContextListener {
72 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
74 private final static ControllerContext INSTANCE = new ControllerContext();
76 private final static String NULL_VALUE = "null";
78 private final static String MOUNT_MODULE = "yang-ext";
80 private final static String MOUNT_NODE = "mount";
82 public final static String MOUNT = "yang-ext:mount";
84 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
86 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
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 private DataNormalizer dataNormalizer;
96 public void setGlobalSchema(final SchemaContext globalSchema) {
97 this.globalSchema = globalSchema;
98 dataNormalizer = new DataNormalizer(globalSchema);
101 public void setMountService(final DOMMountPointService mountService) {
102 this.mountService = mountService;
105 private ControllerContext() {
108 public static ControllerContext getInstance() {
109 return ControllerContext.INSTANCE;
112 private void checkPreconditions() {
113 if (globalSchema == null) {
114 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
118 public void setSchemas(final SchemaContext schemas) {
119 onGlobalContextUpdated(schemas);
122 public InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
123 return toIdentifier(restconfInstance, false);
126 public SchemaContext getGlobalSchema() {
130 public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
131 return toIdentifier(restconfInstance, true);
134 private InstanceIdentifierContext toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
135 checkPreconditions();
137 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
138 omitFirstAndLastEmptyString(pathArgs);
139 if (pathArgs.isEmpty()) {
143 final String first = pathArgs.iterator().next();
144 final String startModule = ControllerContext.toModuleName(first);
145 if (startModule == null) {
146 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
147 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
150 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
151 final Module latestModule = globalSchema.findModuleByName(startModule, null);
152 final InstanceIdentifierContext iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
153 toMountPointIdentifier);
155 if (iiWithSchemaNode == null) {
156 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
159 return iiWithSchemaNode;
162 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
163 if (list.isEmpty()) {
167 final String head = list.iterator().next();
168 if (head.isEmpty()) {
172 if (list.isEmpty()) {
176 final String last = list.get(list.size() - 1);
177 if (last.isEmpty()) {
178 list.remove(list.size() - 1);
183 public Module findModuleByName(final String moduleName) {
184 checkPreconditions();
185 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
186 return globalSchema.findModuleByName(moduleName, null);
189 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
190 Preconditions.checkArgument(moduleName != null && mountPoint != null);
192 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
193 if (mountPointSchema == null) {
197 return mountPointSchema.findModuleByName(moduleName, null);
200 public Module findModuleByNamespace(final URI namespace) {
201 checkPreconditions();
202 Preconditions.checkArgument(namespace != null);
203 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
206 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
207 Preconditions.checkArgument(namespace != null && mountPoint != null);
209 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
210 if (mountPointSchema == null) {
214 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
217 public Module findModuleByNameAndRevision(final QName module) {
218 checkPreconditions();
219 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
221 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
224 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
225 checkPreconditions();
226 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
227 && mountPoint != null);
229 final SchemaContext schemaContext = mountPoint.getSchemaContext();
230 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
231 module.getRevision());
234 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
235 checkPreconditions();
237 final Iterable<PathArgument> elements = path.getPathArguments();
238 final PathArgument head = elements.iterator().next();
239 final QName startQName = head.getNodeType();
240 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
241 startQName.getRevision());
242 DataNodeContainer node = initialModule;
243 for (final PathArgument element : elements) {
244 final QName _nodeType = element.getNodeType();
245 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
246 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
249 node = (DataNodeContainer) potentialNode;
255 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
256 checkPreconditions();
258 final Iterable<PathArgument> elements = path.getPathArguments();
259 final StringBuilder builder = new StringBuilder();
260 final PathArgument head = elements.iterator().next();
261 final QName startQName = head.getNodeType();
262 final SchemaContext schemaContext;
264 schemaContext = mount.getSchemaContext();
266 schemaContext = globalSchema;
268 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
269 startQName.getRevision());
270 DataNodeContainer node = initialModule;
271 for (final PathArgument element : elements) {
272 if (!(element instanceof AugmentationIdentifier)) {
273 final QName _nodeType = element.getNodeType();
274 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
275 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)) {
276 if (!ControllerContext.isListOrContainer(potentialNode)) {
279 builder.append(convertToRestconfIdentifier(element, (DataNodeContainer) potentialNode, mount));
280 node = (DataNodeContainer) potentialNode;
285 return builder.toString();
288 public String findModuleNameByNamespace(final URI namespace) {
289 checkPreconditions();
291 final Module module = this.findModuleByNamespace(namespace);
292 return module == null ? null : module.getName();
295 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
296 final Module module = this.findModuleByNamespace(mountPoint, namespace);
297 return module == null ? null : module.getName();
300 public URI findNamespaceByModuleName(final String moduleName) {
301 final Module module = this.findModuleByName(moduleName);
302 return module == null ? null : module.getNamespace();
305 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
306 final Module module = this.findModuleByName(mountPoint, moduleName);
307 return module == null ? null : module.getNamespace();
310 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
311 checkPreconditions();
313 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
314 return schemaContext == null ? null : schemaContext.getModules();
317 public Set<Module> getAllModules() {
318 checkPreconditions();
319 return globalSchema.getModules();
322 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
323 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
324 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
327 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
328 final SchemaContext schema;
330 schema = mount.getSchemaContext();
332 checkPreconditions();
333 schema = globalSchema;
336 return toRestconfIdentifier(schema, qname);
339 public CharSequence toRestconfIdentifier(final QName qname) {
340 checkPreconditions();
342 return toRestconfIdentifier(globalSchema, qname);
345 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
346 if (mountPoint == null) {
350 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
353 public Module getRestconfModule() {
354 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
357 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
359 public boolean apply(final GroupingDefinition g) {
360 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
364 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
365 final Module restconfModule = getRestconfModule();
366 if (restconfModule == null) {
370 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
372 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
374 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
376 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
377 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
378 return Iterables.getFirst(instanceDataChildrenByName, null);
381 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
383 public boolean apply(final GroupingDefinition g) {
384 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
388 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
389 Module restconfModule = inRestconfModule;
390 if (restconfModule == null) {
391 restconfModule = getRestconfModule();
394 if (restconfModule == null) {
398 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
399 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
400 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
402 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
403 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
404 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
406 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
407 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
408 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
409 return Iterables.getFirst(instances, null);
410 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
411 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
412 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
413 return Iterables.getFirst(instances, null);
414 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
415 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
416 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
417 final DataSchemaNode modules = Iterables.getFirst(instances, null);
418 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
419 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
420 return Iterables.getFirst(instances, null);
421 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
422 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
423 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
424 return Iterables.getFirst(instances, null);
425 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
426 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
427 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
428 final DataSchemaNode modules = Iterables.getFirst(instances, null);
429 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
430 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
431 return Iterables.getFirst(instances, null);
432 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
433 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
434 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
435 return Iterables.getFirst(instances, null);
441 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
442 for (final ChoiceCaseNode caze : container.getCases()) {
443 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
452 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
453 return container.getDataChildByName(name);
456 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
457 return ControllerContext.dataNodeChildByQName(container, name);
460 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
461 return ControllerContext.dataNodeChildByQName(container, name);
464 private static DataSchemaNode childByQName(final Module container, final QName name) {
465 return ControllerContext.dataNodeChildByQName(container, name);
468 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
472 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
473 final DataSchemaNode ret = container.getDataChildByName(name);
475 for (final DataSchemaNode node : container.getChildNodes()) {
476 if ((node instanceof ChoiceNode)) {
477 final ChoiceNode choiceNode = ((ChoiceNode) node);
478 final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
479 if (childByQName != null) {
488 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
489 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
490 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
493 private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
494 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
495 final boolean returnJustMountPoint) {
496 Preconditions.<List<String>> checkNotNull(strings);
498 if (parentNode == null) {
502 if (strings.isEmpty()) {
503 return new InstanceIdentifierContext(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
506 final String head = strings.iterator().next();
507 final String nodeName = toNodeName(head);
508 final String moduleName = ControllerContext.toModuleName(head);
510 DataSchemaNode targetNode = null;
511 if (!Strings.isNullOrEmpty(moduleName)) {
512 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
513 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
514 if (mountPoint != null) {
515 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
516 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
519 if (mountService == null) {
520 throw new RestconfDocumentedException(
521 "MountService was not found. Finding behind mount points does not work.",
522 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
525 final YangInstanceIdentifier partialPath = builder.toInstance();
526 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
527 if (!mountOpt.isPresent()) {
528 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
529 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
530 ErrorTag.UNKNOWN_ELEMENT);
532 final DOMMountPoint mount = mountOpt.get();
534 final SchemaContext mountPointSchema = mount.getSchemaContext();
535 if (mountPointSchema == null) {
536 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
537 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
540 if (returnJustMountPoint) {
541 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
542 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
545 if (strings.size() == 1) {
546 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
547 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
550 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
551 if (moduleNameBehindMountPoint == null) {
552 throw new RestconfDocumentedException(
553 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
554 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
557 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
558 if (moduleBehindMountPoint == null) {
559 throw new RestconfDocumentedException("\"" + moduleName
560 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
563 final List<String> subList = strings.subList(1, strings.size());
564 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
565 returnJustMountPoint);
568 Module module = null;
569 if (mountPoint == null) {
570 checkPreconditions();
571 module = globalSchema.findModuleByName(moduleName, null);
572 if (module == null) {
573 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
574 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
577 final SchemaContext schemaContext = mountPoint.getSchemaContext();
578 if (schemaContext != null) {
579 module = schemaContext.findModuleByName(moduleName, null);
583 if (module == null) {
584 throw new RestconfDocumentedException("\"" + moduleName
585 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
589 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
590 if (targetNode == null) {
591 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
592 + "\" was not found in parent data node.\n" + " 2. \"" + head
593 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
594 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
597 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
598 if (potentialSchemaNodes.size() > 1) {
599 final StringBuilder strBuilder = new StringBuilder();
600 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
601 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
604 throw new RestconfDocumentedException(
605 "URI has bad format. Node \""
607 + "\" is added as augment from more than one module. "
608 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
609 + "\nThe node is added as augment from modules with namespaces:\n"
610 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
613 if (potentialSchemaNodes.isEmpty()) {
614 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
615 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
618 targetNode = potentialSchemaNodes.iterator().next();
621 if (!ControllerContext.isListOrContainer(targetNode)) {
622 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
623 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
627 if ((targetNode instanceof ListSchemaNode)) {
628 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
629 final int keysSize = listNode.getKeyDefinition().size();
630 if ((strings.size() - consumed) < keysSize) {
631 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
632 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
635 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
636 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
638 for (final QName key : listNode.getKeyDefinition()) {
640 final String uriKeyValue = uriKeyValues.get(i);
641 if (uriKeyValue.equals(NULL_VALUE)) {
642 throw new RestconfDocumentedException("URI has bad format. List \""
643 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
644 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
647 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
652 consumed = consumed + i;
653 builder.nodeWithKey(targetNode.getQName(), keyValues);
655 builder.node(targetNode.getQName());
658 if ((targetNode instanceof DataNodeContainer)) {
659 final List<String> remaining = strings.subList(consumed, strings.size());
660 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
661 returnJustMountPoint);
664 return new InstanceIdentifierContext(builder.toInstance(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
667 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
668 final URI namespace) {
669 Preconditions.<URI> checkNotNull(namespace);
671 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
673 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
675 public boolean apply(final DataSchemaNode node) {
676 return Objects.equal(node.getQName().getNamespace(), namespace);
680 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
681 return Iterables.getFirst(result, null);
684 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
685 Preconditions.<DataNodeContainer> checkNotNull(container);
686 Preconditions.<String> checkNotNull(name);
688 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
689 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
690 return instantiatedDataNodeContainers;
693 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
695 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
696 return node.getCases();
700 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
701 final DataNodeContainer container, final String name) {
703 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
705 public boolean apply(final DataSchemaNode node) {
706 return Objects.equal(node.getQName().getLocalName(), name);
710 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
712 // Can't combine this loop with the filter above because the filter is
713 // lazily-applied by Iterables.filter.
714 for (final DataSchemaNode potentialNode : nodes) {
715 if (isInstantiatedDataSchema(potentialNode)) {
716 potentialSchemaNodes.add(potentialNode);
720 final Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
721 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
723 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
724 for (final ChoiceCaseNode caze : allCases) {
725 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
729 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
730 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
731 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
732 || node instanceof AnyXmlSchemaNode;
735 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
736 final DOMMountPoint mountPoint) {
737 Preconditions.<String> checkNotNull(uriValue);
738 Preconditions.checkArgument((node instanceof LeafSchemaNode));
740 final String urlDecoded = urlPathArgDecode(uriValue);
741 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
742 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
744 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
745 String additionalInfo = "";
746 if (decoded == null) {
747 final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
748 if ((baseType instanceof IdentityrefTypeDefinition)) {
749 decoded = toQName(urlDecoded);
750 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
754 if (decoded == null) {
755 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
756 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
759 map.put(node.getQName(), decoded);
762 private static String toModuleName(final String str) {
763 final int idx = str.indexOf(':');
768 // Make sure there is only one occurrence
769 if (str.indexOf(':', idx + 1) != -1) {
773 return str.substring(0, idx);
776 private static String toNodeName(final String str) {
777 final int idx = str.indexOf(':');
782 // Make sure there is only one occurrence
783 if (str.indexOf(':', idx + 1) != -1) {
787 return str.substring(idx + 1);
790 private QName toQName(final String name) {
791 checkPreconditions();
792 final String module = toModuleName(name);
793 final String node = toNodeName(name);
794 final Module m = globalSchema.findModuleByName(module, null);
795 return m == null ? null : QName.create(m.getQNameModule(), node);
798 private static boolean isListOrContainer(final DataSchemaNode node) {
799 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
802 public RpcDefinition getRpcDefinition(final String name) {
803 final QName validName = toQName(name);
804 return validName == null ? null : qnameToRpc.get().get(validName);
808 public void onGlobalContextUpdated(final SchemaContext context) {
809 if (context != null) {
810 final Collection<RpcDefinition> defs = context.getOperations();
811 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
813 for (final RpcDefinition operation : defs) {
814 newMap.put(operation.getQName(), operation);
817 // FIXME: still not completely atomic
818 qnameToRpc.set(ImmutableMap.copyOf(newMap));
819 setGlobalSchema(context);
823 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
825 final List<String> decodedPathArgs = new ArrayList<String>();
826 for (final String pathArg : strings) {
827 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
828 decodedPathArgs.add(_decode);
830 return decodedPathArgs;
831 } catch (final UnsupportedEncodingException e) {
832 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
833 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
837 public String urlPathArgDecode(final String pathArg) {
838 if (pathArg != null) {
840 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
841 } catch (final UnsupportedEncodingException e) {
842 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
843 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
850 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node, final DOMMountPoint mount) {
851 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
852 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
853 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
854 return convertToRestconfIdentifier(argument, node, mount);
855 } else if (argument != null && node != null) {
856 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
858 throw new IllegalArgumentException("Unhandled parameter types: "
859 + Arrays.<Object> asList(argument, node).toString());
863 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
864 return "/" + this.toRestconfIdentifier(argument.getNodeType());
867 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
868 final ListSchemaNode node, final DOMMountPoint mount) {
869 final QName nodeType = argument.getNodeType();
870 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
871 final Map<QName, Object> keyValues = argument.getKeyValues();
873 final StringBuilder builder = new StringBuilder();
875 builder.append(nodeIdentifier);
878 final List<QName> keyDefinition = node.getKeyDefinition();
879 boolean hasElements = false;
880 for (final QName key : keyDefinition) {
881 for (final DataSchemaNode listChild : node.getChildNodes()) {
882 if (listChild.getQName().equals(key)) {
890 Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
891 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
892 } catch (final UnsupportedEncodingException e) {
893 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
901 return builder.toString();
904 private static DataSchemaNode childByQName(final Object container, final QName name) {
905 if (container instanceof ChoiceCaseNode) {
906 return childByQName((ChoiceCaseNode) container, name);
907 } else if (container instanceof ChoiceNode) {
908 return childByQName((ChoiceNode) container, name);
909 } else if (container instanceof ContainerSchemaNode) {
910 return childByQName((ContainerSchemaNode) container, name);
911 } else if (container instanceof ListSchemaNode) {
912 return childByQName((ListSchemaNode) container, name);
913 } else if (container instanceof DataSchemaNode) {
914 return childByQName((DataSchemaNode) container, name);
915 } else if (container instanceof Module) {
916 return childByQName((Module) container, name);
918 throw new IllegalArgumentException("Unhandled parameter types: "
919 + Arrays.<Object> asList(container, name).toString());
923 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
924 final CompositeNode compositeNode) {
926 return dataNormalizer.toNormalized(legacy, compositeNode);
927 } catch (final NullPointerException e) {
928 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
932 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
934 return dataNormalizer.toNormalized(legacy);
935 } catch (final NullPointerException e) {
936 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
940 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
941 final NormalizedNode<?,?> normalizedNode) {
943 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
944 } catch (final NullPointerException e) {
945 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
949 public DataNormalizationOperation<?> getRootOperation() {
950 return dataNormalizer.getRootOperation();