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