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