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