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.DataNormalizationException;
35 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
36 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
38 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
39 import org.opendaylight.controller.sal.rest.api.Draft02;
40 import org.opendaylight.controller.sal.rest.impl.RestUtil;
41 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
43 import org.opendaylight.yangtools.concepts.Codec;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class ControllerContext implements SchemaContextListener {
73 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
75 private final static ControllerContext INSTANCE = new ControllerContext();
77 private final static String NULL_VALUE = "null";
79 private final static String MOUNT_MODULE = "yang-ext";
81 private final static String MOUNT_NODE = "mount";
83 public final static String MOUNT = "yang-ext:mount";
85 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
87 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
89 private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc =
90 new AtomicReference<>(Collections.<QName, RpcDefinition>emptyMap());
92 private volatile SchemaContext globalSchema;
93 private volatile DOMMountPointService mountService;
95 private DataNormalizer dataNormalizer;
97 public void setGlobalSchema(final SchemaContext globalSchema) {
98 this.globalSchema = globalSchema;
99 dataNormalizer = new DataNormalizer(globalSchema);
102 public void setMountService(final DOMMountPointService mountService) {
103 this.mountService = mountService;
106 private ControllerContext() {
109 public static ControllerContext getInstance() {
110 return ControllerContext.INSTANCE;
113 private void checkPreconditions() {
114 if (globalSchema == null) {
115 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
119 public void setSchemas(final SchemaContext schemas) {
120 onGlobalContextUpdated(schemas);
123 public InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
124 return toIdentifier(restconfInstance, false);
127 public SchemaContext getGlobalSchema() {
131 public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
132 return toIdentifier(restconfInstance, true);
135 private InstanceIdentifierContext toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
136 checkPreconditions();
138 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
139 omitFirstAndLastEmptyString(pathArgs);
140 if (pathArgs.isEmpty()) {
144 final String first = pathArgs.iterator().next();
145 final String startModule = ControllerContext.toModuleName(first);
146 if (startModule == null) {
147 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
148 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
151 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
152 final Module latestModule = globalSchema.findModuleByName(startModule, null);
153 final InstanceIdentifierContext iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
154 toMountPointIdentifier);
156 if (iiWithSchemaNode == null) {
157 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
160 return iiWithSchemaNode;
163 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
164 if (list.isEmpty()) {
168 final String head = list.iterator().next();
169 if (head.isEmpty()) {
173 if (list.isEmpty()) {
177 final String last = list.get(list.size() - 1);
178 if (last.isEmpty()) {
179 list.remove(list.size() - 1);
184 public Module findModuleByName(final String moduleName) {
185 checkPreconditions();
186 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
187 return globalSchema.findModuleByName(moduleName, null);
190 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
191 Preconditions.checkArgument(moduleName != null && mountPoint != null);
193 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
194 if (mountPointSchema == null) {
198 return mountPointSchema.findModuleByName(moduleName, null);
201 public Module findModuleByNamespace(final URI namespace) {
202 checkPreconditions();
203 Preconditions.checkArgument(namespace != null);
204 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
207 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
208 Preconditions.checkArgument(namespace != null && mountPoint != null);
210 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
211 if (mountPointSchema == null) {
215 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
218 public Module findModuleByNameAndRevision(final QName module) {
219 checkPreconditions();
220 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
222 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
225 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
226 checkPreconditions();
227 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
228 && mountPoint != null);
230 final SchemaContext schemaContext = mountPoint.getSchemaContext();
231 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
232 module.getRevision());
235 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
236 checkPreconditions();
238 final Iterable<PathArgument> elements = path.getPathArguments();
239 final PathArgument head = elements.iterator().next();
240 final QName startQName = head.getNodeType();
241 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
242 startQName.getRevision());
243 DataNodeContainer node = initialModule;
244 for (final PathArgument element : elements) {
245 final QName _nodeType = element.getNodeType();
246 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
247 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
250 node = (DataNodeContainer) potentialNode;
256 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
257 checkPreconditions();
259 final Iterable<PathArgument> elements = path.getPathArguments();
260 final StringBuilder builder = new StringBuilder();
261 final PathArgument head = elements.iterator().next();
262 final QName startQName = head.getNodeType();
263 final SchemaContext schemaContext;
265 schemaContext = mount.getSchemaContext();
267 schemaContext = globalSchema;
269 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
270 startQName.getRevision());
271 DataNodeContainer node = initialModule;
272 for (final PathArgument element : elements) {
273 if (!(element instanceof AugmentationIdentifier)) {
274 final QName _nodeType = element.getNodeType();
275 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
276 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)) {
277 if (!ControllerContext.isListOrContainer(potentialNode)) {
280 builder.append(convertToRestconfIdentifier(element, (DataNodeContainer) potentialNode, mount));
281 node = (DataNodeContainer) potentialNode;
286 return builder.toString();
289 public String findModuleNameByNamespace(final URI namespace) {
290 checkPreconditions();
292 final Module module = this.findModuleByNamespace(namespace);
293 return module == null ? null : module.getName();
296 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
297 final Module module = this.findModuleByNamespace(mountPoint, namespace);
298 return module == null ? null : module.getName();
301 public URI findNamespaceByModuleName(final String moduleName) {
302 final Module module = this.findModuleByName(moduleName);
303 return module == null ? null : module.getNamespace();
306 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
307 final Module module = this.findModuleByName(mountPoint, moduleName);
308 return module == null ? null : module.getNamespace();
311 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
312 checkPreconditions();
314 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
315 return schemaContext == null ? null : schemaContext.getModules();
318 public Set<Module> getAllModules() {
319 checkPreconditions();
320 return globalSchema.getModules();
323 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
324 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
325 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
328 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
329 final SchemaContext schema;
331 schema = mount.getSchemaContext();
333 checkPreconditions();
334 schema = globalSchema;
337 return toRestconfIdentifier(schema, qname);
340 public CharSequence toRestconfIdentifier(final QName qname) {
341 checkPreconditions();
343 return toRestconfIdentifier(globalSchema, qname);
346 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
347 if (mountPoint == null) {
351 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
354 public Module getRestconfModule() {
355 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
358 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
360 public boolean apply(final GroupingDefinition g) {
361 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
365 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
366 final Module restconfModule = getRestconfModule();
367 if (restconfModule == null) {
371 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
373 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
375 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
377 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
378 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
379 return Iterables.getFirst(instanceDataChildrenByName, null);
382 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
384 public boolean apply(final GroupingDefinition g) {
385 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
389 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
390 Module restconfModule = inRestconfModule;
391 if (restconfModule == null) {
392 restconfModule = getRestconfModule();
395 if (restconfModule == null) {
399 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
400 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
401 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
403 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
404 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
405 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
407 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
408 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
409 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
410 return Iterables.getFirst(instances, null);
411 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
412 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
413 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
414 return Iterables.getFirst(instances, null);
415 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
416 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
417 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
418 final DataSchemaNode modules = Iterables.getFirst(instances, null);
419 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
420 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
421 return Iterables.getFirst(instances, null);
422 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
423 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
424 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
425 return Iterables.getFirst(instances, null);
426 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
427 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
428 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
429 final DataSchemaNode modules = Iterables.getFirst(instances, null);
430 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
431 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
432 return Iterables.getFirst(instances, null);
433 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
434 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
435 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
436 return Iterables.getFirst(instances, null);
442 private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
443 for (final ChoiceCaseNode caze : container.getCases()) {
444 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
453 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
454 return container.getDataChildByName(name);
457 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
458 return ControllerContext.dataNodeChildByQName(container, name);
461 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
462 return ControllerContext.dataNodeChildByQName(container, name);
465 private static DataSchemaNode childByQName(final Module container, final QName name) {
466 return ControllerContext.dataNodeChildByQName(container, name);
469 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
473 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
474 final DataSchemaNode ret = container.getDataChildByName(name);
476 for (final DataSchemaNode node : container.getChildNodes()) {
477 if ((node instanceof ChoiceNode)) {
478 final ChoiceNode choiceNode = ((ChoiceNode) node);
479 final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
480 if (childByQName != null) {
489 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
490 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
491 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
494 private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
495 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
496 final boolean returnJustMountPoint) {
497 Preconditions.<List<String>> checkNotNull(strings);
499 if (parentNode == null) {
503 if (strings.isEmpty()) {
504 return createContext(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
507 final String head = strings.iterator().next();
508 final String nodeName = toNodeName(head);
509 final String moduleName = ControllerContext.toModuleName(head);
511 DataSchemaNode targetNode = null;
512 if (!Strings.isNullOrEmpty(moduleName)) {
513 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
514 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
515 if (mountPoint != null) {
516 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
517 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
520 if (mountService == null) {
521 throw new RestconfDocumentedException(
522 "MountService was not found. Finding behind mount points does not work.",
523 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
526 final YangInstanceIdentifier partialPath = builder.toInstance();
527 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
528 if (!mountOpt.isPresent()) {
529 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
530 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
531 ErrorTag.UNKNOWN_ELEMENT);
533 final DOMMountPoint mount = mountOpt.get();
535 final SchemaContext mountPointSchema = mount.getSchemaContext();
536 if (mountPointSchema == null) {
537 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
538 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
541 if (returnJustMountPoint) {
542 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
543 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
546 if (strings.size() == 1) {
547 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
548 return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
551 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
552 if (moduleNameBehindMountPoint == null) {
553 throw new RestconfDocumentedException(
554 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
555 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
558 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
559 if (moduleBehindMountPoint == null) {
560 throw new RestconfDocumentedException("\"" + moduleName
561 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
564 final List<String> subList = strings.subList(1, strings.size());
565 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
566 returnJustMountPoint);
569 Module module = null;
570 if (mountPoint == null) {
571 checkPreconditions();
572 module = globalSchema.findModuleByName(moduleName, null);
573 if (module == null) {
574 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
575 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
578 final SchemaContext schemaContext = mountPoint.getSchemaContext();
579 if (schemaContext != null) {
580 module = schemaContext.findModuleByName(moduleName, null);
584 if (module == null) {
585 throw new RestconfDocumentedException("\"" + moduleName
586 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
590 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
592 if (targetNode == null && parentNode instanceof Module) {
593 final RpcDefinition rpc = ControllerContext.getInstance().getRpcDefinition(head);
595 return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
596 mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
600 if (targetNode == null) {
601 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
602 + "\" was not found in parent data node.\n" + " 2. \"" + head
603 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
604 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
607 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
608 if (potentialSchemaNodes.size() > 1) {
609 final StringBuilder strBuilder = new StringBuilder();
610 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
611 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
614 throw new RestconfDocumentedException(
615 "URI has bad format. Node \""
617 + "\" is added as augment from more than one module. "
618 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
619 + "\nThe node is added as augment from modules with namespaces:\n"
620 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
623 if (potentialSchemaNodes.isEmpty()) {
624 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
625 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
628 targetNode = potentialSchemaNodes.iterator().next();
631 if (!ControllerContext.isListOrContainer(targetNode)) {
632 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
633 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
637 if ((targetNode instanceof ListSchemaNode)) {
638 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
639 final int keysSize = listNode.getKeyDefinition().size();
640 if ((strings.size() - consumed) < keysSize) {
641 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
642 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
645 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
646 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
648 for (final QName key : listNode.getKeyDefinition()) {
650 final String uriKeyValue = uriKeyValues.get(i);
651 if (uriKeyValue.equals(NULL_VALUE)) {
652 throw new RestconfDocumentedException("URI has bad format. List \""
653 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
654 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
657 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
662 consumed = consumed + i;
663 builder.nodeWithKey(targetNode.getQName(), keyValues);
665 builder.node(targetNode.getQName());
668 if ((targetNode instanceof DataNodeContainer)) {
669 final List<String> remaining = strings.subList(consumed, strings.size());
670 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
671 returnJustMountPoint);
674 return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
677 private InstanceIdentifierContext createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
678 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
680 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
681 return new InstanceIdentifierContext(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
684 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
685 final URI namespace) {
686 Preconditions.<URI> checkNotNull(namespace);
688 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
690 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
692 public boolean apply(final DataSchemaNode node) {
693 return Objects.equal(node.getQName().getNamespace(), namespace);
697 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
698 return Iterables.getFirst(result, null);
701 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
702 Preconditions.<DataNodeContainer> checkNotNull(container);
703 Preconditions.<String> checkNotNull(name);
705 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
706 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
707 return instantiatedDataNodeContainers;
710 private static final Function<ChoiceNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
712 public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
713 return node.getCases();
717 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
718 final DataNodeContainer container, final String name) {
720 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
722 public boolean apply(final DataSchemaNode node) {
723 return Objects.equal(node.getQName().getLocalName(), name);
727 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
729 // Can't combine this loop with the filter above because the filter is
730 // lazily-applied by Iterables.filter.
731 for (final DataSchemaNode potentialNode : nodes) {
732 if (isInstantiatedDataSchema(potentialNode)) {
733 potentialSchemaNodes.add(potentialNode);
737 final Iterable<ChoiceNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceNode.class);
738 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
740 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
741 for (final ChoiceCaseNode caze : allCases) {
742 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
746 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
747 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
748 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
749 || node instanceof AnyXmlSchemaNode;
752 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
753 final DOMMountPoint mountPoint) {
754 Preconditions.<String> checkNotNull(uriValue);
755 Preconditions.checkArgument((node instanceof LeafSchemaNode));
757 final String urlDecoded = urlPathArgDecode(uriValue);
758 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
759 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
761 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
762 String additionalInfo = "";
763 if (decoded == null) {
764 final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
765 if ((baseType instanceof IdentityrefTypeDefinition)) {
766 decoded = toQName(urlDecoded);
767 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
771 if (decoded == null) {
772 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
773 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
776 map.put(node.getQName(), decoded);
779 private static String toModuleName(final String str) {
780 final int idx = str.indexOf(':');
785 // Make sure there is only one occurrence
786 if (str.indexOf(':', idx + 1) != -1) {
790 return str.substring(0, idx);
793 private static String toNodeName(final String str) {
794 final int idx = str.indexOf(':');
799 // Make sure there is only one occurrence
800 if (str.indexOf(':', idx + 1) != -1) {
804 return str.substring(idx + 1);
807 private QName toQName(final String name) {
808 checkPreconditions();
809 final String module = toModuleName(name);
810 final String node = toNodeName(name);
811 final Module m = globalSchema.findModuleByName(module, null);
812 return m == null ? null : QName.create(m.getQNameModule(), node);
815 private static boolean isListOrContainer(final DataSchemaNode node) {
816 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
819 public RpcDefinition getRpcDefinition(final String name) {
820 final QName validName = toQName(name);
821 return validName == null ? null : qnameToRpc.get().get(validName);
825 public void onGlobalContextUpdated(final SchemaContext context) {
826 if (context != null) {
827 final Collection<RpcDefinition> defs = context.getOperations();
828 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
830 for (final RpcDefinition operation : defs) {
831 newMap.put(operation.getQName(), operation);
834 // FIXME: still not completely atomic
835 qnameToRpc.set(ImmutableMap.copyOf(newMap));
836 setGlobalSchema(context);
840 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
842 final List<String> decodedPathArgs = new ArrayList<String>();
843 for (final String pathArg : strings) {
844 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
845 decodedPathArgs.add(_decode);
847 return decodedPathArgs;
848 } catch (final UnsupportedEncodingException e) {
849 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
850 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
854 public String urlPathArgDecode(final String pathArg) {
855 if (pathArg != null) {
857 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
858 } catch (final UnsupportedEncodingException e) {
859 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
860 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
867 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node, final DOMMountPoint mount) {
868 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
869 return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
870 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
871 return convertToRestconfIdentifier(argument, node, mount);
872 } else if (argument != null && node != null) {
873 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
875 throw new IllegalArgumentException("Unhandled parameter types: "
876 + Arrays.<Object> asList(argument, node).toString());
880 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
881 return "/" + this.toRestconfIdentifier(argument.getNodeType());
884 private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
885 final ListSchemaNode node, final DOMMountPoint mount) {
886 final QName nodeType = argument.getNodeType();
887 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
888 final Map<QName, Object> keyValues = argument.getKeyValues();
890 final StringBuilder builder = new StringBuilder();
892 builder.append(nodeIdentifier);
895 final List<QName> keyDefinition = node.getKeyDefinition();
896 boolean hasElements = false;
897 for (final QName key : keyDefinition) {
898 for (final DataSchemaNode listChild : node.getChildNodes()) {
899 if (listChild.getQName().equals(key)) {
907 Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
908 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
909 } catch (final UnsupportedEncodingException e) {
910 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
918 return builder.toString();
921 private static DataSchemaNode childByQName(final Object container, final QName name) {
922 if (container instanceof ChoiceCaseNode) {
923 return childByQName((ChoiceCaseNode) container, name);
924 } else if (container instanceof ChoiceNode) {
925 return childByQName((ChoiceNode) container, name);
926 } else if (container instanceof ContainerSchemaNode) {
927 return childByQName((ContainerSchemaNode) container, name);
928 } else if (container instanceof ListSchemaNode) {
929 return childByQName((ListSchemaNode) container, name);
930 } else if (container instanceof DataSchemaNode) {
931 return childByQName((DataSchemaNode) container, name);
932 } else if (container instanceof Module) {
933 return childByQName((Module) container, name);
935 throw new IllegalArgumentException("Unhandled parameter types: "
936 + Arrays.<Object> asList(container, name).toString());
940 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
941 final CompositeNode compositeNode) {
943 return dataNormalizer.toNormalized(legacy, compositeNode);
944 } catch (final NullPointerException e) {
945 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
949 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
951 return dataNormalizer.toNormalized(legacy);
952 } catch (final NullPointerException e) {
953 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
957 public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
958 final NormalizedNode<?,?> normalizedNode) {
960 return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
961 } catch (final NullPointerException e) {
962 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
966 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
968 return dataNormalizer.toLegacy(instanceIdentifier);
969 } catch (NullPointerException e) {
970 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
971 } catch (DataNormalizationException e) {
972 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
976 public boolean isNodeMixin(YangInstanceIdentifier path) {
977 final DataNormalizationOperation<?> operation;
979 operation = dataNormalizer.getOperation(path);
980 } catch (DataNormalizationException e) {
981 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
983 return operation.isMixin();
986 public DataNormalizationOperation<?> getRootOperation() {
987 return dataNormalizer.getRootOperation();