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