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.netconf.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;
31 import java.util.concurrent.atomic.AtomicReference;
32 import javax.ws.rs.core.Response.Status;
33 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
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.netconf.sal.rest.api.Draft02;
39 import org.opendaylight.netconf.sal.rest.impl.RestUtil;
40 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
41 import org.opendaylight.netconf.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.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
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 static final YangInstanceIdentifier ROOT = YangInstanceIdentifier.builder().build();
90 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
91 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
93 private volatile SchemaContext globalSchema;
94 private volatile DOMMountPointService mountService;
96 private DataNormalizer dataNormalizer;
98 public void setGlobalSchema(final SchemaContext globalSchema) {
99 this.globalSchema = globalSchema;
100 dataNormalizer = new DataNormalizer(globalSchema);
103 public void setMountService(final DOMMountPointService mountService) {
104 this.mountService = mountService;
107 private ControllerContext() {
110 public static ControllerContext getInstance() {
111 return ControllerContext.INSTANCE;
114 private void checkPreconditions() {
115 if (globalSchema == null) {
116 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
120 public void setSchemas(final SchemaContext schemas) {
121 onGlobalContextUpdated(schemas);
124 public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
125 return toIdentifier(restconfInstance, false);
128 public SchemaContext getGlobalSchema() {
132 public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
133 return toIdentifier(restconfInstance, true);
136 private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
137 checkPreconditions();
139 if(restconfInstance == null) {
140 return new InstanceIdentifierContext<>(ROOT, globalSchema, null, globalSchema);
143 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
144 omitFirstAndLastEmptyString(pathArgs);
145 if (pathArgs.isEmpty()) {
149 final String first = pathArgs.iterator().next();
150 final String startModule = ControllerContext.toModuleName(first);
151 if (startModule == null) {
152 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
153 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
156 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
157 final Module latestModule = globalSchema.findModuleByName(startModule, null);
159 if (latestModule == null) {
160 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
163 final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
164 toMountPointIdentifier);
166 if (iiWithSchemaNode == null) {
167 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
170 return iiWithSchemaNode;
173 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
174 if (list.isEmpty()) {
178 final String head = list.iterator().next();
179 if (head.isEmpty()) {
183 if (list.isEmpty()) {
187 final String last = list.get(list.size() - 1);
188 if (last.isEmpty()) {
189 list.remove(list.size() - 1);
194 public Module findModuleByName(final String moduleName) {
195 checkPreconditions();
196 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
197 return globalSchema.findModuleByName(moduleName, null);
200 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
201 Preconditions.checkArgument(moduleName != null && mountPoint != null);
203 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
204 if (mountPointSchema == null) {
208 return mountPointSchema.findModuleByName(moduleName, null);
211 public Module findModuleByNamespace(final URI namespace) {
212 checkPreconditions();
213 Preconditions.checkArgument(namespace != null);
214 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
217 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
218 Preconditions.checkArgument(namespace != null && mountPoint != null);
220 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
221 if (mountPointSchema == null) {
225 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
228 public Module findModuleByNameAndRevision(final QName module) {
229 checkPreconditions();
230 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
232 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
235 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
236 checkPreconditions();
237 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
238 && mountPoint != null);
240 final SchemaContext schemaContext = mountPoint.getSchemaContext();
241 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
242 module.getRevision());
245 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
246 checkPreconditions();
248 final Iterable<PathArgument> elements = path.getPathArguments();
249 final PathArgument head = elements.iterator().next();
250 final QName startQName = head.getNodeType();
251 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
252 startQName.getRevision());
253 DataNodeContainer node = initialModule;
254 for (final PathArgument element : elements) {
255 final QName _nodeType = element.getNodeType();
256 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
257 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
260 node = (DataNodeContainer) potentialNode;
266 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
267 checkPreconditions();
269 final Iterable<PathArgument> elements = path.getPathArguments();
270 final StringBuilder builder = new StringBuilder();
271 final PathArgument head = elements.iterator().next();
272 final QName startQName = head.getNodeType();
273 final SchemaContext schemaContext;
275 schemaContext = mount.getSchemaContext();
277 schemaContext = globalSchema;
279 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
280 startQName.getRevision());
281 DataNodeContainer node = initialModule;
282 for (final PathArgument element : elements) {
283 if (!(element instanceof AugmentationIdentifier)) {
284 final QName _nodeType = element.getNodeType();
285 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
286 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode) &&
287 !(potentialNode instanceof ChoiceSchemaNode)) {
288 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
289 if (potentialNode instanceof DataNodeContainer) {
290 node = (DataNodeContainer) potentialNode;
296 return builder.toString();
299 public String findModuleNameByNamespace(final URI namespace) {
300 checkPreconditions();
302 final Module module = this.findModuleByNamespace(namespace);
303 return module == null ? null : module.getName();
306 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
307 final Module module = this.findModuleByNamespace(mountPoint, namespace);
308 return module == null ? null : module.getName();
311 public URI findNamespaceByModuleName(final String moduleName) {
312 final Module module = this.findModuleByName(moduleName);
313 return module == null ? null : module.getNamespace();
316 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
317 final Module module = this.findModuleByName(mountPoint, moduleName);
318 return module == null ? null : module.getNamespace();
321 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
322 checkPreconditions();
324 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
325 return schemaContext == null ? null : schemaContext.getModules();
328 public Set<Module> getAllModules() {
329 checkPreconditions();
330 return globalSchema.getModules();
333 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
334 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
335 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
338 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
339 final SchemaContext schema;
341 schema = mount.getSchemaContext();
343 checkPreconditions();
344 schema = globalSchema;
347 return toRestconfIdentifier(schema, qname);
350 public CharSequence toRestconfIdentifier(final QName qname) {
351 checkPreconditions();
353 return toRestconfIdentifier(globalSchema, qname);
356 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
357 if (mountPoint == null) {
361 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
364 public Module getRestconfModule() {
365 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
368 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
370 public boolean apply(final GroupingDefinition g) {
371 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
375 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
376 final Module restconfModule = getRestconfModule();
377 if (restconfModule == null) {
381 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
383 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
385 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
387 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
388 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
389 return Iterables.getFirst(instanceDataChildrenByName, null);
392 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
394 public boolean apply(final GroupingDefinition g) {
395 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
399 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
400 Module restconfModule = inRestconfModule;
401 if (restconfModule == null) {
402 restconfModule = getRestconfModule();
405 if (restconfModule == null) {
409 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
410 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
411 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
413 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
414 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
415 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
417 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
418 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
419 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
420 return Iterables.getFirst(instances, null);
421 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
422 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
423 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
424 return Iterables.getFirst(instances, null);
425 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
426 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
427 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
428 final DataSchemaNode modules = Iterables.getFirst(instances, null);
429 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
430 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
431 return Iterables.getFirst(instances, null);
432 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
433 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
434 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
435 return Iterables.getFirst(instances, null);
436 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
437 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
438 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
439 final DataSchemaNode modules = Iterables.getFirst(instances, null);
440 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
441 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
442 return Iterables.getFirst(instances, null);
443 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
444 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
445 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
446 return Iterables.getFirst(instances, null);
452 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
453 for (final ChoiceCaseNode caze : container.getCases()) {
454 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
463 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
464 return container.getDataChildByName(name);
467 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
468 return ControllerContext.dataNodeChildByQName(container, name);
471 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
472 return ControllerContext.dataNodeChildByQName(container, name);
475 private static DataSchemaNode childByQName(final Module container, final QName name) {
476 return ControllerContext.dataNodeChildByQName(container, name);
479 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
483 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
484 final DataSchemaNode ret = container.getDataChildByName(name);
486 for (final DataSchemaNode node : container.getChildNodes()) {
487 if ((node instanceof ChoiceSchemaNode)) {
488 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
489 final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
490 if (childByQName != null) {
499 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
500 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
501 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
504 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
505 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
506 final boolean returnJustMountPoint) {
507 Preconditions.<List<String>> checkNotNull(strings);
509 if (parentNode == null) {
513 if (strings.isEmpty()) {
514 return createContext(builder.build(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
517 final String head = strings.iterator().next();
518 final String nodeName = toNodeName(head);
519 final String moduleName = ControllerContext.toModuleName(head);
521 DataSchemaNode targetNode = null;
522 if (!Strings.isNullOrEmpty(moduleName)) {
523 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
524 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
525 if (mountPoint != null) {
526 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
527 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
530 if (mountService == null) {
531 throw new RestconfDocumentedException(
532 "MountService was not found. Finding behind mount points does not work.",
533 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
536 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
537 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
538 if (!mountOpt.isPresent()) {
539 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
540 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
541 ErrorTag.DATA_MISSING);
543 final DOMMountPoint mount = mountOpt.get();
545 final SchemaContext mountPointSchema = mount.getSchemaContext();
546 if (mountPointSchema == null) {
547 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
548 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
551 if (returnJustMountPoint || strings.size() == 1) {
552 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build();
553 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
556 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
557 if (moduleNameBehindMountPoint == null) {
558 throw new RestconfDocumentedException(
559 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
560 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
563 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
564 if (moduleBehindMountPoint == null) {
565 throw new RestconfDocumentedException("\"" + moduleName
566 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
569 final List<String> subList = strings.subList(1, strings.size());
570 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
571 returnJustMountPoint);
574 Module module = null;
575 if (mountPoint == null) {
576 checkPreconditions();
577 module = globalSchema.findModuleByName(moduleName, null);
578 if (module == null) {
579 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
580 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
583 final SchemaContext schemaContext = mountPoint.getSchemaContext();
584 if (schemaContext != null) {
585 module = schemaContext.findModuleByName(moduleName, null);
589 if (module == null) {
590 throw new RestconfDocumentedException("\"" + moduleName
591 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
595 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
597 if (targetNode == null && parentNode instanceof Module) {
598 final RpcDefinition rpc = ControllerContext.getInstance().getRpcDefinition(head);
600 return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
601 mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
605 if (targetNode == null) {
606 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
607 + "\" was not found in parent data node.\n" + " 2. \"" + head
608 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
609 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
612 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
613 if (potentialSchemaNodes.size() > 1) {
614 final StringBuilder strBuilder = new StringBuilder();
615 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
616 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
619 throw new RestconfDocumentedException(
620 "URI has bad format. Node \""
622 + "\" is added as augment from more than one module. "
623 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
624 + "\nThe node is added as augment from modules with namespaces:\n"
625 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
628 if (potentialSchemaNodes.isEmpty()) {
629 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
630 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
633 targetNode = potentialSchemaNodes.iterator().next();
636 if (!ControllerContext.isListOrContainer(targetNode)) {
637 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
638 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
642 if ((targetNode instanceof ListSchemaNode)) {
643 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
644 final int keysSize = listNode.getKeyDefinition().size();
645 if ((strings.size() - consumed) < keysSize) {
646 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
647 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
650 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
651 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
653 for (final QName key : listNode.getKeyDefinition()) {
655 final String uriKeyValue = uriKeyValues.get(i);
656 if (uriKeyValue.equals(NULL_VALUE)) {
657 throw new RestconfDocumentedException("URI has bad format. List \""
658 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
659 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
662 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
667 consumed = consumed + i;
668 builder.nodeWithKey(targetNode.getQName(), keyValues);
670 builder.node(targetNode.getQName());
673 if ((targetNode instanceof DataNodeContainer)) {
674 final List<String> remaining = strings.subList(consumed, strings.size());
675 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
676 returnJustMountPoint);
679 return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
682 private InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
683 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
685 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
686 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
689 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
690 final URI namespace) {
691 Preconditions.<URI> checkNotNull(namespace);
693 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
695 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
697 public boolean apply(final DataSchemaNode node) {
698 return Objects.equal(node.getQName().getNamespace(), namespace);
702 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
703 return Iterables.getFirst(result, null);
706 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
707 Preconditions.<DataNodeContainer> checkNotNull(container);
708 Preconditions.<String> checkNotNull(name);
710 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
711 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
712 return instantiatedDataNodeContainers;
715 private static final Function<ChoiceSchemaNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceSchemaNode, Set<ChoiceCaseNode>>() {
717 public Set<ChoiceCaseNode> apply(final ChoiceSchemaNode node) {
718 return node.getCases();
722 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
723 final DataNodeContainer container, final String name) {
725 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
727 public boolean apply(final DataSchemaNode node) {
728 return Objects.equal(node.getQName().getLocalName(), name);
732 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
734 // Can't combine this loop with the filter above because the filter is
735 // lazily-applied by Iterables.filter.
736 for (final DataSchemaNode potentialNode : nodes) {
737 if (isInstantiatedDataSchema(potentialNode)) {
738 potentialSchemaNodes.add(potentialNode);
742 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
743 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
745 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
746 for (final ChoiceCaseNode caze : allCases) {
747 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
751 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
752 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
753 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
754 || node instanceof AnyXmlSchemaNode;
757 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
758 final DOMMountPoint mountPoint) {
759 Preconditions.checkNotNull(uriValue);
760 Preconditions.checkArgument((node instanceof LeafSchemaNode));
762 final String urlDecoded = urlPathArgDecode(uriValue);
763 TypeDefinition<?> typedef = ((LeafSchemaNode) node).getType();
764 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
765 if (baseType instanceof LeafrefTypeDefinition) {
766 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, globalSchema, node);
768 Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
769 Object decoded = codec.deserialize(urlDecoded);
770 String additionalInfo = "";
771 if (decoded == null) {
772 if ((baseType instanceof IdentityrefTypeDefinition)) {
773 decoded = toQName(urlDecoded);
774 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
778 if (decoded == null) {
779 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
780 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
783 map.put(node.getQName(), decoded);
786 private static String toModuleName(final String str) {
787 final int idx = str.indexOf(':');
792 // Make sure there is only one occurrence
793 if (str.indexOf(':', idx + 1) != -1) {
797 return str.substring(0, idx);
800 private static String toNodeName(final String str) {
801 final int idx = str.indexOf(':');
806 // Make sure there is only one occurrence
807 if (str.indexOf(':', idx + 1) != -1) {
811 return str.substring(idx + 1);
814 private QName toQName(final String name) {
815 checkPreconditions();
816 final String module = toModuleName(name);
817 final String node = toNodeName(name);
818 final Module m = globalSchema.findModuleByName(module, null);
819 return m == null ? null : QName.create(m.getQNameModule(), node);
822 private static boolean isListOrContainer(final DataSchemaNode node) {
823 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
826 public RpcDefinition getRpcDefinition(final String name) {
827 final QName validName = toQName(name);
828 return validName == null ? null : qnameToRpc.get().get(validName);
832 public void onGlobalContextUpdated(final SchemaContext context) {
833 if (context != null) {
834 final Collection<RpcDefinition> defs = context.getOperations();
835 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
837 for (final RpcDefinition operation : defs) {
838 newMap.put(operation.getQName(), operation);
841 // FIXME: still not completely atomic
842 qnameToRpc.set(ImmutableMap.copyOf(newMap));
843 setGlobalSchema(context);
847 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
849 final List<String> decodedPathArgs = new ArrayList<String>();
850 for (final String pathArg : strings) {
851 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
852 decodedPathArgs.add(_decode);
854 return decodedPathArgs;
855 } catch (final UnsupportedEncodingException e) {
856 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
857 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
861 public String urlPathArgDecode(final String pathArg) {
862 if (pathArg != null) {
864 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
865 } catch (final UnsupportedEncodingException e) {
866 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
867 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
874 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node, final DOMMountPoint mount) {
875 if (argument instanceof NodeIdentifier) {
876 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
877 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
878 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node, mount);
879 } else if (argument != null && node != null) {
880 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
882 throw new IllegalArgumentException("Unhandled parameter types: "
883 + Arrays.<Object> asList(argument, node).toString());
887 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
888 return "/" + this.toRestconfIdentifier(argument.getNodeType(),node);
891 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
892 final ListSchemaNode node, final DOMMountPoint mount) {
893 final QName nodeType = argument.getNodeType();
894 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
895 final Map<QName, Object> keyValues = argument.getKeyValues();
897 final StringBuilder builder = new StringBuilder();
899 builder.append(nodeIdentifier);
902 final List<QName> keyDefinition = node.getKeyDefinition();
903 boolean hasElements = false;
904 for (final QName key : keyDefinition) {
905 for (final DataSchemaNode listChild : node.getChildNodes()) {
906 if (listChild.getQName().equals(key)) {
914 Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
915 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
916 } catch (final UnsupportedEncodingException e) {
917 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
925 return builder.toString();
928 private static DataSchemaNode childByQName(final Object container, final QName name) {
929 if (container instanceof ChoiceCaseNode) {
930 return childByQName((ChoiceCaseNode) container, name);
931 } else if (container instanceof ChoiceSchemaNode) {
932 return childByQName((ChoiceSchemaNode) container, name);
933 } else if (container instanceof ContainerSchemaNode) {
934 return childByQName((ContainerSchemaNode) container, name);
935 } else if (container instanceof ListSchemaNode) {
936 return childByQName((ListSchemaNode) container, name);
937 } else if (container instanceof DataSchemaNode) {
938 return childByQName((DataSchemaNode) container, name);
939 } else if (container instanceof Module) {
940 return childByQName((Module) container, name);
942 throw new IllegalArgumentException("Unhandled parameter types: "
943 + Arrays.<Object> asList(container, name).toString());
947 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
949 return dataNormalizer.toNormalized(legacy);
950 } catch (final NullPointerException e) {
951 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
955 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
957 return dataNormalizer.toLegacy(instanceIdentifier);
958 } catch (final NullPointerException e) {
959 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
960 } catch (final DataNormalizationException e) {
961 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
965 public boolean isNodeMixin(final YangInstanceIdentifier path) {
966 final DataNormalizationOperation<?> operation;
968 operation = dataNormalizer.getOperation(path);
969 } catch (final DataNormalizationException e) {
970 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
972 return operation.isMixin();
975 public DataNormalizationOperation<?> getRootOperation() {
976 return dataNormalizer.getRootOperation();