2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2014 Brocade Communication Systems, Inc.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.restconf.impl;
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.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import java.math.BigInteger;
23 import java.net.URISyntaxException;
24 import java.text.ParseException;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.Response.Status;
37 import javax.ws.rs.core.UriBuilder;
38 import javax.ws.rs.core.UriInfo;
39 import org.apache.commons.lang3.StringUtils;
40 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
45 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
46 import org.opendaylight.controller.sal.rest.api.Draft02;
47 import org.opendaylight.controller.sal.rest.api.RestconfService;
48 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
50 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
51 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
52 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
53 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
54 import org.opendaylight.controller.sal.streams.listeners.Notificator;
55 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
56 import org.opendaylight.yangtools.concepts.Codec;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.QNameModule;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
61 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.Node;
63 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
75 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
76 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
77 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
78 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
82 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.util.EmptyType;
98 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
99 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
100 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
101 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
105 public class RestconfImpl implements RestconfService {
107 private enum UriParameters {
108 PRETTY_PRINT("prettyPrint"),
111 private String uriParameterName;
113 UriParameters(final String uriParameterName) {
114 this.uriParameterName = uriParameterName;
118 public String toString() {
119 return uriParameterName;
123 private static class TypeDef {
124 public final TypeDefinition<? extends Object> typedef;
125 public final QName qName;
127 TypeDef(final TypeDefinition<? extends Object> typedef, final QName qName) {
128 this.typedef = typedef;
133 private final static RestconfImpl INSTANCE = new RestconfImpl();
135 private static final int NOTIFICATION_PORT = 8181;
137 private static final int CHAR_NOT_FOUND = -1;
139 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
141 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
143 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
145 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
147 private BrokerFacade broker;
149 private ControllerContext controllerContext;
151 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
153 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
155 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
157 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
159 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
161 private static final String DATASTORE_PARAM_NAME = "datastore";
163 private static final String SCOPE_PARAM_NAME = "scope";
165 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
167 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
169 private static final QName NETCONF_BASE_QNAME;
173 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
174 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
175 } catch (final ParseException e) {
176 throw new RestconfDocumentedException(
177 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
178 ErrorTag.OPERATION_FAILED);
179 } catch (final URISyntaxException e) {
180 throw new RestconfDocumentedException(
181 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
182 ErrorTag.OPERATION_FAILED);
186 public void setBroker(final BrokerFacade broker) {
187 this.broker = broker;
190 public void setControllerContext(final ControllerContext controllerContext) {
191 this.controllerContext = controllerContext;
194 private RestconfImpl() {
197 public static RestconfImpl getInstance() {
202 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
203 final Set<Module> allModules = controllerContext.getAllModules();
204 final MapNode allModuleMap = makeModuleMapNode(allModules);
206 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
208 final Module restconfModule = getRestconfModule();
209 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
210 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
211 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
213 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
214 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
215 moduleContainerBuilder.withChild(allModuleMap);
217 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
218 null, schemaContext), moduleContainerBuilder.build());
222 * Valid only for mount point
225 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
226 Preconditions.checkNotNull(identifier);
227 if ( ! identifier.contains(ControllerContext.MOUNT)) {
228 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
229 + " URI has to end with " + ControllerContext.MOUNT;
230 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
233 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
234 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
235 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
236 final SchemaContext schemaContext = mountPoint.getSchemaContext();
237 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
239 final Module restconfModule = getRestconfModule();
240 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
241 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
242 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
244 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
245 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
246 moduleContainerBuilder.withChild(mountPointModulesMap);
248 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
249 mountPoint, schemaContext), moduleContainerBuilder.build());
253 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
254 Preconditions.checkNotNull(identifier);
255 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
256 Module module = null;
257 DOMMountPoint mountPoint = null;
258 final SchemaContext schemaContext;
259 if (identifier.contains(ControllerContext.MOUNT)) {
260 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
261 mountPoint = mountPointIdentifier.getMountPoint();
262 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
263 schemaContext = mountPoint.getSchemaContext();
265 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
266 schemaContext = controllerContext.getGlobalSchema();
269 if (module == null) {
270 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
271 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
272 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
275 final Module restconfModule = getRestconfModule();
276 final Set<Module> modules = Collections.singleton(module);
277 final MapNode moduleMap = makeModuleMapNode(modules);
279 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
280 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
281 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283 return new NormalizedNodeContext(new InstanceIdentifierContext(null, moduleSchemaNode, mountPoint,
284 schemaContext), moduleMap);
288 public StructuredData getAvailableStreams(final UriInfo uriInfo) {
289 final Set<String> availableStreams = Notificator.getStreamNames();
291 final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
292 final Module restconfModule = getRestconfModule();
293 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
294 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
295 for (final String streamName : availableStreams) {
296 streamsAsData.add(toStreamCompositeNode(streamName, streamSchemaNode));
299 final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
300 Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
301 final QName qName = streamsSchemaNode.getQName();
302 final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
303 return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
307 public StructuredData getOperations(final UriInfo uriInfo) {
308 final Set<Module> allModules = controllerContext.getAllModules();
309 return operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
313 public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
314 Set<Module> modules = null;
315 DOMMountPoint mountPoint = null;
316 if (identifier.contains(ControllerContext.MOUNT)) {
317 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
318 mountPoint = mountPointIdentifier.getMountPoint();
319 modules = controllerContext.getAllModules(mountPoint);
321 throw new RestconfDocumentedException(
322 "URI has bad format. If operations behind mount point should be showed, URI has to end with "
323 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
326 return operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
329 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
330 final DOMMountPoint mountPoint, final boolean prettyPrint) {
331 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
332 final Module restconfModule = getRestconfModule();
333 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
334 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
335 final QName qName = operationsSchemaNode.getQName();
336 final SchemaPath path = operationsSchemaNode.getPath();
337 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
338 Draft02.RestConfModule.NAME, 0, qName, path);
339 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
340 for (final Module module : modules) {
341 final Set<RpcDefinition> rpcs = module.getRpcs();
342 for (final RpcDefinition rpc : rpcs) {
343 final QName rpcQName = rpc.getQName();
344 final SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
346 operationsAsData.add(immutableSimpleNode);
348 final String name = module.getName();
349 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
350 SchemaPath.create(true, QName.create("dummy")));
351 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
352 fakeRpcSchemaNode.setAugmenting(true);
354 final EmptyType instance = EmptyType.getInstance();
355 fakeRpcSchemaNode.setType(instance);
356 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
360 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
361 final ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
362 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
365 private Module getRestconfModule() {
366 final Module restconfModule = controllerContext.getRestconfModule();
367 if (restconfModule == null) {
368 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
369 ErrorTag.OPERATION_NOT_SUPPORTED);
372 return restconfModule;
375 private QName getModuleNameAndRevision(final String identifier) {
376 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
377 String moduleNameAndRevision = "";
378 if (mountIndex >= 0) {
379 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
381 moduleNameAndRevision = identifier;
384 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
385 final Iterable<String> split = splitter.split(moduleNameAndRevision);
386 final List<String> pathArgs = Lists.<String> newArrayList(split);
387 if (pathArgs.size() < 2) {
388 throw new RestconfDocumentedException(
389 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
390 ErrorTag.INVALID_VALUE);
394 final String moduleName = pathArgs.get(0);
395 final String revision = pathArgs.get(1);
396 final Date moduleRevision = REVISION_FORMAT.parse(revision);
397 return QName.create(null, moduleRevision, moduleName);
398 } catch (final ParseException e) {
399 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
400 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
404 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
405 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
406 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
407 ((DataNodeContainer) streamSchemaNode), "name");
408 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
410 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
412 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
413 ((DataNodeContainer) streamSchemaNode), "description");
414 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
415 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
416 "DESCRIPTION_PLACEHOLDER"));
418 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
419 ((DataNodeContainer) streamSchemaNode), "replay-support");
420 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
421 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
422 Boolean.valueOf(true)));
424 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
425 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
426 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
427 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
430 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
431 ((DataNodeContainer) streamSchemaNode), "events");
432 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
433 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
435 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
438 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
439 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
440 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
441 ((DataNodeContainer) moduleSchemaNode), "name");
442 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
443 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
446 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
447 ((DataNodeContainer) moduleSchemaNode), "revision");
448 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
449 final Date _revision = module.getRevision();
450 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
451 REVISION_FORMAT.format(_revision)));
453 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
454 ((DataNodeContainer) moduleSchemaNode), "namespace");
455 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
456 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
457 module.getNamespace().toString()));
459 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
460 ((DataNodeContainer) moduleSchemaNode), "feature");
461 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
462 for (final FeatureDefinition feature : module.getFeatures()) {
463 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
464 feature.getQName().getLocalName()));
467 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
471 public Object getRoot() {
476 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
477 final RpcExecutor rpc = resolveIdentifierInInvokeRpc(identifier);
478 final QName rpcName = rpc.getRpcDefinition().getQName();
479 final URI rpcNamespace = rpcName.getNamespace();
480 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
481 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
482 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
485 validateInput(rpc.getRpcDefinition().getInput(), payload);
487 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
490 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
491 if (inputSchema != null && payload == null) {
492 // expected a non null payload
493 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
494 } else if (inputSchema == null && payload != null) {
495 // did not expect any input
496 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
500 // TODO: Validate "mandatory" and "config" values here??? Or should those be
502 // validate in a more central location inside MD-SAL core.
506 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
507 final boolean prettyPrint) {
508 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
509 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
510 rpc.getQName(), "path"));
511 final Object pathValue = pathNode == null ? null : pathNode.getValue();
513 if (!(pathValue instanceof YangInstanceIdentifier)) {
514 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
515 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
518 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
519 String streamName = null;
520 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
521 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier);
523 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
524 DATASTORE_PARAM_NAME);
525 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
527 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
528 scope = scope == null ? DEFAULT_SCOPE : scope;
530 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
531 + "/scope=" + scope);
534 if (Strings.isNullOrEmpty(streamName)) {
535 throw new RestconfDocumentedException(
536 "Path is empty or contains data node which is not Container or List build-in type.",
537 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
540 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
541 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
542 final List<Node<?>> output = new ArrayList<Node<?>>();
543 output.add(streamNameNode);
545 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
546 null, output, null, null);
548 if (!Notificator.existListenerFor(streamName)) {
549 Notificator.createListener(pathIdentifier, streamName);
552 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
556 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
557 if (StringUtils.isNotBlank(noPayload)) {
558 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
560 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
563 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
564 String identifierEncoded = null;
565 DOMMountPoint mountPoint = null;
566 if (identifier.contains(ControllerContext.MOUNT)) {
567 // mounted RPC call - look up mount instance.
568 final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
569 mountPoint = mountPointId.getMountPoint();
571 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
572 + ControllerContext.MOUNT.length() + 1;
573 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
574 identifierEncoded = remoteRpcName;
576 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
577 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
578 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
579 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
581 identifierEncoded = identifier;
584 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
586 RpcDefinition rpc = null;
587 if (mountPoint == null) {
588 rpc = controllerContext.getRpcDefinition(identifierDecoded);
590 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
594 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
597 if (mountPoint == null) {
598 return new BrokerRpcExecutor(rpc, broker);
600 return new MountPointRpcExecutor(rpc, mountPoint);
605 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
606 final String[] splittedIdentifier = identifierDecoded.split(":");
607 if (splittedIdentifier.length != 2) {
608 throw new RestconfDocumentedException(identifierDecoded
609 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
610 ErrorTag.INVALID_VALUE);
612 for (final Module module : schemaContext.getModules()) {
613 if (module.getName().equals(splittedIdentifier[0])) {
614 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
615 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
616 return rpcDefinition;
624 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
625 if (rpcExecutor == null) {
626 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
629 CompositeNode rpcRequest = null;
630 final RpcDefinition rpc = rpcExecutor.getRpcDefinition();
631 final QName rpcName = rpc.getQName();
633 if (payload == null) {
634 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
636 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
637 final List<Node<?>> input = Collections.<Node<?>> singletonList(value);
638 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
641 final RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
643 checkRpcSuccessAndThrowException(rpcResult);
645 if (rpcResult.getResult() == null) {
649 if (rpc.getOutput() == null) {
650 return null; // no output, nothing to send back.
653 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
656 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
657 if (rpcResult.isSuccessful() == false) {
659 throw new RestconfDocumentedException("The operation was not successful", null,
660 rpcResult.getErrors());
665 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
666 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
667 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
668 NormalizedNode<?, ?> data = null;
669 YangInstanceIdentifier normalizedII;
670 if (mountPoint != null) {
671 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
672 .getInstanceIdentifier());
673 data = broker.readConfigurationData(mountPoint, normalizedII);
675 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
676 data = broker.readConfigurationData(normalizedII);
678 return new NormalizedNodeContext(iiWithData, data);
681 @SuppressWarnings("unchecked")
682 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
687 if (node instanceof CompositeNode) {
688 final ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
690 for (final Node<?> childNode : ((CompositeNode) node).getValue()) {
691 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
695 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
696 } else { // SimpleNode
701 private Integer parseDepthParameter(final UriInfo info) {
702 final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
703 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
708 final Integer depth = Integer.valueOf(param);
710 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
711 "Invalid depth parameter: " + depth, null,
712 "The depth parameter must be an integer > 1 or \"unbounded\""));
716 } catch (final NumberFormatException e) {
717 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
718 "Invalid depth parameter: " + e.getMessage(), null,
719 "The depth parameter must be an integer > 1 or \"unbounded\""));
724 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
725 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
726 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
727 NormalizedNode<?, ?> data = null;
728 YangInstanceIdentifier normalizedII;
729 if (mountPoint != null) {
730 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
731 .getInstanceIdentifier());
732 data = broker.readOperationalData(mountPoint, normalizedII);
734 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
735 data = broker.readOperationalData(normalizedII);
738 return new NormalizedNodeContext(iiWithData, data);
741 private boolean parsePrettyPrintParameter(final UriInfo info) {
742 final String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
743 return Boolean.parseBoolean(param);
747 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
748 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
750 validateInput(iiWithData.getSchemaNode(), payload);
752 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
753 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
754 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
755 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
756 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
757 iiWithData.getSchemaNode());
760 YangInstanceIdentifier normalizedII;
761 if (mountPoint != null) {
762 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
763 iiWithData.getInstanceIdentifier());
765 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
769 * There is a small window where another write transaction could be updating the same data
770 * simultaneously and we get an OptimisticLockFailedException. This error is likely
771 * transient and The WriteTransaction#submit API docs state that a retry will likely
772 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
773 * probably will never succeed so we'll fail in that case.
775 * By retrying we're attempting to hide the internal implementation of the data store and
776 * how it handles concurrent updates from the restconf client. The client has instructed us
777 * to put the data and we should make every effort to do so without pushing optimistic lock
778 * failures back to the client and forcing them to handle it via retry (and having to
779 * document the behavior).
784 if (mountPoint != null) {
785 broker.commitConfigurationDataPut(mountPoint, normalizedII,
786 datastoreNormalizedNode).checkedGet();
788 broker.commitConfigurationDataPut(normalizedII,
789 datastoreNormalizedNode).checkedGet();
793 } catch (final TransactionCommitFailedException e) {
794 if(e instanceof OptimisticLockFailedException) {
796 LOG.debug("Got OptimisticLockFailedException on last try - failing");
797 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
800 LOG.debug("Got OptimisticLockFailedException - trying again");
802 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
807 return Response.status(Status.OK).build();
810 private void validateTopLevelNodeName(final Node<?> node,
811 final YangInstanceIdentifier identifier) {
812 final String payloadName = getName(node);
813 final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
816 if (!pathArguments.hasNext()) {
818 if (!node.getNodeType().equals(NETCONF_BASE_QNAME)) {
819 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
820 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
824 final String identifierName = pathArguments.next().getNodeType().getLocalName();
825 if (!payloadName.equals(identifierName)) {
826 throw new RestconfDocumentedException("Payload name (" + payloadName
827 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
828 ErrorTag.MALFORMED_MESSAGE);
834 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
836 * @throws RestconfDocumentedException
837 * if key values or key count in payload and URI isn't equal
840 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
841 final CompositeNode payload) {
842 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
843 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
844 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
845 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
846 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
848 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
853 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
854 final List<QName> keyDefinitions) {
855 for (final QName keyDefinition : keyDefinitions) {
856 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
857 // should be caught during parsing URI to InstanceIdentifier
858 if (uriKeyValue == null) {
859 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
860 ErrorTag.DATA_MISSING);
862 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
863 if (payloadKeyValues.isEmpty()) {
864 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
865 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
868 final Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
869 if (!uriKeyValue.equals(payloadKeyValue)) {
870 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
871 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
872 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
873 ErrorTag.INVALID_VALUE);
879 public Response createConfigurationData(final String identifier, final Node<?> payload) {
880 if (payload == null) {
881 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
884 final URI payloadNS = namespace(payload);
885 if (payloadNS == null) {
886 throw new RestconfDocumentedException(
887 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
888 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
891 InstanceIdentifierContext iiWithData = null;
892 CompositeNode value = null;
893 if (representsMountPointRootData(payload)) {
894 // payload represents mount point data and URI represents path to the mount point
896 if (endsWithMountPoint(identifier)) {
897 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
898 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
899 ErrorTag.INVALID_VALUE);
902 final String completeIdentifier = addMountPointIdentifier(identifier);
903 iiWithData = controllerContext.toInstanceIdentifier(completeIdentifier);
905 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
907 final InstanceIdentifierContext incompleteInstIdWithData = controllerContext
908 .toInstanceIdentifier(identifier);
909 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
910 final DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
911 final Module module = findModule(mountPoint, payload);
913 final String payloadName = getName(payload);
914 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
915 parentSchema, payloadName, module.getNamespace());
916 value = this.normalizeNode(payload, schemaNode, mountPoint);
918 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
921 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
922 iiWithData.getSchemaNode());
923 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
924 YangInstanceIdentifier normalizedII;
927 if (mountPoint != null) {
928 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
929 .getInstanceIdentifier());
930 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
932 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
933 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
935 } catch(final RestconfDocumentedException e) {
937 } catch (final Exception e) {
938 throw new RestconfDocumentedException("Error creating data", e);
941 return Response.status(Status.NO_CONTENT).build();
945 public Response createConfigurationData(final Node<?> payload) {
946 if (payload == null) {
947 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
950 final URI payloadNS = namespace(payload);
951 if (payloadNS == null) {
952 throw new RestconfDocumentedException(
953 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
954 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
957 final Module module = this.findModule(null, payload);
959 final String payloadName = getName(payload);
960 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
961 payloadName, module.getNamespace());
962 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
963 final InstanceIdentifierContext iiWithData = addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
964 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
965 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
966 YangInstanceIdentifier normalizedII;
969 if (mountPoint != null) {
970 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
971 .getInstanceIdentifier());
972 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
975 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
976 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
978 } catch(final RestconfDocumentedException e) {
980 } catch (final Exception e) {
981 throw new RestconfDocumentedException("Error creating data", e);
984 return Response.status(Status.NO_CONTENT).build();
988 public Response deleteConfigurationData(final String identifier) {
989 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
990 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
991 YangInstanceIdentifier normalizedII;
994 if (mountPoint != null) {
995 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
996 .getInstanceIdentifier());
997 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
999 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1000 broker.commitConfigurationDataDelete(normalizedII).get();
1002 } catch (final Exception e) {
1003 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1004 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1005 if (searchedException.isPresent()) {
1006 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
1008 throw new RestconfDocumentedException("Error while deleting data", e);
1010 return Response.status(Status.OK).build();
1014 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1016 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1018 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
1019 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
1023 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1024 final String streamName = Notificator.createStreamNameFromUri(identifier);
1025 if (Strings.isNullOrEmpty(streamName)) {
1026 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1029 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1030 if (listener == null) {
1031 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1034 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1035 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1036 paramToValues.get(DATASTORE_PARAM_NAME));
1037 if (datastore == null) {
1038 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1039 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1041 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1042 if (scope == null) {
1043 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1044 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1047 broker.registerToListenDataChanges(datastore, scope, listener);
1049 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1050 int notificationPort = NOTIFICATION_PORT;
1052 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1053 notificationPort = webSocketServerInstance.getPort();
1054 } catch (final NullPointerException e) {
1055 WebSocketServer.createInstance(NOTIFICATION_PORT);
1057 final UriBuilder port = uriBuilder.port(notificationPort);
1058 final URI uriToWebsocketServer = port.replacePath(streamName).build();
1060 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1064 * Load parameter for subscribing to stream from input composite node
1068 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1070 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1071 final String paramName) {
1072 final QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1073 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1074 final SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1075 if (simpleNode == null) {
1078 final Object rawValue = simpleNode.getValue();
1079 if (!(rawValue instanceof String)) {
1083 return resolveAsEnum(classDescriptor, (String) rawValue);
1087 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1089 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1092 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1093 if (Strings.isNullOrEmpty(value)) {
1096 return resolveAsEnum(classDescriptor, value);
1099 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1100 final T[] enumConstants = classDescriptor.getEnumConstants();
1101 if (enumConstants != null) {
1102 for (final T enm : classDescriptor.getEnumConstants()) {
1103 if (((Enum<?>) enm).name().equals(value)) {
1111 private Map<String, String> resolveValuesFromUri(final String uri) {
1112 final Map<String, String> result = new HashMap<>();
1113 final String[] tokens = uri.split("/");
1114 for (int i = 1; i < tokens.length; i++) {
1115 final String[] parameterTokens = tokens[i].split("=");
1116 if (parameterTokens.length == 2) {
1117 result.put(parameterTokens[0], parameterTokens[1]);
1123 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1124 Module module = null;
1125 if (data instanceof NodeWrapper) {
1126 module = findModule(mountPoint, (NodeWrapper<?>) data);
1127 } else if (data != null) {
1128 final URI namespace = data.getNodeType().getNamespace();
1129 if (mountPoint != null) {
1130 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1132 module = controllerContext.findModuleByNamespace(namespace);
1135 if (module != null) {
1138 throw new RestconfDocumentedException(
1139 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
1140 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1143 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1144 final URI namespace = data.getNamespace();
1145 Preconditions.<URI> checkNotNull(namespace);
1147 Module module = null;
1148 if (mountPoint != null) {
1149 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1150 if (module == null) {
1151 module = controllerContext.findModuleByName(mountPoint, namespace.toString());
1154 module = controllerContext.findModuleByNamespace(namespace);
1155 if (module == null) {
1156 module = controllerContext.findModuleByName(namespace.toString());
1163 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1164 final CompositeNode data, final DataSchemaNode schemaOfData, final SchemaContext schemaContext) {
1165 YangInstanceIdentifier instanceIdentifier = null;
1166 if (identifierWithSchemaNode != null) {
1167 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1170 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1171 InstanceIdentifierBuilder iiBuilder = null;
1172 if (iiOriginal == null) {
1173 iiBuilder = YangInstanceIdentifier.builder();
1175 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1178 if ((schemaOfData instanceof ListSchemaNode)) {
1179 final HashMap<QName, Object> keys = resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1180 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1182 iiBuilder.node(schemaOfData.getQName());
1185 final YangInstanceIdentifier instance = iiBuilder.toInstance();
1186 DOMMountPoint mountPoint = null;
1187 final SchemaContext schemaCtx = null;
1188 if (identifierWithSchemaNode != null) {
1189 mountPoint = identifierWithSchemaNode.getMountPoint();
1192 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1195 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1196 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1197 final List<QName> _keyDefinition = listNode.getKeyDefinition();
1198 for (final QName key : _keyDefinition) {
1199 SimpleNode<? extends Object> head = null;
1200 final String localName = key.getLocalName();
1201 final List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1202 if (simpleNodesByName != null) {
1203 head = Iterables.getFirst(simpleNodesByName, null);
1206 Object dataNodeKeyValueObject = null;
1208 dataNodeKeyValueObject = head.getValue();
1211 if (dataNodeKeyValueObject == null) {
1212 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1213 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1214 ErrorTag.INVALID_VALUE);
1217 keyValues.put(key, dataNodeKeyValueObject);
1223 private boolean endsWithMountPoint(final String identifier) {
1224 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1227 private boolean representsMountPointRootData(final Node<?> data) {
1228 final URI namespace = namespace(data);
1229 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1230 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1233 && SchemaContext.NAME.getLocalName().equals(localName(data));
1236 private String addMountPointIdentifier(final String identifier) {
1237 final boolean endsWith = identifier.endsWith("/");
1239 return (identifier + ControllerContext.MOUNT);
1242 return identifier + "/" + ControllerContext.MOUNT;
1245 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1246 if (schema == null) {
1247 final String localName = node == null ? null :
1248 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1249 node.getNodeType().getLocalName();
1251 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1252 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1255 if (!(schema instanceof DataNodeContainer)) {
1256 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1257 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1260 if ((node instanceof NodeWrapper<?>)) {
1261 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1262 final boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1263 if (isChangeAllowed) {
1264 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1266 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1267 } catch (final IllegalArgumentException e) {
1268 final RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1269 restconfDocumentedException.addSuppressed(e);
1270 throw restconfDocumentedException;
1272 if (nodeWrap instanceof CompositeNodeWrapper) {
1273 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1278 if (node instanceof CompositeNode) {
1279 return (CompositeNode) node;
1282 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1283 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1286 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1287 final QName previousAugment, final DOMMountPoint mountPoint) {
1288 if (schema == null) {
1289 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1290 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1293 QName currentAugment = null;
1294 if (nodeBuilder.getQname() != null) {
1295 currentAugment = previousAugment;
1297 currentAugment = normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1298 if (nodeBuilder.getQname() == null) {
1299 throw new RestconfDocumentedException(
1300 "Data has bad format.\nIf data is in XML format then namespace for \""
1301 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1302 + "\".\n" + "If data is in JSON format then module name for \""
1303 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1304 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1308 if (nodeBuilder instanceof CompositeNodeWrapper) {
1309 if (schema instanceof DataNodeContainer) {
1310 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1312 } else if (schema instanceof AnyXmlSchemaNode) {
1313 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1315 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1316 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1317 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1318 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1322 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1323 final List<NodeWrapper<?>> children = compositeNode.getValues();
1324 for (final NodeWrapper<? extends Object> child : children) {
1325 child.setNamespace(schema.getQName().getNamespace());
1326 if (child instanceof CompositeNodeWrapper) {
1327 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1332 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1333 if ((schema instanceof LeafSchemaNode)) {
1334 emptyNodeBuilder.setComposite(false);
1336 if ((schema instanceof ContainerSchemaNode)) {
1337 // FIXME: Add presence check
1338 emptyNodeBuilder.setComposite(true);
1343 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1344 final DOMMountPoint mountPoint) {
1345 final Object value = simpleNode.getValue();
1346 Object inputValue = value;
1347 final TypeDef typeDef = this.typeDefinition(schema);
1348 TypeDefinition<? extends Object> typeDefinition = typeDef != null ? typeDef.typedef : null;
1350 // For leafrefs, extract the type it is pointing to
1351 if(typeDefinition instanceof LeafrefTypeDefinition) {
1352 if (schema.getQName().equals(typeDef.qName)) {
1353 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema);
1355 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), typeDef.qName);
1359 if (typeDefinition instanceof IdentityrefTypeDefinition) {
1360 inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue);
1363 Object outputValue = inputValue;
1365 if (typeDefinition != null) {
1366 final Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1367 outputValue = codec == null ? null : codec.deserialize(inputValue);
1370 simpleNode.setValue(outputValue);
1373 private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) {
1374 if ((value instanceof String)) {
1375 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1377 } // else value is already instance of IdentityValuesDTO
1381 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1382 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1383 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1384 checkNodeMultiplicityAccordingToSchema(schema, children);
1385 for (final NodeWrapper<? extends Object> child : children) {
1386 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1387 schema, child.getLocalName());
1389 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1390 final StringBuilder builder = new StringBuilder();
1391 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1392 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1395 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1396 + "\" is added as augment from more than one module. "
1397 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1398 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1399 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1402 boolean rightNodeSchemaFound = false;
1403 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1404 if (!rightNodeSchemaFound) {
1405 final QName potentialCurrentAugment = normalizeNodeName(child, potentialSchemaNode,
1406 currentAugment, mountPoint);
1407 if (child.getQname() != null) {
1408 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1409 rightNodeSchemaFound = true;
1414 if (!rightNodeSchemaFound) {
1415 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1416 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1420 if ((schema instanceof ListSchemaNode)) {
1421 final ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1422 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1423 for (final QName listKey : listKeys) {
1424 boolean foundKey = false;
1425 for (final NodeWrapper<? extends Object> child : children) {
1426 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1432 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1433 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1434 ErrorTag.DATA_MISSING);
1440 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1441 final List<NodeWrapper<?>> nodes) {
1442 final Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1443 for (final NodeWrapper<?> child : nodes) {
1444 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1445 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1448 for (final DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1449 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1450 final String localName = childSchemaNode.getQName().getLocalName();
1451 final Integer count = equalNodeNamesToCounts.get(localName);
1452 if (count != null && count > 1) {
1453 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1454 + childSchemaNode.getQName().getLocalName()
1455 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1456 ErrorTag.BAD_ELEMENT);
1462 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1463 final QName previousAugment, final DOMMountPoint mountPoint) {
1464 QName validQName = schema.getQName();
1465 QName currentAugment = previousAugment;
1466 if (schema.isAugmenting()) {
1467 currentAugment = schema.getQName();
1468 } else if (previousAugment != null
1469 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1470 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1473 String moduleName = null;
1474 if (mountPoint == null) {
1475 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1477 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1480 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1481 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1483 * || Note : this check is wrong -
1484 * can never be true as it compares
1485 * a URI with a String not sure what
1486 * the intention is so commented out
1487 * ... Objects . equal ( nodeBuilder
1488 * . getNamespace ( ) ,
1489 * MOUNT_POINT_MODULE_NAME )
1492 nodeBuilder.setQname(validQName);
1495 return currentAugment;
1498 private URI namespace(final Node<?> data) {
1499 if (data instanceof NodeWrapper) {
1500 return ((NodeWrapper<?>) data).getNamespace();
1501 } else if (data != null) {
1502 return data.getNodeType().getNamespace();
1504 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1508 private String localName(final Node<?> data) {
1509 if (data instanceof NodeWrapper) {
1510 return ((NodeWrapper<?>) data).getLocalName();
1511 } else if (data != null) {
1512 return data.getNodeType().getLocalName();
1514 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1518 private String getName(final Node<?> data) {
1519 if (data instanceof NodeWrapper) {
1520 return ((NodeWrapper<?>) data).getLocalName();
1521 } else if (data != null) {
1522 return data.getNodeType().getLocalName();
1524 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1528 private TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
1529 TypeDefinition<?> baseType = type;
1530 QName qName = nodeQName;
1531 while (baseType.getBaseType() != null) {
1532 if (baseType instanceof ExtendedType) {
1533 qName = baseType.getQName();
1535 baseType = baseType.getBaseType();
1538 return new TypeDef(baseType, qName);
1542 private TypeDef typeDefinition(final DataSchemaNode node) {
1543 if (node instanceof LeafListSchemaNode) {
1544 return typeDefinition(((LeafListSchemaNode)node).getType(), node.getQName());
1545 } else if (node instanceof LeafSchemaNode) {
1546 return typeDefinition(((LeafSchemaNode)node).getType(), node.getQName());
1547 } else if (node instanceof AnyXmlSchemaNode) {
1550 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1554 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1555 Node<?> nodes = null;
1556 if (dataNode == null) {
1557 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1558 "No data was found."));
1560 nodes = DataNormalizer.toLegacy(dataNode);
1561 if (nodes != null) {
1562 if (nodes instanceof CompositeNode) {
1563 return (CompositeNode) nodes;
1565 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1568 LOG.error("Top level node isn't of type Container or List schema node but "
1569 + schema.getClass().getSimpleName());
1572 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1573 "It wasn't possible to correctly interpret data."));
1576 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1577 final DataSchemaNode schema) {
1578 final List<Node<?>> lst = new ArrayList<Node<?>>();
1580 if (schema instanceof ContainerSchemaNode) {
1581 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1582 .parse(lst, (ContainerSchemaNode) schema);
1583 } else if (schema instanceof ListSchemaNode) {
1584 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1585 .parse(lst, (ListSchemaNode) schema);
1588 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1590 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1591 "It wasn't possible to translate specified data to datastore readable form."));
1594 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1595 final InstanceIdentifierContext iiWithSchemaNode) {
1596 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1599 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1600 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1601 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1602 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1603 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1606 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1607 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1608 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1609 final List<PathArgument> result = new ArrayList<PathArgument>();
1610 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1611 while (iter.hasNext()) {
1612 final PathArgument pathArgument = iter.next();
1613 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1614 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1616 result.add(pathArgument);
1618 return YangInstanceIdentifier.create(result);
1621 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1622 final DataSchemaNode schemaNode) {
1623 if (node instanceof CompositeNodeWrapper) {
1624 return (CompositeNodeWrapper) node;
1625 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1626 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1627 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1630 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1631 "Top level element has to be composite node or has to represent data container node."));
1634 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1635 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1641 public BigInteger getOperationalReceived() {
1642 // TODO Auto-generated method stub
1646 private MapNode makeModuleMapNode(final Set<Module> modules) {
1647 Preconditions.checkNotNull(modules);
1648 final Module restconfModule = getRestconfModule();
1649 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1650 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1651 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1653 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1654 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1656 for (final Module module : modules) {
1657 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1659 return listModuleBuilder.build();
1662 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1663 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1664 "moduleSchemaNode has to be of type ListSchemaNode");
\r final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
\r final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
\r .mapEntryBuilder(listModuleSchemaNode);
\r\r List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "name");
\r final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
\r .build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "revision");
\r final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
\r final String revision = REVISION_FORMAT.format(module.getRevision());
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
\r .build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "namespace");
\r final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
\r .withValue(module.getNamespace().toString()).build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "feature");
\r final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
\r final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
\r .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
\r for (final FeatureDefinition feature : module.getFeatures()) {
\r featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
\r .withValue(feature.getQName().getLocalName()).build());
\r }
\r moduleNodeValues.withChild(featuresBuilder.build());
1665 \r return moduleNodeValues.build();
\r }