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);
157 if (latestModule == null) {
158 throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
161 final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
162 toMountPointIdentifier);
164 if (iiWithSchemaNode == null) {
165 throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
168 return iiWithSchemaNode;
171 private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
172 if (list.isEmpty()) {
176 final String head = list.iterator().next();
177 if (head.isEmpty()) {
181 if (list.isEmpty()) {
185 final String last = list.get(list.size() - 1);
186 if (last.isEmpty()) {
187 list.remove(list.size() - 1);
192 public Module findModuleByName(final String moduleName) {
193 checkPreconditions();
194 Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
195 return globalSchema.findModuleByName(moduleName, null);
198 public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) {
199 Preconditions.checkArgument(moduleName != null && mountPoint != null);
201 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
202 if (mountPointSchema == null) {
206 return mountPointSchema.findModuleByName(moduleName, null);
209 public Module findModuleByNamespace(final URI namespace) {
210 checkPreconditions();
211 Preconditions.checkArgument(namespace != null);
212 return globalSchema.findModuleByNamespaceAndRevision(namespace, null);
215 public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
216 Preconditions.checkArgument(namespace != null && mountPoint != null);
218 final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
219 if (mountPointSchema == null) {
223 return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null);
226 public Module findModuleByNameAndRevision(final QName module) {
227 checkPreconditions();
228 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
230 return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
233 public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
234 checkPreconditions();
235 Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
236 && mountPoint != null);
238 final SchemaContext schemaContext = mountPoint.getSchemaContext();
239 return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
240 module.getRevision());
243 public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) {
244 checkPreconditions();
246 final Iterable<PathArgument> elements = path.getPathArguments();
247 final PathArgument head = elements.iterator().next();
248 final QName startQName = head.getNodeType();
249 final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
250 startQName.getRevision());
251 DataNodeContainer node = initialModule;
252 for (final PathArgument element : elements) {
253 final QName _nodeType = element.getNodeType();
254 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
255 if (potentialNode == null || !ControllerContext.isListOrContainer(potentialNode)) {
258 node = (DataNodeContainer) potentialNode;
264 public String toFullRestconfIdentifier(final YangInstanceIdentifier path, final DOMMountPoint mount) {
265 checkPreconditions();
267 final Iterable<PathArgument> elements = path.getPathArguments();
268 final StringBuilder builder = new StringBuilder();
269 final PathArgument head = elements.iterator().next();
270 final QName startQName = head.getNodeType();
271 final SchemaContext schemaContext;
273 schemaContext = mount.getSchemaContext();
275 schemaContext = globalSchema;
277 final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(),
278 startQName.getRevision());
279 DataNodeContainer node = initialModule;
280 for (final PathArgument element : elements) {
281 if (!(element instanceof AugmentationIdentifier)) {
282 final QName _nodeType = element.getNodeType();
283 final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
284 if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode) &&
285 !(potentialNode instanceof ChoiceSchemaNode)) {
286 builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
287 if (potentialNode instanceof DataNodeContainer) {
288 node = (DataNodeContainer) potentialNode;
294 return builder.toString();
297 public String findModuleNameByNamespace(final URI namespace) {
298 checkPreconditions();
300 final Module module = this.findModuleByNamespace(namespace);
301 return module == null ? null : module.getName();
304 public String findModuleNameByNamespace(final DOMMountPoint mountPoint, final URI namespace) {
305 final Module module = this.findModuleByNamespace(mountPoint, namespace);
306 return module == null ? null : module.getName();
309 public URI findNamespaceByModuleName(final String moduleName) {
310 final Module module = this.findModuleByName(moduleName);
311 return module == null ? null : module.getNamespace();
314 public URI findNamespaceByModuleName(final DOMMountPoint mountPoint, final String moduleName) {
315 final Module module = this.findModuleByName(mountPoint, moduleName);
316 return module == null ? null : module.getNamespace();
319 public Set<Module> getAllModules(final DOMMountPoint mountPoint) {
320 checkPreconditions();
322 final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
323 return schemaContext == null ? null : schemaContext.getModules();
326 public Set<Module> getAllModules() {
327 checkPreconditions();
328 return globalSchema.getModules();
331 private static final CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) {
332 final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
333 return schema == null ? null : schema.getName() + ':' + qname.getLocalName();
336 public CharSequence toRestconfIdentifier(final QName qname, final DOMMountPoint mount) {
337 final SchemaContext schema;
339 schema = mount.getSchemaContext();
341 checkPreconditions();
342 schema = globalSchema;
345 return toRestconfIdentifier(schema, qname);
348 public CharSequence toRestconfIdentifier(final QName qname) {
349 checkPreconditions();
351 return toRestconfIdentifier(globalSchema, qname);
354 public CharSequence toRestconfIdentifier(final DOMMountPoint mountPoint, final QName qname) {
355 if (mountPoint == null) {
359 return toRestconfIdentifier(mountPoint.getSchemaContext(), qname);
362 public Module getRestconfModule() {
363 return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
366 private static final Predicate<GroupingDefinition> ERRORS_GROUPING_FILTER = new Predicate<GroupingDefinition>() {
368 public boolean apply(final GroupingDefinition g) {
369 return Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
373 public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
374 final Module restconfModule = getRestconfModule();
375 if (restconfModule == null) {
379 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
381 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, ERRORS_GROUPING_FILTER);
383 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
385 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
386 Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
387 return Iterables.getFirst(instanceDataChildrenByName, null);
390 private static final Predicate<GroupingDefinition> GROUPING_FILTER = new Predicate<GroupingDefinition>() {
392 public boolean apply(final GroupingDefinition g) {
393 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
397 public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
398 Module restconfModule = inRestconfModule;
399 if (restconfModule == null) {
400 restconfModule = getRestconfModule();
403 if (restconfModule == null) {
407 final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
408 final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings, GROUPING_FILTER);
409 final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
411 final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
412 Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
413 final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
415 if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
416 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
417 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
418 return Iterables.getFirst(instances, null);
419 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
420 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
421 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
422 return Iterables.getFirst(instances, null);
423 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
424 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
425 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
426 final DataSchemaNode modules = Iterables.getFirst(instances, null);
427 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
428 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
429 return Iterables.getFirst(instances, null);
430 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
431 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
432 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
433 return Iterables.getFirst(instances, null);
434 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
435 List<DataSchemaNode> instances = findInstanceDataChildrenByName(
436 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
437 final DataSchemaNode modules = Iterables.getFirst(instances, null);
438 instances = findInstanceDataChildrenByName(((DataNodeContainer) modules),
439 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
440 return Iterables.getFirst(instances, null);
441 } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
442 final List<DataSchemaNode> instances = findInstanceDataChildrenByName(
443 ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
444 return Iterables.getFirst(instances, null);
450 private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) {
451 for (final ChoiceCaseNode caze : container.getCases()) {
452 final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
461 private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
462 return container.getDataChildByName(name);
465 private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
466 return ControllerContext.dataNodeChildByQName(container, name);
469 private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
470 return ControllerContext.dataNodeChildByQName(container, name);
473 private static DataSchemaNode childByQName(final Module container, final QName name) {
474 return ControllerContext.dataNodeChildByQName(container, name);
477 private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
481 private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
482 final DataSchemaNode ret = container.getDataChildByName(name);
484 for (final DataSchemaNode node : container.getChildNodes()) {
485 if ((node instanceof ChoiceSchemaNode)) {
486 final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node);
487 final DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
488 if (childByQName != null) {
497 private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount) throws UnsupportedEncodingException {
498 final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
499 return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
502 private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
503 final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
504 final boolean returnJustMountPoint) {
505 Preconditions.<List<String>> checkNotNull(strings);
507 if (parentNode == null) {
511 if (strings.isEmpty()) {
512 return createContext(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
515 final String head = strings.iterator().next();
516 final String nodeName = toNodeName(head);
517 final String moduleName = ControllerContext.toModuleName(head);
519 DataSchemaNode targetNode = null;
520 if (!Strings.isNullOrEmpty(moduleName)) {
521 if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
522 && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
523 if (mountPoint != null) {
524 throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
525 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
528 if (mountService == null) {
529 throw new RestconfDocumentedException(
530 "MountService was not found. Finding behind mount points does not work.",
531 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
534 final YangInstanceIdentifier partialPath = dataNormalizer.toNormalized(builder.build());
535 final Optional<DOMMountPoint> mountOpt = mountService.getMountPoint(partialPath);
536 if (!mountOpt.isPresent()) {
537 LOG.debug("Instance identifier to missing mount point: {}", partialPath);
538 throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
539 ErrorTag.UNKNOWN_ELEMENT);
541 final DOMMountPoint mount = mountOpt.get();
543 final SchemaContext mountPointSchema = mount.getSchemaContext();
544 if (mountPointSchema == null) {
545 throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
546 ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
549 if (returnJustMountPoint || strings.size() == 1) {
550 final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
551 return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
554 final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
555 if (moduleNameBehindMountPoint == null) {
556 throw new RestconfDocumentedException(
557 "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
558 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
561 final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
562 if (moduleBehindMountPoint == null) {
563 throw new RestconfDocumentedException("\"" + moduleName
564 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
567 final List<String> subList = strings.subList(1, strings.size());
568 return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
569 returnJustMountPoint);
572 Module module = null;
573 if (mountPoint == null) {
574 checkPreconditions();
575 module = globalSchema.findModuleByName(moduleName, null);
576 if (module == null) {
577 throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
578 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
581 final SchemaContext schemaContext = mountPoint.getSchemaContext();
582 if (schemaContext != null) {
583 module = schemaContext.findModuleByName(moduleName, null);
587 if (module == null) {
588 throw new RestconfDocumentedException("\"" + moduleName
589 + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
593 targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
595 if (targetNode == null && parentNode instanceof Module) {
596 final RpcDefinition rpc = ControllerContext.getInstance().getRpcDefinition(head);
598 return new InstanceIdentifierContext<RpcDefinition>(builder.build(), rpc, mountPoint,
599 mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
603 if (targetNode == null) {
604 throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
605 + "\" was not found in parent data node.\n" + " 2. \"" + head
606 + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
607 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
610 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(parentNode, nodeName);
611 if (potentialSchemaNodes.size() > 1) {
612 final StringBuilder strBuilder = new StringBuilder();
613 for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
614 strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
617 throw new RestconfDocumentedException(
618 "URI has bad format. Node \""
620 + "\" is added as augment from more than one module. "
621 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
622 + "\nThe node is added as augment from modules with namespaces:\n"
623 + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
626 if (potentialSchemaNodes.isEmpty()) {
627 throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
628 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
631 targetNode = potentialSchemaNodes.iterator().next();
634 if (!ControllerContext.isListOrContainer(targetNode)) {
635 throw new RestconfDocumentedException("URI has bad format. Node \"" + head
636 + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
640 if ((targetNode instanceof ListSchemaNode)) {
641 final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
642 final int keysSize = listNode.getKeyDefinition().size();
643 if ((strings.size() - consumed) < keysSize) {
644 throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
645 + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
648 final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
649 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
651 for (final QName key : listNode.getKeyDefinition()) {
653 final String uriKeyValue = uriKeyValues.get(i);
654 if (uriKeyValue.equals(NULL_VALUE)) {
655 throw new RestconfDocumentedException("URI has bad format. List \""
656 + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
657 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
660 addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
665 consumed = consumed + i;
666 builder.nodeWithKey(targetNode.getQName(), keyValues);
668 builder.node(targetNode.getQName());
671 if ((targetNode instanceof DataNodeContainer)) {
672 final List<String> remaining = strings.subList(consumed, strings.size());
673 return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
674 returnJustMountPoint);
677 return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
680 private InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
681 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
683 final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
684 return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
687 public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
688 final URI namespace) {
689 Preconditions.<URI> checkNotNull(namespace);
691 final List<DataSchemaNode> potentialSchemaNodes = findInstanceDataChildrenByName(container, name);
693 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
695 public boolean apply(final DataSchemaNode node) {
696 return Objects.equal(node.getQName().getNamespace(), namespace);
700 final Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
701 return Iterables.getFirst(result, null);
704 public static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
705 Preconditions.<DataNodeContainer> checkNotNull(container);
706 Preconditions.<String> checkNotNull(name);
708 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
709 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
710 return instantiatedDataNodeContainers;
713 private static final Function<ChoiceSchemaNode, Set<ChoiceCaseNode>> CHOICE_FUNCTION = new Function<ChoiceSchemaNode, Set<ChoiceCaseNode>>() {
715 public Set<ChoiceCaseNode> apply(final ChoiceSchemaNode node) {
716 return node.getCases();
720 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
721 final DataNodeContainer container, final String name) {
723 final Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
725 public boolean apply(final DataSchemaNode node) {
726 return Objects.equal(node.getQName().getLocalName(), name);
730 final Iterable<DataSchemaNode> nodes = Iterables.filter(container.getChildNodes(), filter);
732 // Can't combine this loop with the filter above because the filter is
733 // lazily-applied by Iterables.filter.
734 for (final DataSchemaNode potentialNode : nodes) {
735 if (isInstantiatedDataSchema(potentialNode)) {
736 potentialSchemaNodes.add(potentialNode);
740 final Iterable<ChoiceSchemaNode> choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
741 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, CHOICE_FUNCTION);
743 final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
744 for (final ChoiceCaseNode caze : allCases) {
745 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
749 public static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
750 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
751 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
752 || node instanceof AnyXmlSchemaNode;
755 private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
756 final DOMMountPoint mountPoint) {
757 Preconditions.<String> checkNotNull(uriValue);
758 Preconditions.checkArgument((node instanceof LeafSchemaNode));
760 final String urlDecoded = urlPathArgDecode(uriValue);
761 final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
762 final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
764 Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
765 String additionalInfo = "";
766 if (decoded == null) {
767 final TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
768 if ((baseType instanceof IdentityrefTypeDefinition)) {
769 decoded = toQName(urlDecoded);
770 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
774 if (decoded == null) {
775 throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
776 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
779 map.put(node.getQName(), decoded);
782 private static String toModuleName(final String str) {
783 final int idx = str.indexOf(':');
788 // Make sure there is only one occurrence
789 if (str.indexOf(':', idx + 1) != -1) {
793 return str.substring(0, idx);
796 private static String toNodeName(final String str) {
797 final int idx = str.indexOf(':');
802 // Make sure there is only one occurrence
803 if (str.indexOf(':', idx + 1) != -1) {
807 return str.substring(idx + 1);
810 private QName toQName(final String name) {
811 checkPreconditions();
812 final String module = toModuleName(name);
813 final String node = toNodeName(name);
814 final Module m = globalSchema.findModuleByName(module, null);
815 return m == null ? null : QName.create(m.getQNameModule(), node);
818 private static boolean isListOrContainer(final DataSchemaNode node) {
819 return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
822 public RpcDefinition getRpcDefinition(final String name) {
823 final QName validName = toQName(name);
824 return validName == null ? null : qnameToRpc.get().get(validName);
828 public void onGlobalContextUpdated(final SchemaContext context) {
829 if (context != null) {
830 final Collection<RpcDefinition> defs = context.getOperations();
831 final Map<QName, RpcDefinition> newMap = new HashMap<>(defs.size());
833 for (final RpcDefinition operation : defs) {
834 newMap.put(operation.getQName(), operation);
837 // FIXME: still not completely atomic
838 qnameToRpc.set(ImmutableMap.copyOf(newMap));
839 setGlobalSchema(context);
843 public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
845 final List<String> decodedPathArgs = new ArrayList<String>();
846 for (final String pathArg : strings) {
847 final String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
848 decodedPathArgs.add(_decode);
850 return decodedPathArgs;
851 } catch (final UnsupportedEncodingException e) {
852 throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
853 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
857 public String urlPathArgDecode(final String pathArg) {
858 if (pathArg != null) {
860 return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
861 } catch (final UnsupportedEncodingException e) {
862 throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
863 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
870 private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataSchemaNode node, final DOMMountPoint mount) {
871 if (argument instanceof NodeIdentifier) {
872 return convertToRestconfIdentifier((NodeIdentifier) argument, mount);
873 } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
874 return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node, mount);
875 } else if (argument != null && node != null) {
876 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
878 throw new IllegalArgumentException("Unhandled parameter types: "
879 + Arrays.<Object> asList(argument, node).toString());
883 private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final DOMMountPoint node) {
884 return "/" + this.toRestconfIdentifier(argument.getNodeType(),node);
887 private CharSequence convertToRestconfIdentifierWithPredicates(final NodeIdentifierWithPredicates argument,
888 final ListSchemaNode node, final DOMMountPoint mount) {
889 final QName nodeType = argument.getNodeType();
890 final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType, mount);
891 final Map<QName, Object> keyValues = argument.getKeyValues();
893 final StringBuilder builder = new StringBuilder();
895 builder.append(nodeIdentifier);
898 final List<QName> keyDefinition = node.getKeyDefinition();
899 boolean hasElements = false;
900 for (final QName key : keyDefinition) {
901 for (final DataSchemaNode listChild : node.getChildNodes()) {
902 if (listChild.getQName().equals(key)) {
910 Preconditions.checkState(listChild instanceof LeafSchemaNode, "List key has to consist of leaves");
911 builder.append(toUriString(keyValues.get(key), (LeafSchemaNode)listChild, mount));
912 } catch (final UnsupportedEncodingException e) {
913 LOG.error("Error parsing URI: {}", keyValues.get(key), e);
921 return builder.toString();
924 private static DataSchemaNode childByQName(final Object container, final QName name) {
925 if (container instanceof ChoiceCaseNode) {
926 return childByQName((ChoiceCaseNode) container, name);
927 } else if (container instanceof ChoiceSchemaNode) {
928 return childByQName((ChoiceSchemaNode) container, name);
929 } else if (container instanceof ContainerSchemaNode) {
930 return childByQName((ContainerSchemaNode) container, name);
931 } else if (container instanceof ListSchemaNode) {
932 return childByQName((ListSchemaNode) container, name);
933 } else if (container instanceof DataSchemaNode) {
934 return childByQName((DataSchemaNode) container, name);
935 } else if (container instanceof Module) {
936 return childByQName((Module) container, name);
938 throw new IllegalArgumentException("Unhandled parameter types: "
939 + Arrays.<Object> asList(container, name).toString());
943 public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
945 return dataNormalizer.toNormalized(legacy);
946 } catch (final NullPointerException e) {
947 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
951 public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
953 return dataNormalizer.toLegacy(instanceIdentifier);
954 } catch (final NullPointerException e) {
955 throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
956 } catch (final DataNormalizationException e) {
957 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
961 public boolean isNodeMixin(final YangInstanceIdentifier path) {
962 final DataNormalizationOperation<?> operation;
964 operation = dataNormalizer.getOperation(path);
965 } catch (final DataNormalizationException e) {
966 throw new RestconfDocumentedException("Data normalizer failed. Normalization isn't possible", e);
968 return operation.isMixin();
971 public DataNormalizationOperation<?> getRootOperation() {
972 return dataNormalizer.getRootOperation();