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());
591 if (targetNode == null && parentNode instanceof Module) {
592 final RpcDefinition rpc = ControllerContext.getInstance().getRpcDefinition(head);
594 return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
595 mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
599 if (targetNode == null) {
600 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
601 + "\" was not found in parent data node.\n" + " 2. \"" + head
602 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
603 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
606 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
607 if (potentialSchemaNodes.size() > 1) {
608 final StringBuilder strBuilder = new StringBuilder();
609 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
610 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
613 throw new RestconfDocumentedException(
614 "URI has bad format. Node \""
616 + "\" is added as augment from more than one module. "
617 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
618 + "\nThe node is added as augment from modules with namespaces:\n"
619 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
622 if (potentialSchemaNodes.isEmpty()) {
623 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
624 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
627 targetNode = potentialSchemaNodes.iterator().next();
630 if (!ControllerContext.isListOrContainer(targetNode)) {
631 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
632 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
636 if ((targetNode instanceof ListSchemaNode)) {
637 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
638 final int keysSize = listNode.getKeyDefinition().size();
639 if ((strings.size() - consumed) < keysSize) {
640 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
641 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
644 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
645 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
647 for (final QName key : listNode.getKeyDefinition()) {
649 final String uriKeyValue = uriKeyValues.get(i);
650 if (uriKeyValue.equals(NULL_VALUE)) {
651 throw new RestconfDocumentedException("URI has bad format. List \""
652 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
653 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
656 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
661 consumed = consumed + i;
662 builder.nodeWithKey(targetNode.getQName(), keyValues);
664 builder.node(targetNode.getQName());
667 if ((targetNode instanceof DataNodeContainer)) {
668 final List<String> remaining = strings.subList(consumed, strings.size());
669 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
670 returnJustMountPoint);
673 return new InstanceIdentifierContext(builder.toInstance(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
676 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
677 final URI namespace) {
678 Preconditions.<URI> checkNotNull(namespace);
680 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
682 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
684 public boolean apply(final DataSchemaNode node) {
685 return Objects.equal(node.getQName().getNamespace(), namespace);
689 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
690 return Iterables.getFirst(result, null);
693 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
694 Preconditions.<DataNodeContainer> checkNotNull(container);
695 Preconditions.<String> checkNotNull(name);
697 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
698 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
699 return instantiatedDataNodeContainers;
702 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
704 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
705 return node.getCases();
709 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
710 final DataNodeContainer container, final String name) {
712 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
714 public boolean apply(final DataSchemaNode node) {
715 return Objects.equal(node.getQName().getLocalName(), name);
719 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
721 // Can't combine this loop with the filter above because the filter is
722 // lazily-applied by Iterables.filter.
723 for (final DataSchemaNode potentialNode : nodes) {
724 if (isInstantiatedDataSchema(potentialNode)) {
725 potentialSchemaNodes.add(potentialNode);
729 final Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
730 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
732 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
733 for (final ChoiceCaseNode caze : allCases) {
734 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
738 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
739 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
740 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
741 || node instanceof AnyXmlSchemaNode;
744 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
745 final DOMMountPoint mountPoint) {
746 Preconditions.<String> checkNotNull(uriValue);
747 Preconditions.checkArgument((node instanceof LeafSchemaNode));
749 final String urlDecoded = urlPathArgDecode(uriValue);
750 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
751 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
753 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
754 String additionalInfo = "";
755 if (decoded == null) {
756 final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
757 if ((baseType instanceof IdentityrefTypeDefinition)) {
758 decoded = toQName(urlDecoded);
759 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
763 if (decoded == null) {
764 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
765 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
768 map.put(node.getQName(), decoded);
771 private static String toModuleName(final String str) {
772 final int idx = str.indexOf(':');
777 // Make sure there is only one occurrence
778 if (str.indexOf(':', idx + 1) != -1) {
782 return str.substring(0, idx);
785 private static String toNodeName(final String str) {
786 final int idx = str.indexOf(':');
791 // Make sure there is only one occurrence
792 if (str.indexOf(':', idx + 1) != -1) {
796 return str.substring(idx + 1);
799 private QName toQName(final String name) {
800 checkPreconditions();
801 final String module = toModuleName(name);
802 final String node = toNodeName(name);
803 final Module m = globalSchema.findModuleByName(module, null);
804 return m == null ? null : QName.create(m.getQNameModule(), node);
807 private static boolean isListOrContainer(final DataSchemaNode node) {
808 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
811 public RpcDefinition getRpcDefinition(final String name) {
812 final QName validName = toQName(name);
813 return validName == null ? null : qnameToRpc.get().get(validName);
817 public void onGlobalContextUpdated(final SchemaContext context) {
818 if (context != null) {
819 final Collection<RpcDefinition> defs = context.getOperations();
820 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
822 for (final RpcDefinition operation : defs) {
823 newMap.put(operation.getQName(), operation);
826 // FIXME: still not completely atomic
827 qnameToRpc.set(ImmutableMap.copyOf(newMap));
828 setGlobalSchema(context);
832 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
834 final List<String> decodedPathArgs = new ArrayList<String>();
835 for (final String pathArg : strings) {
836 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
837 decodedPathArgs.add(_decode);
839 return decodedPathArgs;
840 } catch (final UnsupportedEncodingException e) {
841 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
842 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
846 public String urlPathArgDecode(final String pathArg) {
847 if (pathArg != null) {
849 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
850 } catch (final UnsupportedEncodingException e) {
851 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
852 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
859 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node, final DOMMountPoint mount) {
860 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
861 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
862 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
863 return convertToRestconfIdentifier(argument, node, mount);
864 } else if (argument != null && node != null) {
865 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
867 throw new IllegalArgumentException("Unhandled parameter types: "
868 + Arrays.<Object> asList(argument, node).toString());
872 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
873 return "/" + this.toRestconfIdentifier(argument.getNodeType());
876 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
877 final ListSchemaNode node, final DOMMountPoint mount) {
878 final QName nodeType = argument.getNodeType();
879 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
880 final Map<QName, Object> keyValues = argument.getKeyValues();
882 final StringBuilder builder = new StringBuilder();
884 builder.append(nodeIdentifier);
887 final List<QName> keyDefinition = node.getKeyDefinition();
888 boolean hasElements = false;
889 for (final QName key : keyDefinition) {
890 for (final DataSchemaNode listChild : node.getChildNodes()) {
891 if (listChild.getQName().equals(key)) {
899 Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
900 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
901 } catch (final UnsupportedEncodingException e) {
902 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
910 return builder.toString();
913 private static DataSchemaNode childByQName(final Object container, final QName name) {
914 if (container instanceof ChoiceCaseNode) {
915 return childByQName((ChoiceCaseNode) container, name);
916 } else if (container instanceof ChoiceNode) {
917 return childByQName((ChoiceNode) container, name);
918 } else if (container instanceof ContainerSchemaNode) {
919 return childByQName((ContainerSchemaNode) container, name);
920 } else if (container instanceof ListSchemaNode) {
921 return childByQName((ListSchemaNode) container, name);
922 } else if (container instanceof DataSchemaNode) {
923 return childByQName((DataSchemaNode) container, name);
924 } else if (container instanceof Module) {
925 return childByQName((Module) container, name);
927 throw new IllegalArgumentException("Unhandled parameter types: "
928 + Arrays.<Object> asList(container, name).toString());
932 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
933 final CompositeNode compositeNode) {
935 return dataNormalizer.toNormalized(legacy, compositeNode);
936 } catch (final NullPointerException e) {
937 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
941 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
943 return dataNormalizer.toNormalized(legacy);
944 } catch (final NullPointerException e) {
945 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
949 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
950 final NormalizedNode<?,?> normalizedNode) {
952 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
953 } catch (final NullPointerException e) {
954 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
958 public DataNormalizationOperation<?> getRootOperation() {
959 return dataNormalizer.getRootOperation();