Bug 222: Added basic Restconf operational statistics
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / RestconfImpl.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2014 Brocade Communication Systems, Inc.
4  *
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
8  */
9 package org.opendaylight.controller.sal.restconf.impl;
10
11 import com.google.common.base.Objects;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import java.math.BigInteger;
19 import java.net.URI;
20 import java.text.ParseException;
21 import java.text.SimpleDateFormat;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.Response.Status;
33 import javax.ws.rs.core.UriBuilder;
34 import javax.ws.rs.core.UriInfo;
35 import org.apache.commons.lang3.StringUtils;
36 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
41 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
42 import org.opendaylight.controller.sal.rest.api.Draft02;
43 import org.opendaylight.controller.sal.rest.api.RestconfService;
44 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
45 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
46 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
47 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
48 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
49 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
50 import org.opendaylight.controller.sal.streams.listeners.Notificator;
51 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
52 import org.opendaylight.yangtools.concepts.Codec;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.QNameModule;
55 import org.opendaylight.yangtools.yang.common.RpcResult;
56 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
57 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
58 import org.opendaylight.yangtools.yang.data.api.Node;
59 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
66 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
67 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
68 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
71 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
73 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.Module;
77 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
78 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
80 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.util.EmptyType;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
84 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87
88 public class RestconfImpl implements RestconfService {
89
90     private enum UriParameters {
91         PRETTY_PRINT("prettyPrint"),
92         DEPTH("depth");
93
94         private String uriParameterName;
95
96         UriParameters(final String uriParameterName) {
97             this.uriParameterName = uriParameterName;
98         }
99
100         @Override
101         public String toString() {
102             return uriParameterName;
103         }
104     }
105
106
107
108     private final static RestconfImpl INSTANCE = new RestconfImpl();
109
110     private static final int NOTIFICATION_PORT = 8181;
111
112     private static final int CHAR_NOT_FOUND = -1;
113
114     private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
115
116     private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
117
118     private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
119
120     private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
121
122     private BrokerFacade broker;
123
124     private ControllerContext controllerContext;
125
126     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
127
128     private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
129
130     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
131
132     private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
133
134     private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
135
136     private static final String DATASTORE_PARAM_NAME = "datastore";
137
138     private static final String SCOPE_PARAM_NAME = "scope";
139
140     static {
141         try {
142             EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
143         } catch (ParseException e) {
144             throw new RestconfDocumentedException(
145                     "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
146                     ErrorTag.OPERATION_FAILED);
147         }
148     }
149
150     public void setBroker(final BrokerFacade broker) {
151         this.broker = broker;
152     }
153
154     public void setControllerContext(final ControllerContext controllerContext) {
155         this.controllerContext = controllerContext;
156     }
157
158     private RestconfImpl() {
159     }
160
161     public static RestconfImpl getInstance() {
162         return INSTANCE;
163     }
164
165     @Override
166     public StructuredData getModules(final UriInfo uriInfo) {
167         final Module restconfModule = this.getRestconfModule();
168
169         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
170         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
171                 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
172
173         Set<Module> allModules = this.controllerContext.getAllModules();
174         for (final Module module : allModules) {
175             CompositeNode moduleCompositeNode = this.toModuleCompositeNode(module, moduleSchemaNode);
176             modulesAsData.add(moduleCompositeNode);
177         }
178
179         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
180                 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
181         QName qName = modulesSchemaNode.getQName();
182         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
183         return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
184     }
185
186     @Override
187     public StructuredData getAvailableStreams(final UriInfo uriInfo) {
188         Set<String> availableStreams = Notificator.getStreamNames();
189
190         final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
191         Module restconfModule = this.getRestconfModule();
192         final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
193                 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
194         for (final String streamName : availableStreams) {
195             streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
196         }
197
198         final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
199                 Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
200         QName qName = streamsSchemaNode.getQName();
201         final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
202         return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
203     }
204
205     @Override
206     public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
207         Set<Module> modules = null;
208         DOMMountPoint mountPoint = null;
209         if (identifier.contains(ControllerContext.MOUNT)) {
210             InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
211             mountPoint = mountPointIdentifier.getMountPoint();
212             modules = this.controllerContext.getAllModules(mountPoint);
213         } else {
214             throw new RestconfDocumentedException(
215                     "URI has bad format. If modules behind mount point should be showed, URI has to end with "
216                             + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
217         }
218
219         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
220         Module restconfModule = this.getRestconfModule();
221         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
222                 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
223
224         for (final Module module : modules) {
225             modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
226         }
227
228         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
229                 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
230         QName qName = modulesSchemaNode.getQName();
231         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
232         return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
233     }
234
235     @Override
236     public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
237         final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
238         Module module = null;
239         DOMMountPoint mountPoint = null;
240         if (identifier.contains(ControllerContext.MOUNT)) {
241             InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
242             mountPoint = mountPointIdentifier.getMountPoint();
243             module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
244         } else {
245             module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
246         }
247
248         if (module == null) {
249             throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
250                     + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
251                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
252         }
253
254         Module restconfModule = this.getRestconfModule();
255         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
256                 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
257         final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
258         return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
259     }
260
261     @Override
262     public StructuredData getOperations(final UriInfo uriInfo) {
263         Set<Module> allModules = this.controllerContext.getAllModules();
264         return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
265     }
266
267     @Override
268     public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
269         Set<Module> modules = null;
270         DOMMountPoint mountPoint = null;
271         if (identifier.contains(ControllerContext.MOUNT)) {
272             InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
273             mountPoint = mountPointIdentifier.getMountPoint();
274             modules = this.controllerContext.getAllModules(mountPoint);
275         } else {
276             throw new RestconfDocumentedException(
277                     "URI has bad format. If operations behind mount point should be showed, URI has to end with "
278                             + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
279         }
280
281         return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
282     }
283
284     private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
285             final DOMMountPoint mountPoint, final boolean prettyPrint) {
286         final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
287         Module restconfModule = this.getRestconfModule();
288         final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
289                 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
290         QName qName = operationsSchemaNode.getQName();
291         SchemaPath path = operationsSchemaNode.getPath();
292         ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
293                 Draft02.RestConfModule.NAME, 0, qName, path);
294         final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
295         for (final Module module : modules) {
296             Set<RpcDefinition> rpcs = module.getRpcs();
297             for (final RpcDefinition rpc : rpcs) {
298                 QName rpcQName = rpc.getQName();
299                 SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
300                         null);
301                 operationsAsData.add(immutableSimpleNode);
302
303                 String name = module.getName();
304                 LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
305                         SchemaPath.create(true, QName.create("dummy")));
306                 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
307                 fakeRpcSchemaNode.setAugmenting(true);
308
309                 EmptyType instance = EmptyType.getInstance();
310                 fakeRpcSchemaNode.setType(instance);
311                 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
312             }
313         }
314
315         final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
316         ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
317         return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
318     }
319
320     private Module getRestconfModule() {
321         Module restconfModule = controllerContext.getRestconfModule();
322         if (restconfModule == null) {
323             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
324                     ErrorTag.OPERATION_NOT_SUPPORTED);
325         }
326
327         return restconfModule;
328     }
329
330     private QName getModuleNameAndRevision(final String identifier) {
331         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
332         String moduleNameAndRevision = "";
333         if (mountIndex >= 0) {
334             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
335         } else {
336             moduleNameAndRevision = identifier;
337         }
338
339         Splitter splitter = Splitter.on("/").omitEmptyStrings();
340         Iterable<String> split = splitter.split(moduleNameAndRevision);
341         final List<String> pathArgs = Lists.<String> newArrayList(split);
342         if (pathArgs.size() < 2) {
343             throw new RestconfDocumentedException(
344                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
345                     ErrorTag.INVALID_VALUE);
346         }
347
348         try {
349             final String moduleName = pathArgs.get(0);
350             String revision = pathArgs.get(1);
351             final Date moduleRevision = REVISION_FORMAT.parse(revision);
352             return QName.create(null, moduleRevision, moduleName);
353         } catch (ParseException e) {
354             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
355                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
356         }
357     }
358
359     private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
360         final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
361         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
362                 ((DataNodeContainer) streamSchemaNode), "name");
363         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
364         streamNodeValues
365         .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
366
367         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
368                 ((DataNodeContainer) streamSchemaNode), "description");
369         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
370         streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
371                 "DESCRIPTION_PLACEHOLDER"));
372
373         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
374                 ((DataNodeContainer) streamSchemaNode), "replay-support");
375         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
376         streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
377                 Boolean.valueOf(true)));
378
379         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
380                 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
381         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
382         streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
383                 null, ""));
384
385         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
386                 ((DataNodeContainer) streamSchemaNode), "events");
387         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
388         streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
389
390         return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
391     }
392
393     private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
394         final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
395         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
396                 ((DataNodeContainer) moduleSchemaNode), "name");
397         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
398         moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
399                 module.getName()));
400
401         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
402                 ((DataNodeContainer) moduleSchemaNode), "revision");
403         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
404         Date _revision = module.getRevision();
405         moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
406                 REVISION_FORMAT.format(_revision)));
407
408         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
409                 ((DataNodeContainer) moduleSchemaNode), "namespace");
410         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
411         moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
412                 module.getNamespace().toString()));
413
414         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
415                 ((DataNodeContainer) moduleSchemaNode), "feature");
416         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
417         for (final FeatureDefinition feature : module.getFeatures()) {
418             moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
419                     feature.getQName().getLocalName()));
420         }
421
422         return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
423     }
424
425     @Override
426     public Object getRoot() {
427         return null;
428     }
429
430     @Override
431     public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
432         final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
433         QName rpcName = rpc.getRpcDefinition().getQName();
434         URI rpcNamespace = rpcName.getNamespace();
435         if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
436                 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
437             return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
438         }
439
440         validateInput(rpc.getRpcDefinition().getInput(), payload);
441
442         return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
443     }
444
445     private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
446         if (inputSchema != null && payload == null) {
447             // expected a non null payload
448             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
449         } else if (inputSchema == null && payload != null) {
450             // did not expect any input
451             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
452         }
453         // else
454         // {
455         // TODO: Validate "mandatory" and "config" values here??? Or should those be
456         // those be
457         // validate in a more central location inside MD-SAL core.
458         // }
459     }
460
461     private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
462             final boolean prettyPrint) {
463         final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
464         final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
465                 rpc.getQName(), "path"));
466         final Object pathValue = pathNode == null ? null : pathNode.getValue();
467
468         if (!(pathValue instanceof YangInstanceIdentifier)) {
469             throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
470                     ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
471         }
472
473         final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
474         String streamName = null;
475         if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
476             String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
477
478             LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
479                     DATASTORE_PARAM_NAME);
480             datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
481
482             DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
483             scope = scope == null ? DEFAULT_SCOPE : scope;
484
485             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
486                     + "/scope=" + scope);
487         }
488
489         if (Strings.isNullOrEmpty(streamName)) {
490             throw new RestconfDocumentedException(
491                     "Path is empty or contains data node which is not Container or List build-in type.",
492                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
493         }
494
495         final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
496                 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
497         final List<Node<?>> output = new ArrayList<Node<?>>();
498         output.add(streamNameNode);
499
500         final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
501                 null, output, null, null);
502
503         if (!Notificator.existListenerFor(streamName)) {
504             Notificator.createListener(pathIdentifier, streamName);
505         }
506
507         return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
508     }
509
510     @Override
511     public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
512         if (StringUtils.isNotBlank(noPayload)) {
513             throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
514         }
515         return invokeRpc(identifier, (CompositeNode) null, uriInfo);
516     }
517
518     private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
519         String identifierEncoded = null;
520         DOMMountPoint mountPoint = null;
521         if (identifier.contains(ControllerContext.MOUNT)) {
522             // mounted RPC call - look up mount instance.
523             InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
524             mountPoint = mountPointId.getMountPoint();
525
526             int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
527                     + ControllerContext.MOUNT.length() + 1;
528             String remoteRpcName = identifier.substring(startOfRemoteRpcName);
529             identifierEncoded = remoteRpcName;
530
531         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
532             final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
533                     + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
534             throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
535         } else {
536             identifierEncoded = identifier;
537         }
538
539         final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
540
541         RpcDefinition rpc = null;
542         if (mountPoint == null) {
543             rpc = controllerContext.getRpcDefinition(identifierDecoded);
544         } else {
545             rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
546         }
547
548         if (rpc == null) {
549             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
550         }
551
552         if (mountPoint == null) {
553             return new BrokerRpcExecutor(rpc, broker);
554         } else {
555             return new MountPointRpcExecutor(rpc, mountPoint);
556         }
557
558     }
559
560     private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
561         final String[] splittedIdentifier = identifierDecoded.split(":");
562         if (splittedIdentifier.length != 2) {
563             throw new RestconfDocumentedException(identifierDecoded
564                     + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
565                     ErrorTag.INVALID_VALUE);
566         }
567         for (Module module : schemaContext.getModules()) {
568             if (module.getName().equals(splittedIdentifier[0])) {
569                 for (RpcDefinition rpcDefinition : module.getRpcs()) {
570                     if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
571                         return rpcDefinition;
572                     }
573                 }
574             }
575         }
576         return null;
577     }
578
579     private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
580         if (rpcExecutor == null) {
581             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
582         }
583
584         CompositeNode rpcRequest = null;
585         RpcDefinition rpc = rpcExecutor.getRpcDefinition();
586         QName rpcName = rpc.getQName();
587
588         if (payload == null) {
589             rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
590         } else {
591             final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
592             List<Node<?>> input = Collections.<Node<?>> singletonList(value);
593             rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
594         }
595
596         RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
597
598         checkRpcSuccessAndThrowException(rpcResult);
599
600         if (rpcResult.getResult() == null) {
601             return null;
602         }
603
604         if (rpc.getOutput() == null) {
605             return null; // no output, nothing to send back.
606         }
607
608         return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
609     }
610
611     private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
612         if (rpcResult.isSuccessful() == false) {
613
614             throw new RestconfDocumentedException("The operation was not successful", null,
615                     rpcResult.getErrors());
616         }
617     }
618
619     @Override
620     public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
621         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
622         DOMMountPoint mountPoint = iiWithData.getMountPoint();
623         NormalizedNode<?, ?> data = null;
624         YangInstanceIdentifier normalizedII;
625         if (mountPoint != null) {
626             normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
627                     .getInstanceIdentifier());
628             data = broker.readConfigurationData(mountPoint, normalizedII);
629         } else {
630             normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
631             data = broker.readConfigurationData(normalizedII);
632         }
633         return new NormalizedNodeContext(iiWithData, data);
634     }
635
636     @SuppressWarnings("unchecked")
637     private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
638         if (depth == null) {
639             return node;
640         }
641
642         if (node instanceof CompositeNode) {
643             ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
644             if (depth > 1) {
645                 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
646                     newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
647                 }
648             }
649
650             return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
651         } else { // SimpleNode
652             return node;
653         }
654     }
655
656     private Integer parseDepthParameter(final UriInfo info) {
657         String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
658         if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
659             return null;
660         }
661
662         try {
663             Integer depth = Integer.valueOf(param);
664             if (depth < 1) {
665                 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
666                         "Invalid depth parameter: " + depth, null,
667                         "The depth parameter must be an integer > 1 or \"unbounded\""));
668             }
669
670             return depth;
671         } catch (NumberFormatException e) {
672             throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
673                     "Invalid depth parameter: " + e.getMessage(), null,
674                     "The depth parameter must be an integer > 1 or \"unbounded\""));
675         }
676     }
677
678     @Override
679     public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
680         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
681         DOMMountPoint mountPoint = iiWithData.getMountPoint();
682         NormalizedNode<?, ?> data = null;
683         YangInstanceIdentifier normalizedII;
684         if (mountPoint != null) {
685             normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
686                     .getInstanceIdentifier());
687             data = broker.readOperationalData(mountPoint, normalizedII);
688         } else {
689             normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
690             data = broker.readOperationalData(normalizedII);
691         }
692
693         return new NormalizedNodeContext(iiWithData, data);
694     }
695
696     private boolean parsePrettyPrintParameter(final UriInfo info) {
697         String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
698         return Boolean.parseBoolean(param);
699     }
700
701     @Override
702     public Response updateConfigurationData(final String identifier, final Node<?> payload) {
703         final InstanceIdentifierContext iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
704
705         validateInput(iiWithData.getSchemaNode(), payload);
706
707         DOMMountPoint mountPoint = iiWithData.getMountPoint();
708         final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
709         validateListKeysEqualityInPayloadAndUri(iiWithData, value);
710         final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
711                 iiWithData.getSchemaNode());
712
713         YangInstanceIdentifier normalizedII;
714         if (mountPoint != null) {
715             normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
716                     iiWithData.getInstanceIdentifier());
717         } else {
718             normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
719         }
720
721         /*
722          * There is a small window where another write transaction could be updating the same data
723          * simultaneously and we get an OptimisticLockFailedException. This error is likely
724          * transient and The WriteTransaction#submit API docs state that a retry will likely
725          * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
726          * probably will never succeed so we'll fail in that case.
727          *
728          * By retrying we're attempting to hide the internal implementation of the data store and
729          * how it handles concurrent updates from the restconf client. The client has instructed us
730          * to put the data and we should make every effort to do so without pushing optimistic lock
731          * failures back to the client and forcing them to handle it via retry (and having to
732          * document the behavior).
733          */
734         int tries = 2;
735         while(true) {
736             try {
737                 if (mountPoint != null) {
738                     broker.commitConfigurationDataPut(mountPoint, normalizedII,
739                             datastoreNormalizedNode).checkedGet();
740                 } else {
741                     broker.commitConfigurationDataPut(normalizedII,
742                             datastoreNormalizedNode).checkedGet();
743                 }
744
745                 break;
746             } catch (TransactionCommitFailedException e) {
747                 if(e instanceof OptimisticLockFailedException) {
748                     if(--tries <= 0) {
749                         LOG.debug("Got OptimisticLockFailedException on last try - failing");
750                         throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
751                     }
752
753                     LOG.debug("Got OptimisticLockFailedException - trying again");
754                 } else {
755                     throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
756                 }
757             }
758         }
759
760         return Response.status(Status.OK).build();
761     }
762
763     /**
764      * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
765      *
766      * @throws RestconfDocumentedException
767      *             if key values or key count in payload and URI isn't equal
768      *
769      */
770     private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
771             final CompositeNode payload) {
772         if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
773             final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
774             final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
775             if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
776                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
777                         .getKeyValues();
778                 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
779             }
780         }
781     }
782
783     private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
784             final List<QName> keyDefinitions) {
785         for (QName keyDefinition : keyDefinitions) {
786             final Object uriKeyValue = uriKeyValues.get(keyDefinition);
787             // should be caught during parsing URI to InstanceIdentifier
788             if (uriKeyValue == null) {
789                 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
790                         ErrorTag.DATA_MISSING);
791             }
792             final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
793             if (payloadKeyValues.isEmpty()) {
794                 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
795                         + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
796             }
797
798             Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
799             if (!uriKeyValue.equals(payloadKeyValue)) {
800                 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
801                         + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
802                         + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
803                         ErrorTag.INVALID_VALUE);
804             }
805         }
806     }
807
808     @Override
809     public Response createConfigurationData(final String identifier, final Node<?> payload) {
810         if (payload == null) {
811             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
812         }
813
814         URI payloadNS = this.namespace(payload);
815         if (payloadNS == null) {
816             throw new RestconfDocumentedException(
817                     "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
818                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
819         }
820
821         InstanceIdentifierContext iiWithData = null;
822         CompositeNode value = null;
823         if (this.representsMountPointRootData(payload)) {
824             // payload represents mount point data and URI represents path to the mount point
825
826             if (this.endsWithMountPoint(identifier)) {
827                 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
828                         + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
829                         ErrorTag.INVALID_VALUE);
830             }
831
832             final String completeIdentifier = this.addMountPointIdentifier(identifier);
833             iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
834
835             value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
836         } else {
837             final InstanceIdentifierContext incompleteInstIdWithData = this.controllerContext
838                     .toInstanceIdentifier(identifier);
839             final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
840             DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
841             final Module module = findModule(mountPoint, payload);
842             if (module == null) {
843                 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
844                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
845             }
846
847             String payloadName = this.getName(payload);
848             final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
849                     parentSchema, payloadName, module.getNamespace());
850             value = this.normalizeNode(payload, schemaNode, mountPoint);
851
852             iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
853         }
854
855         final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
856                 iiWithData.getSchemaNode());
857         DOMMountPoint mountPoint = iiWithData.getMountPoint();
858         YangInstanceIdentifier normalizedII;
859
860         try {
861             if (mountPoint != null) {
862                 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
863                         .getInstanceIdentifier());
864                 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
865             } else {
866                 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
867                 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
868             }
869         } catch(RestconfDocumentedException e) {
870             throw e;
871         } catch (Exception e) {
872             throw new RestconfDocumentedException("Error creating data", e);
873         }
874
875         return Response.status(Status.NO_CONTENT).build();
876     }
877
878     @Override
879     public Response createConfigurationData(final Node<?> payload) {
880         if (payload == null) {
881             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
882         }
883
884         URI payloadNS = this.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);
889         }
890
891         final Module module = this.findModule(null, payload);
892         if (module == null) {
893             throw new RestconfDocumentedException(
894                     "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
895                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
896         }
897
898         String payloadName = this.getName(payload);
899         final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
900                 payloadName, module.getNamespace());
901         final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
902         final InstanceIdentifierContext iiWithData = this.addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
903         final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
904         DOMMountPoint mountPoint = iiWithData.getMountPoint();
905         YangInstanceIdentifier normalizedII;
906
907         try {
908             if (mountPoint != null) {
909                 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
910                         .getInstanceIdentifier());
911                 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
912
913             } else {
914                 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
915                 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
916             }
917         } catch(RestconfDocumentedException e) {
918             throw e;
919         } catch (Exception e) {
920             throw new RestconfDocumentedException("Error creating data", e);
921         }
922
923         return Response.status(Status.NO_CONTENT).build();
924     }
925
926     @Override
927     public Response deleteConfigurationData(final String identifier) {
928         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
929         DOMMountPoint mountPoint = iiWithData.getMountPoint();
930         YangInstanceIdentifier normalizedII;
931
932         try {
933             if (mountPoint != null) {
934                 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
935                         .getInstanceIdentifier());
936                 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
937             } else {
938                 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
939                 broker.commitConfigurationDataDelete(normalizedII).get();
940             }
941         } catch (Exception e) {
942             throw new RestconfDocumentedException("Error creating data", e);
943         }
944
945         return Response.status(Status.OK).build();
946     }
947
948     /**
949      * Subscribes to some path in schema context (stream) to listen on changes on this stream.
950      *
951      * Additional parameters for subscribing to stream are loaded via rpc input parameters:
952      * <ul>
953      * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
954      * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
955      * </ul>
956      */
957     @Override
958     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
959         final String streamName = Notificator.createStreamNameFromUri(identifier);
960         if (Strings.isNullOrEmpty(streamName)) {
961             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
962         }
963
964         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
965         if (listener == null) {
966             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
967         }
968
969         Map<String, String> paramToValues = resolveValuesFromUri(identifier);
970         LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
971                 paramToValues.get(DATASTORE_PARAM_NAME));
972         if (datastore == null) {
973             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
974                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
975         }
976         DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
977         if (scope == null) {
978             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
979                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
980         }
981
982         broker.registerToListenDataChanges(datastore, scope, listener);
983
984         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
985         int notificationPort = NOTIFICATION_PORT;
986         try {
987             WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
988             notificationPort = webSocketServerInstance.getPort();
989         } catch (NullPointerException e) {
990             WebSocketServer.createInstance(NOTIFICATION_PORT);
991         }
992         UriBuilder port = uriBuilder.port(notificationPort);
993         final URI uriToWebsocketServer = port.replacePath(streamName).build();
994
995         return Response.status(Status.OK).location(uriToWebsocketServer).build();
996     }
997
998     /**
999      * Load parameter for subscribing to stream from input composite node
1000      *
1001      * @param compNode
1002      *            contains value
1003      * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1004      */
1005     private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1006             final String paramName) {
1007         QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1008                 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1009         SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1010         if (simpleNode == null) {
1011             return null;
1012         }
1013         Object rawValue = simpleNode.getValue();
1014         if (!(rawValue instanceof String)) {
1015             return null;
1016         }
1017
1018         return resolveAsEnum(classDescriptor, (String) rawValue);
1019     }
1020
1021     /**
1022      * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1023      *
1024      * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1025      *         null.
1026      */
1027     private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1028         if (Strings.isNullOrEmpty(value)) {
1029             return null;
1030         }
1031         return resolveAsEnum(classDescriptor, value);
1032     }
1033
1034     private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1035         T[] enumConstants = classDescriptor.getEnumConstants();
1036         if (enumConstants != null) {
1037             for (T enm : classDescriptor.getEnumConstants()) {
1038                 if (((Enum<?>) enm).name().equals(value)) {
1039                     return enm;
1040                 }
1041             }
1042         }
1043         return null;
1044     }
1045
1046     private Map<String, String> resolveValuesFromUri(final String uri) {
1047         Map<String, String> result = new HashMap<>();
1048         String[] tokens = uri.split("/");
1049         for (int i = 1; i < tokens.length; i++) {
1050             String[] parameterTokens = tokens[i].split("=");
1051             if (parameterTokens.length == 2) {
1052                 result.put(parameterTokens[0], parameterTokens[1]);
1053             }
1054         }
1055         return result;
1056     }
1057
1058     private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1059         if (data instanceof NodeWrapper) {
1060             return findModule(mountPoint, (NodeWrapper<?>) data);
1061         } else if (data != null) {
1062             URI namespace = data.getNodeType().getNamespace();
1063             if (mountPoint != null) {
1064                 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1065             } else {
1066                 return this.controllerContext.findModuleByNamespace(namespace);
1067             }
1068         } else {
1069             throw new IllegalArgumentException("Unhandled parameter types: "
1070                     + Arrays.<Object> asList(mountPoint, data).toString());
1071         }
1072     }
1073
1074     private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1075         URI namespace = data.getNamespace();
1076         Preconditions.<URI> checkNotNull(namespace);
1077
1078         Module module = null;
1079         if (mountPoint != null) {
1080             module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1081             if (module == null) {
1082                 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1083             }
1084         } else {
1085             module = this.controllerContext.findModuleByNamespace(namespace);
1086             if (module == null) {
1087                 module = this.controllerContext.findModuleByName(namespace.toString());
1088             }
1089         }
1090
1091         return module;
1092     }
1093
1094     private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1095             final CompositeNode data, final DataSchemaNode schemaOfData, SchemaContext schemaContext) {
1096         YangInstanceIdentifier instanceIdentifier = null;
1097         if (identifierWithSchemaNode != null) {
1098             instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1099         }
1100
1101         final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1102         InstanceIdentifierBuilder iiBuilder = null;
1103         if (iiOriginal == null) {
1104             iiBuilder = YangInstanceIdentifier.builder();
1105         } else {
1106             iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1107         }
1108
1109         if ((schemaOfData instanceof ListSchemaNode)) {
1110             HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1111             iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1112         } else {
1113             iiBuilder.node(schemaOfData.getQName());
1114         }
1115
1116         YangInstanceIdentifier instance = iiBuilder.toInstance();
1117         DOMMountPoint mountPoint = null;
1118         SchemaContext schemaCtx = null;
1119         if (identifierWithSchemaNode != null) {
1120             mountPoint = identifierWithSchemaNode.getMountPoint();
1121         }
1122
1123         return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1124     }
1125
1126     private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1127         final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1128         List<QName> _keyDefinition = listNode.getKeyDefinition();
1129         for (final QName key : _keyDefinition) {
1130             SimpleNode<? extends Object> head = null;
1131             String localName = key.getLocalName();
1132             List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1133             if (simpleNodesByName != null) {
1134                 head = Iterables.getFirst(simpleNodesByName, null);
1135             }
1136
1137             Object dataNodeKeyValueObject = null;
1138             if (head != null) {
1139                 dataNodeKeyValueObject = head.getValue();
1140             }
1141
1142             if (dataNodeKeyValueObject == null) {
1143                 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1144                         + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1145                         ErrorTag.INVALID_VALUE);
1146             }
1147
1148             keyValues.put(key, dataNodeKeyValueObject);
1149         }
1150
1151         return keyValues;
1152     }
1153
1154     private boolean endsWithMountPoint(final String identifier) {
1155         return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1156     }
1157
1158     private boolean representsMountPointRootData(final Node<?> data) {
1159         URI namespace = this.namespace(data);
1160         return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1161          * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1162          * toString( ) )
1163          */)
1164          && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1165     }
1166
1167     private String addMountPointIdentifier(final String identifier) {
1168         boolean endsWith = identifier.endsWith("/");
1169         if (endsWith) {
1170             return (identifier + ControllerContext.MOUNT);
1171         }
1172
1173         return identifier + "/" + ControllerContext.MOUNT;
1174     }
1175
1176     private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1177         if (schema == null) {
1178             String localName = node == null ? null :
1179                     node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1180                     node.getNodeType().getLocalName();
1181
1182             throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1183                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1184         }
1185
1186         if (!(schema instanceof DataNodeContainer)) {
1187             throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1188                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1189         }
1190
1191         if ((node instanceof NodeWrapper<?>)) {
1192             NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1193             boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1194             if (isChangeAllowed) {
1195                 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1196                 try {
1197                     this.normalizeNode(nodeWrap, schema, null, mountPoint);
1198                 } catch (IllegalArgumentException e) {
1199                     throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1200                 }
1201                 if (nodeWrap instanceof CompositeNodeWrapper) {
1202                     return ((CompositeNodeWrapper) nodeWrap).unwrap();
1203                 }
1204             }
1205         }
1206
1207         if (node instanceof CompositeNode) {
1208             return (CompositeNode) node;
1209         }
1210
1211         throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1212                 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1213     }
1214
1215     private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1216             final QName previousAugment, final DOMMountPoint mountPoint) {
1217         if (schema == null) {
1218             throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1219                     + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1220         }
1221
1222         QName currentAugment = null;
1223         if (nodeBuilder.getQname() != null) {
1224             currentAugment = previousAugment;
1225         } else {
1226             currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1227             if (nodeBuilder.getQname() == null) {
1228                 throw new RestconfDocumentedException(
1229                         "Data has bad format.\nIf data is in XML format then namespace for \""
1230                                 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1231                                 + "\".\n" + "If data is in JSON format then module name for \""
1232                                 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1233                                 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1234             }
1235         }
1236
1237         if (nodeBuilder instanceof CompositeNodeWrapper) {
1238             if (schema instanceof DataNodeContainer) {
1239                 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1240                         currentAugment);
1241             } else if (schema instanceof AnyXmlSchemaNode) {
1242                 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1243             }
1244         } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1245             normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1246         } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1247             normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1248         }
1249     }
1250
1251     private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1252         List<NodeWrapper<?>> children = compositeNode.getValues();
1253         for (NodeWrapper<? extends Object> child : children) {
1254             child.setNamespace(schema.getQName().getNamespace());
1255             if (child instanceof CompositeNodeWrapper) {
1256                 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1257             }
1258         }
1259     }
1260
1261     private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1262         if ((schema instanceof LeafSchemaNode)) {
1263             emptyNodeBuilder.setComposite(false);
1264         } else {
1265             if ((schema instanceof ContainerSchemaNode)) {
1266                 // FIXME: Add presence check
1267                 emptyNodeBuilder.setComposite(true);
1268             }
1269         }
1270     }
1271
1272     private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1273             final DOMMountPoint mountPoint) {
1274         final Object value = simpleNode.getValue();
1275         Object inputValue = value;
1276         TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1277         if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1278             if ((value instanceof String)) {
1279                 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1280                         (String) value);
1281             } // else value is already instance of IdentityValuesDTO
1282         }
1283
1284         Object outputValue = inputValue;
1285
1286         if (typeDefinition != null) {
1287             Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1288             outputValue = codec == null ? null : codec.deserialize(inputValue);
1289         }
1290
1291         simpleNode.setValue(outputValue);
1292     }
1293
1294     private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1295             final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1296         final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1297         checkNodeMultiplicityAccordingToSchema(schema, children);
1298         for (final NodeWrapper<? extends Object> child : children) {
1299             final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1300                     schema, child.getLocalName());
1301
1302             if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1303                 StringBuilder builder = new StringBuilder();
1304                 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1305                     builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1306                 }
1307
1308                 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1309                         + "\" is added as augment from more than one module. "
1310                         + "Therefore node must have namespace (XML format) or module name (JSON format)."
1311                         + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1312                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1313             }
1314
1315             boolean rightNodeSchemaFound = false;
1316             for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1317                 if (!rightNodeSchemaFound) {
1318                     final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1319                             currentAugment, mountPoint);
1320                     if (child.getQname() != null) {
1321                         this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1322                         rightNodeSchemaFound = true;
1323                     }
1324                 }
1325             }
1326
1327             if (!rightNodeSchemaFound) {
1328                 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1329                         + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1330             }
1331         }
1332
1333         if ((schema instanceof ListSchemaNode)) {
1334             ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1335             final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1336             for (final QName listKey : listKeys) {
1337                 boolean foundKey = false;
1338                 for (final NodeWrapper<? extends Object> child : children) {
1339                     if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1340                         foundKey = true;
1341                     }
1342                 }
1343
1344                 if (!foundKey) {
1345                     throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1346                             + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1347                             ErrorTag.DATA_MISSING);
1348                 }
1349             }
1350         }
1351     }
1352
1353     private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1354             final List<NodeWrapper<?>> nodes) {
1355         Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1356         for (NodeWrapper<?> child : nodes) {
1357             Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1358             equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1359         }
1360
1361         for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1362             if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1363                 String localName = childSchemaNode.getQName().getLocalName();
1364                 Integer count = equalNodeNamesToCounts.get(localName);
1365                 if (count != null && count > 1) {
1366                     throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1367                             + childSchemaNode.getQName().getLocalName()
1368                             + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1369                             ErrorTag.BAD_ELEMENT);
1370                 }
1371             }
1372         }
1373     }
1374
1375     private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1376             final QName previousAugment, final DOMMountPoint mountPoint) {
1377         QName validQName = schema.getQName();
1378         QName currentAugment = previousAugment;
1379         if (schema.isAugmenting()) {
1380             currentAugment = schema.getQName();
1381         } else if (previousAugment != null
1382                 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1383             validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1384         }
1385
1386         String moduleName = null;
1387         if (mountPoint == null) {
1388             moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1389         } else {
1390             moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1391         }
1392
1393         if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1394                 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1395             /*
1396              * || Note : this check is wrong -
1397              * can never be true as it compares
1398              * a URI with a String not sure what
1399              * the intention is so commented out
1400              * ... Objects . equal ( nodeBuilder
1401              * . getNamespace ( ) ,
1402              * MOUNT_POINT_MODULE_NAME )
1403              */
1404
1405             nodeBuilder.setQname(validQName);
1406         }
1407
1408         return currentAugment;
1409     }
1410
1411     private URI namespace(final Node<?> data) {
1412         if (data instanceof NodeWrapper) {
1413             return ((NodeWrapper<?>) data).getNamespace();
1414         } else if (data != null) {
1415             return data.getNodeType().getNamespace();
1416         } else {
1417             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1418         }
1419     }
1420
1421     private String localName(final Node<?> data) {
1422         if (data instanceof NodeWrapper) {
1423             return ((NodeWrapper<?>) data).getLocalName();
1424         } else if (data != null) {
1425             return data.getNodeType().getLocalName();
1426         } else {
1427             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1428         }
1429     }
1430
1431     private String getName(final Node<?> data) {
1432         if (data instanceof NodeWrapper) {
1433             return ((NodeWrapper<?>) data).getLocalName();
1434         } else if (data != null) {
1435             return data.getNodeType().getLocalName();
1436         } else {
1437             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1438         }
1439     }
1440
1441     private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1442         TypeDefinition<?> baseType = node.getType();
1443         while (baseType.getBaseType() != null) {
1444             baseType = baseType.getBaseType();
1445         }
1446
1447         return baseType;
1448     }
1449
1450     private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1451         TypeDefinition<?> baseType = node.getType();
1452         while (baseType.getBaseType() != null) {
1453             baseType = baseType.getBaseType();
1454         }
1455
1456         return baseType;
1457     }
1458
1459     private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1460         if (node instanceof LeafListSchemaNode) {
1461             return typeDefinition((LeafListSchemaNode) node);
1462         } else if (node instanceof LeafSchemaNode) {
1463             return _typeDefinition((LeafSchemaNode) node);
1464         } else if (node instanceof AnyXmlSchemaNode) {
1465             return null;
1466         } else {
1467             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1468         }
1469     }
1470
1471     private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1472         Node<?> nodes = null;
1473         if (dataNode == null) {
1474             throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1475                     "No data was found."));
1476         }
1477         nodes = DataNormalizer.toLegacy(dataNode);
1478         if (nodes != null) {
1479             if (nodes instanceof CompositeNode) {
1480                 return (CompositeNode) nodes;
1481             } else {
1482                 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1483             }
1484         } else {
1485             LOG.error("Top level node isn't of type Container or List schema node but "
1486                     + schema.getClass().getSimpleName());
1487         }
1488
1489         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1490                 "It wasn't possible to correctly interpret data."));
1491     }
1492
1493     private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1494             final DataSchemaNode schema) {
1495         List<Node<?>> lst = new ArrayList<Node<?>>();
1496         lst.add(compNode);
1497         if (schema instanceof ContainerSchemaNode) {
1498             return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1499                     .parse(lst, (ContainerSchemaNode) schema);
1500         } else if (schema instanceof ListSchemaNode) {
1501             return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1502                     .parse(lst, (ListSchemaNode) schema);
1503         }
1504
1505         LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1506
1507         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1508                 "It wasn't possible to translate specified data to datastore readable form."));
1509     }
1510
1511     private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1512             final InstanceIdentifierContext iiWithSchemaNode) {
1513         return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1514     }
1515
1516     private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1517             final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1518         return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1519                 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1520                 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1521     }
1522
1523     private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1524             final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1525         Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1526         final List<PathArgument> result = new ArrayList<PathArgument>();
1527         final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1528         while (iter.hasNext()) {
1529             final PathArgument pathArgument = iter.next();
1530             if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1531                 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1532             }
1533             result.add(pathArgument);
1534         }
1535         return YangInstanceIdentifier.create(result);
1536     }
1537
1538     private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1539             final DataSchemaNode schemaNode) {
1540         if (node instanceof CompositeNodeWrapper) {
1541             return (CompositeNodeWrapper) node;
1542         } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1543             final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1544             return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1545         }
1546
1547         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1548                 "Top level element has to be composite node or has to represent data container node."));
1549     }
1550
1551     private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1552         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1553             return true;
1554         }
1555         return false;
1556     }
1557
1558     public BigInteger getOperationalReceived() {
1559         // TODO Auto-generated method stub
1560         return null;
1561     }
1562 }