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;
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.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.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.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class ControllerContext implements SchemaContextListener {
70 private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
72 private final static ControllerContext INSTANCE = new ControllerContext();
74 private final static String NULL_VALUE = "null";
76 private final static String MOUNT_MODULE = "yang-ext";
78 private final static String MOUNT_NODE = "mount";
80 public final static String MOUNT = "yang-ext:mount";
82 private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
84 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
86 private static final YangInstanceIdentifier ROOT = YangInstanceIdentifier.builder().build();
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 if(restconfInstance == null) {
138 return new InstanceIdentifierContext<>(ROOT, globalSchema, null, globalSchema);
141 final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
142 omitFirstAndLastEmptyString(pathArgs);
143 if (pathArgs.isEmpty()) {
147 final String first = pathArgs.iterator().next();
148 final String startModule = ControllerContext.toModuleName(first);
149 if (startModule == null) {
150 throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
151 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
154 final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
155 final Module latestModule = globalSchema.findModuleByName(startModule, null);
156 final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
157 toMountPointIdentifier);
159 if (iiWithSchemaNode == null) {
160 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
163 return iiWithSchemaNode;
166 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
167 if (list.isEmpty()) {
171 final String head = list.iterator().next();
172 if (head.isEmpty()) {
176 if (list.isEmpty()) {
180 final String last = list.get(list.size() - 1);
181 if (last.isEmpty()) {
182 list.remove(list.size() - 1);
187 public Module findModuleByName(final String moduleName) {
188 checkPreconditions();
189 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
190 return globalSchema.findModuleByName(moduleName, null);
193 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
194 Preconditions.checkArgument(moduleName != null && mountPoint != null);
196 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
197 if (mountPointSchema == null) {
201 return mountPointSchema.findModuleByName(moduleName, null);
204 public Module findModuleByNamespace(final URI namespace) {
205 checkPreconditions();
206 Preconditions.checkArgument(namespace != null);
207 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
210 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
211 Preconditions.checkArgument(namespace != null && mountPoint != null);
213 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
214 if (mountPointSchema == null) {
218 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
221 public Module findModuleByNameAndRevision(final QName module) {
222 checkPreconditions();
223 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
225 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
228 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
229 checkPreconditions();
230 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
231 && mountPoint != null);
233 final SchemaContext schemaContext = mountPoint.getSchemaContext();
234 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
235 module.getRevision());
238 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
239 checkPreconditions();
241 final Iterable<PathArgument> elements = path.getPathArguments();
242 final PathArgument head = elements.iterator().next();
243 final QName startQName = head.getNodeType();
244 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
245 startQName.getRevision());
246 DataNodeContainer node = initialModule;
247 for (final PathArgument element : elements) {
248 final QName _nodeType = element.getNodeType();
249 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
250 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
253 node = (DataNodeContainer) potentialNode;
259 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
260 checkPreconditions();
262 final Iterable<PathArgument> elements = path.getPathArguments();
263 final StringBuilder builder = new StringBuilder();
264 final PathArgument head = elements.iterator().next();
265 final QName startQName = head.getNodeType();
266 final SchemaContext schemaContext;
268 schemaContext = mount.getSchemaContext();
270 schemaContext = globalSchema;
272 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
273 startQName.getRevision());
274 DataNodeContainer node = initialModule;
275 for (final PathArgument element : elements) {
276 if (!(element instanceof AugmentationIdentifier)) {
277 final QName _nodeType = element.getNodeType();
278 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
279 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode)) {
280 if (!ControllerContext.isListOrContainer(potentialNode)) {
283 builder.append(convertToRestconfIdentifier(element, (DataNodeContainer) potentialNode, mount));
284 node = (DataNodeContainer) potentialNode;
289 return builder.toString();
292 public String findModuleNameByNamespace(final URI namespace) {
293 checkPreconditions();
295 final Module module = this.findModuleByNamespace(namespace);
296 return module == null ? null : module.getName();
299 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
300 final Module module = this.findModuleByNamespace(mountPoint, namespace);
301 return module == null ? null : module.getName();
304 public URI findNamespaceByModuleName(final String moduleName) {
305 final Module module = this.findModuleByName(moduleName);
306 return module == null ? null : module.getNamespace();
309 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
310 final Module module = this.findModuleByName(mountPoint, moduleName);
311 return module == null ? null : module.getNamespace();
314 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
315 checkPreconditions();
317 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
318 return schemaContext == null ? null : schemaContext.getModules();
321 public Set<Module> getAllModules() {
322 checkPreconditions();
323 return globalSchema.getModules();
326 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
327 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
328 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
331 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
332 final SchemaContext schema;
334 schema = mount.getSchemaContext();
336 checkPreconditions();
337 schema = globalSchema;
340 return toRestconfIdentifier(schema, qname);
343 public CharSequence toRestconfIdentifier(final QName qname) {
344 checkPreconditions();
346 return toRestconfIdentifier(globalSchema, qname);
349 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
350 if (mountPoint == null) {
354 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
357 public Module getRestconfModule() {
358 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
361 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
363 public boolean apply(final GroupingDefinition g) {
364 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
368 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
369 final Module restconfModule = getRestconfModule();
370 if (restconfModule == null) {
374 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
376 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
378 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
380 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
381 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
382 return Iterables.getFirst(instanceDataChildrenByName, null);
385 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
387 public boolean apply(final GroupingDefinition g) {
388 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
392 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
393 Module restconfModule = inRestconfModule;
394 if (restconfModule == null) {
395 restconfModule = getRestconfModule();
398 if (restconfModule == null) {
402 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
403 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
404 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
406 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
407 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
408 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
410 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
411 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
412 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
413 return Iterables.getFirst(instances, null);
414 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
415 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
416 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
417 return Iterables.getFirst(instances, null);
418 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
419 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
420 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
421 final DataSchemaNode modules = Iterables.getFirst(instances, null);
422 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
423 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
424 return Iterables.getFirst(instances, null);
425 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
426 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
427 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
428 return Iterables.getFirst(instances, null);
429 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
430 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
431 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
432 final DataSchemaNode modules = Iterables.getFirst(instances, null);
433 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
434 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
435 return Iterables.getFirst(instances, null);
436 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
437 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
438 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
439 return Iterables.getFirst(instances, null);
445 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
446 for (final ChoiceCaseNode caze : container.getCases()) {
447 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
456 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
457 return container.getDataChildByName(name);
460 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
461 return ControllerContext.dataNodeChildByQName(container, name);
464 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
465 return ControllerContext.dataNodeChildByQName(container, name);
468 private static DataSchemaNode childByQName(final Module container, final QName name) {
469 return ControllerContext.dataNodeChildByQName(container, name);
472 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
476 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
477 final DataSchemaNode ret = container.getDataChildByName(name);
479 for (final DataSchemaNode node : container.getChildNodes()) {
480 if ((node instanceof ChoiceSchemaNode)) {
481 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
482 final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
483 if (childByQName != null) {
492 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
493 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
494 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
497 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
498 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
499 final boolean returnJustMountPoint) {
500 Preconditions.<List<String>> checkNotNull(strings);
502 if (parentNode == null) {
506 if (strings.isEmpty()) {
507 return createContext(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
510 final String head = strings.iterator().next();
511 final String nodeName = toNodeName(head);
512 final String moduleName = ControllerContext.toModuleName(head);
514 DataSchemaNode targetNode = null;
515 if (!Strings.isNullOrEmpty(moduleName)) {
516 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
517 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
518 if (mountPoint != null) {
519 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
520 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
523 if (mountService == null) {
524 throw new RestconfDocumentedException(
525 "MountService was not found. Finding behind mount points does not work.",
526 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
529 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
530 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
531 if (!mountOpt.isPresent()) {
532 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
533 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
534 ErrorTag.UNKNOWN_ELEMENT);
536 final DOMMountPoint mount = mountOpt.get();
538 final SchemaContext mountPointSchema = mount.getSchemaContext();
539 if (mountPointSchema == null) {
540 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
541 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
544 if (returnJustMountPoint || strings.size() == 1) {
545 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
546 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
549 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
550 if (moduleNameBehindMountPoint == null) {
551 throw new RestconfDocumentedException(
552 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
553 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
556 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
557 if (moduleBehindMountPoint == null) {
558 throw new RestconfDocumentedException("\"" + moduleName
559 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
562 final List<String> subList = strings.subList(1, strings.size());
563 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
564 returnJustMountPoint);
567 Module module = null;
568 if (mountPoint == null) {
569 checkPreconditions();
570 module = globalSchema.findModuleByName(moduleName, null);
571 if (module == null) {
572 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
573 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
576 final SchemaContext schemaContext = mountPoint.getSchemaContext();
577 if (schemaContext != null) {
578 module = schemaContext.findModuleByName(moduleName, null);
582 if (module == null) {
583 throw new RestconfDocumentedException("\"" + moduleName
584 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
588 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
590 if (targetNode == null && parentNode instanceof Module) {
591 final RpcDefinition rpc = ControllerContext.getInstance().getRpcDefinition(head);
593 return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
594 mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
598 if (targetNode == null) {
599 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
600 + "\" was not found in parent data node.\n" + " 2. \"" + head
601 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
602 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
605 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
606 if (potentialSchemaNodes.size() > 1) {
607 final StringBuilder strBuilder = new StringBuilder();
608 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
609 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
612 throw new RestconfDocumentedException(
613 "URI has bad format. Node \""
615 + "\" is added as augment from more than one module. "
616 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
617 + "\nThe node is added as augment from modules with namespaces:\n"
618 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
621 if (potentialSchemaNodes.isEmpty()) {
622 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
623 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
626 targetNode = potentialSchemaNodes.iterator().next();
629 if (!ControllerContext.isListOrContainer(targetNode)) {
630 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
631 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
635 if ((targetNode instanceof ListSchemaNode)) {
636 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
637 final int keysSize = listNode.getKeyDefinition().size();
638 if ((strings.size() - consumed) < keysSize) {
639 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
640 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
643 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
644 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
646 for (final QName key : listNode.getKeyDefinition()) {
648 final String uriKeyValue = uriKeyValues.get(i);
649 if (uriKeyValue.equals(NULL_VALUE)) {
650 throw new RestconfDocumentedException("URI has bad format. List \""
651 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
652 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
655 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
660 consumed = consumed + i;
661 builder.nodeWithKey(targetNode.getQName(), keyValues);
663 builder.node(targetNode.getQName());
666 if ((targetNode instanceof DataNodeContainer)) {
667 final List<String> remaining = strings.subList(consumed, strings.size());
668 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
669 returnJustMountPoint);
672 return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
675 private InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
676 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
678 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
679 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
682 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
683 final URI namespace) {
684 Preconditions.<URI> checkNotNull(namespace);
686 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
688 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
690 public boolean apply(final DataSchemaNode node) {
691 return Objects.equal(node.getQName().getNamespace(), namespace);
695 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
696 return Iterables.getFirst(result, null);
699 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
700 Preconditions.<DataNodeContainer> checkNotNull(container);
701 Preconditions.<String> checkNotNull(name);
703 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
704 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
705 return instantiatedDataNodeContainers;
708 private static final Function<ChoiceSchemaNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceSchemaNode, Set<ChoiceCaseNode>>() {
710 public Set<ChoiceCaseNode> apply(final ChoiceSchemaNode node) {
711 return node.getCases();
715 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
716 final DataNodeContainer container, final String name) {
718 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
720 public boolean apply(final DataSchemaNode node) {
721 return Objects.equal(node.getQName().getLocalName(), name);
725 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
727 // Can't combine this loop with the filter above because the filter is
728 // lazily-applied by Iterables.filter.
729 for (final DataSchemaNode potentialNode : nodes) {
730 if (isInstantiatedDataSchema(potentialNode)) {
731 potentialSchemaNodes.add(potentialNode);
735 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
736 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
738 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
739 for (final ChoiceCaseNode caze : allCases) {
740 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
744 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
745 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
746 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
747 || node instanceof AnyXmlSchemaNode;
750 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
751 final DOMMountPoint mountPoint) {
752 Preconditions.<String> checkNotNull(uriValue);
753 Preconditions.checkArgument((node instanceof LeafSchemaNode));
755 final String urlDecoded = urlPathArgDecode(uriValue);
756 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
757 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
759 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
760 String additionalInfo = "";
761 if (decoded == null) {
762 final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
763 if ((baseType instanceof IdentityrefTypeDefinition)) {
764 decoded = toQName(urlDecoded);
765 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
769 if (decoded == null) {
770 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
771 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
774 map.put(node.getQName(), decoded);
777 private static String toModuleName(final String str) {
778 final int idx = str.indexOf(':');
783 // Make sure there is only one occurrence
784 if (str.indexOf(':', idx + 1) != -1) {
788 return str.substring(0, idx);
791 private static String toNodeName(final String str) {
792 final int idx = str.indexOf(':');
797 // Make sure there is only one occurrence
798 if (str.indexOf(':', idx + 1) != -1) {
802 return str.substring(idx + 1);
805 private QName toQName(final String name) {
806 checkPreconditions();
807 final String module = toModuleName(name);
808 final String node = toNodeName(name);
809 final Module m = globalSchema.findModuleByName(module, null);
810 return m == null ? null : QName.create(m.getQNameModule(), node);
813 private static boolean isListOrContainer(final DataSchemaNode node) {
814 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
817 public RpcDefinition getRpcDefinition(final String name) {
818 final QName validName = toQName(name);
819 return validName == null ? null : qnameToRpc.get().get(validName);
823 public void onGlobalContextUpdated(final SchemaContext context) {
824 if (context != null) {
825 final Collection<RpcDefinition> defs = context.getOperations();
826 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
828 for (final RpcDefinition operation : defs) {
829 newMap.put(operation.getQName(), operation);
832 // FIXME: still not completely atomic
833 qnameToRpc.set(ImmutableMap.copyOf(newMap));
834 setGlobalSchema(context);
838 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
840 final List<String> decodedPathArgs = new ArrayList<String>();
841 for (final String pathArg : strings) {
842 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
843 decodedPathArgs.add(_decode);
845 return decodedPathArgs;
846 } catch (final UnsupportedEncodingException e) {
847 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
848 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
852 public String urlPathArgDecode(final String pathArg) {
853 if (pathArg != null) {
855 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
856 } catch (final UnsupportedEncodingException e) {
857 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
858 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
865 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node, final DOMMountPoint mount) {
866 if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
867 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
868 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
869 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node, mount);
870 } else if (argument != null && node != null) {
871 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
873 throw new IllegalArgumentException("Unhandled parameter types: "
874 + Arrays.<Object> asList(argument, node).toString());
878 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
879 return "/" + this.toRestconfIdentifier(argument.getNodeType(),node);
882 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
883 final ListSchemaNode node, final DOMMountPoint mount) {
884 final QName nodeType = argument.getNodeType();
885 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
886 final Map<QName, Object> keyValues = argument.getKeyValues();
888 final StringBuilder builder = new StringBuilder();
890 builder.append(nodeIdentifier);
893 final List<QName> keyDefinition = node.getKeyDefinition();
894 boolean hasElements = false;
895 for (final QName key : keyDefinition) {
896 for (final DataSchemaNode listChild : node.getChildNodes()) {
897 if (listChild.getQName().equals(key)) {
905 Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
906 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
907 } catch (final UnsupportedEncodingException e) {
908 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
916 return builder.toString();
919 private static DataSchemaNode childByQName(final Object container, final QName name) {
920 if (container instanceof ChoiceCaseNode) {
921 return childByQName((ChoiceCaseNode) container, name);
922 } else if (container instanceof ChoiceSchemaNode) {
923 return childByQName((ChoiceSchemaNode) container, name);
924 } else if (container instanceof ContainerSchemaNode) {
925 return childByQName((ContainerSchemaNode) container, name);
926 } else if (container instanceof ListSchemaNode) {
927 return childByQName((ListSchemaNode) container, name);
928 } else if (container instanceof DataSchemaNode) {
929 return childByQName((DataSchemaNode) container, name);
930 } else if (container instanceof Module) {
931 return childByQName((Module) container, name);
933 throw new IllegalArgumentException("Unhandled parameter types: "
934 + Arrays.<Object> asList(container, name).toString());
938 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
940 return dataNormalizer.toNormalized(legacy);
941 } catch (final NullPointerException e) {
942 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
946 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
948 return dataNormalizer.toLegacy(instanceIdentifier);
949 } catch (final NullPointerException e) {
950 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
951 } catch (final DataNormalizationException e) {
952 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
956 public boolean isNodeMixin(final YangInstanceIdentifier path) {
957 final DataNormalizationOperation<?> operation;
959 operation = dataNormalizer.getOperation(path);
960 } catch (final DataNormalizationException e) {
961 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
963 return operation.isMixin();
966 public DataNormalizationOperation<?> getRootOperation() {
967 return dataNormalizer.getRootOperation();