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