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