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