Merge "findModule method refactoring"
[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
895             String payloadName = this.getName(payload);
896             final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
897                     parentSchema, payloadName, module.getNamespace());
898             value = this.normalizeNode(payload, schemaNode, mountPoint);
899
900             iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
901         }
902
903         final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
904                 iiWithData.getSchemaNode());
905         DOMMountPoint mountPoint = iiWithData.getMountPoint();
906         YangInstanceIdentifier normalizedII;
907
908         try {
909             if (mountPoint != null) {
910                 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
911                         .getInstanceIdentifier());
912                 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
913             } else {
914                 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
915                 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
916             }
917         } catch(RestconfDocumentedException e) {
918             throw e;
919         } catch (Exception e) {
920             throw new RestconfDocumentedException("Error creating data", e);
921         }
922
923         return Response.status(Status.NO_CONTENT).build();
924     }
925
926     @Override
927     public Response createConfigurationData(final Node<?> payload) {
928         if (payload == null) {
929             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
930         }
931
932         URI payloadNS = this.namespace(payload);
933         if (payloadNS == null) {
934             throw new RestconfDocumentedException(
935                     "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
936                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
937         }
938
939         final Module module = this.findModule(null, payload);
940
941         String payloadName = this.getName(payload);
942         final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
943                 payloadName, module.getNamespace());
944         final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
945         final InstanceIdentifierContext iiWithData = this.addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
946         final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
947         DOMMountPoint mountPoint = iiWithData.getMountPoint();
948         YangInstanceIdentifier normalizedII;
949
950         try {
951             if (mountPoint != null) {
952                 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
953                         .getInstanceIdentifier());
954                 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
955
956             } else {
957                 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
958                 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
959             }
960         } catch(RestconfDocumentedException e) {
961             throw e;
962         } catch (Exception e) {
963             throw new RestconfDocumentedException("Error creating data", e);
964         }
965
966         return Response.status(Status.NO_CONTENT).build();
967     }
968
969     @Override
970     public Response deleteConfigurationData(final String identifier) {
971         final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
972         DOMMountPoint mountPoint = iiWithData.getMountPoint();
973         YangInstanceIdentifier normalizedII;
974
975         try {
976             if (mountPoint != null) {
977                 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
978                         .getInstanceIdentifier());
979                 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
980             } else {
981                 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
982                 broker.commitConfigurationDataDelete(normalizedII).get();
983             }
984         } catch (Exception e) {
985             final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
986                     Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
987             if (searchedException.isPresent()) {
988                 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
989             }
990             throw new RestconfDocumentedException("Error while deleting data", e);
991         }
992         return Response.status(Status.OK).build();
993     }
994
995     /**
996      * Subscribes to some path in schema context (stream) to listen on changes on this stream.
997      *
998      * Additional parameters for subscribing to stream are loaded via rpc input parameters:
999      * <ul>
1000      * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
1001      * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
1002      * </ul>
1003      */
1004     @Override
1005     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1006         final String streamName = Notificator.createStreamNameFromUri(identifier);
1007         if (Strings.isNullOrEmpty(streamName)) {
1008             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1009         }
1010
1011         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1012         if (listener == null) {
1013             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1014         }
1015
1016         Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1017         LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1018                 paramToValues.get(DATASTORE_PARAM_NAME));
1019         if (datastore == null) {
1020             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1021                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1022         }
1023         DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1024         if (scope == null) {
1025             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1026                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1027         }
1028
1029         broker.registerToListenDataChanges(datastore, scope, listener);
1030
1031         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1032         int notificationPort = NOTIFICATION_PORT;
1033         try {
1034             WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1035             notificationPort = webSocketServerInstance.getPort();
1036         } catch (NullPointerException e) {
1037             WebSocketServer.createInstance(NOTIFICATION_PORT);
1038         }
1039         UriBuilder port = uriBuilder.port(notificationPort);
1040         final URI uriToWebsocketServer = port.replacePath(streamName).build();
1041
1042         return Response.status(Status.OK).location(uriToWebsocketServer).build();
1043     }
1044
1045     /**
1046      * Load parameter for subscribing to stream from input composite node
1047      *
1048      * @param compNode
1049      *            contains value
1050      * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1051      */
1052     private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1053             final String paramName) {
1054         QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1055                 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1056         SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1057         if (simpleNode == null) {
1058             return null;
1059         }
1060         Object rawValue = simpleNode.getValue();
1061         if (!(rawValue instanceof String)) {
1062             return null;
1063         }
1064
1065         return resolveAsEnum(classDescriptor, (String) rawValue);
1066     }
1067
1068     /**
1069      * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1070      *
1071      * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1072      *         null.
1073      */
1074     private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1075         if (Strings.isNullOrEmpty(value)) {
1076             return null;
1077         }
1078         return resolveAsEnum(classDescriptor, value);
1079     }
1080
1081     private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1082         T[] enumConstants = classDescriptor.getEnumConstants();
1083         if (enumConstants != null) {
1084             for (T enm : classDescriptor.getEnumConstants()) {
1085                 if (((Enum<?>) enm).name().equals(value)) {
1086                     return enm;
1087                 }
1088             }
1089         }
1090         return null;
1091     }
1092
1093     private Map<String, String> resolveValuesFromUri(final String uri) {
1094         Map<String, String> result = new HashMap<>();
1095         String[] tokens = uri.split("/");
1096         for (int i = 1; i < tokens.length; i++) {
1097             String[] parameterTokens = tokens[i].split("=");
1098             if (parameterTokens.length == 2) {
1099                 result.put(parameterTokens[0], parameterTokens[1]);
1100             }
1101         }
1102         return result;
1103     }
1104
1105     private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1106         Module module = null;
1107         if (data instanceof NodeWrapper) {
1108             module = findModule(mountPoint, (NodeWrapper<?>) data);
1109         } else if (data != null) {
1110             URI namespace = data.getNodeType().getNamespace();
1111             if (mountPoint != null) {
1112                 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1113             } else {
1114                 module = this.controllerContext.findModuleByNamespace(namespace);
1115             }
1116         }
1117         if (module != null) {
1118             return module;
1119         }
1120         throw new RestconfDocumentedException(
1121                 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
1122                 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1123     }
1124
1125     private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1126         URI namespace = data.getNamespace();
1127         Preconditions.<URI> checkNotNull(namespace);
1128
1129         Module module = null;
1130         if (mountPoint != null) {
1131             module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1132             if (module == null) {
1133                 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1134             }
1135         } else {
1136             module = this.controllerContext.findModuleByNamespace(namespace);
1137             if (module == null) {
1138                 module = this.controllerContext.findModuleByName(namespace.toString());
1139             }
1140         }
1141
1142         return module;
1143     }
1144
1145     private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1146             final CompositeNode data, final DataSchemaNode schemaOfData, SchemaContext schemaContext) {
1147         YangInstanceIdentifier instanceIdentifier = null;
1148         if (identifierWithSchemaNode != null) {
1149             instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1150         }
1151
1152         final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1153         InstanceIdentifierBuilder iiBuilder = null;
1154         if (iiOriginal == null) {
1155             iiBuilder = YangInstanceIdentifier.builder();
1156         } else {
1157             iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1158         }
1159
1160         if ((schemaOfData instanceof ListSchemaNode)) {
1161             HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1162             iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1163         } else {
1164             iiBuilder.node(schemaOfData.getQName());
1165         }
1166
1167         YangInstanceIdentifier instance = iiBuilder.toInstance();
1168         DOMMountPoint mountPoint = null;
1169         SchemaContext schemaCtx = null;
1170         if (identifierWithSchemaNode != null) {
1171             mountPoint = identifierWithSchemaNode.getMountPoint();
1172         }
1173
1174         return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1175     }
1176
1177     private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1178         final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1179         List<QName> _keyDefinition = listNode.getKeyDefinition();
1180         for (final QName key : _keyDefinition) {
1181             SimpleNode<? extends Object> head = null;
1182             String localName = key.getLocalName();
1183             List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1184             if (simpleNodesByName != null) {
1185                 head = Iterables.getFirst(simpleNodesByName, null);
1186             }
1187
1188             Object dataNodeKeyValueObject = null;
1189             if (head != null) {
1190                 dataNodeKeyValueObject = head.getValue();
1191             }
1192
1193             if (dataNodeKeyValueObject == null) {
1194                 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1195                         + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1196                         ErrorTag.INVALID_VALUE);
1197             }
1198
1199             keyValues.put(key, dataNodeKeyValueObject);
1200         }
1201
1202         return keyValues;
1203     }
1204
1205     private boolean endsWithMountPoint(final String identifier) {
1206         return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1207     }
1208
1209     private boolean representsMountPointRootData(final Node<?> data) {
1210         URI namespace = this.namespace(data);
1211         return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1212          * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1213          * toString( ) )
1214          */)
1215          && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1216     }
1217
1218     private String addMountPointIdentifier(final String identifier) {
1219         boolean endsWith = identifier.endsWith("/");
1220         if (endsWith) {
1221             return (identifier + ControllerContext.MOUNT);
1222         }
1223
1224         return identifier + "/" + ControllerContext.MOUNT;
1225     }
1226
1227     private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1228         if (schema == null) {
1229             String localName = node == null ? null :
1230                     node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1231                     node.getNodeType().getLocalName();
1232
1233             throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1234                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1235         }
1236
1237         if (!(schema instanceof DataNodeContainer)) {
1238             throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1239                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1240         }
1241
1242         if ((node instanceof NodeWrapper<?>)) {
1243             NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1244             boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1245             if (isChangeAllowed) {
1246                 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1247                 try {
1248                     this.normalizeNode(nodeWrap, schema, null, mountPoint);
1249                 } catch (IllegalArgumentException e) {
1250                     RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1251                     restconfDocumentedException.addSuppressed(e);
1252                     throw restconfDocumentedException;
1253                 }
1254                 if (nodeWrap instanceof CompositeNodeWrapper) {
1255                     return ((CompositeNodeWrapper) nodeWrap).unwrap();
1256                 }
1257             }
1258         }
1259
1260         if (node instanceof CompositeNode) {
1261             return (CompositeNode) node;
1262         }
1263
1264         throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1265                 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1266     }
1267
1268     private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1269             final QName previousAugment, final DOMMountPoint mountPoint) {
1270         if (schema == null) {
1271             throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1272                     + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1273         }
1274
1275         QName currentAugment = null;
1276         if (nodeBuilder.getQname() != null) {
1277             currentAugment = previousAugment;
1278         } else {
1279             currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1280             if (nodeBuilder.getQname() == null) {
1281                 throw new RestconfDocumentedException(
1282                         "Data has bad format.\nIf data is in XML format then namespace for \""
1283                                 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1284                                 + "\".\n" + "If data is in JSON format then module name for \""
1285                                 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1286                                 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1287             }
1288         }
1289
1290         if (nodeBuilder instanceof CompositeNodeWrapper) {
1291             if (schema instanceof DataNodeContainer) {
1292                 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1293                         currentAugment);
1294             } else if (schema instanceof AnyXmlSchemaNode) {
1295                 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1296             }
1297         } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1298             normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1299         } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1300             normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1301         }
1302     }
1303
1304     private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1305         List<NodeWrapper<?>> children = compositeNode.getValues();
1306         for (NodeWrapper<? extends Object> child : children) {
1307             child.setNamespace(schema.getQName().getNamespace());
1308             if (child instanceof CompositeNodeWrapper) {
1309                 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1310             }
1311         }
1312     }
1313
1314     private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1315         if ((schema instanceof LeafSchemaNode)) {
1316             emptyNodeBuilder.setComposite(false);
1317         } else {
1318             if ((schema instanceof ContainerSchemaNode)) {
1319                 // FIXME: Add presence check
1320                 emptyNodeBuilder.setComposite(true);
1321             }
1322         }
1323     }
1324
1325     private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1326             final DOMMountPoint mountPoint) {
1327         final Object value = simpleNode.getValue();
1328         Object inputValue = value;
1329         TypeDef typeDef = this.typeDefinition(schema);
1330         TypeDefinition<? extends Object> typeDefinition = typeDef != null ? typeDef.typedef : null;
1331
1332         // For leafrefs, extract the type it is pointing to
1333         if(typeDefinition instanceof LeafrefTypeDefinition) {
1334             if (schema.getQName().equals(typeDef.qName)) {
1335                 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? this.controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema);
1336             } else {
1337                 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? this.controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), typeDef.qName);
1338             }
1339         }
1340
1341         if (typeDefinition instanceof IdentityrefTypeDefinition) {
1342             inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue);
1343         }
1344
1345         Object outputValue = inputValue;
1346
1347         if (typeDefinition != null) {
1348             Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1349             outputValue = codec == null ? null : codec.deserialize(inputValue);
1350         }
1351
1352         simpleNode.setValue(outputValue);
1353     }
1354
1355     private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) {
1356         if ((value instanceof String)) {
1357             inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1358                     (String) value);
1359         } // else value is already instance of IdentityValuesDTO
1360         return inputValue;
1361     }
1362
1363     private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1364             final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1365         final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1366         checkNodeMultiplicityAccordingToSchema(schema, children);
1367         for (final NodeWrapper<? extends Object> child : children) {
1368             final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1369                     schema, child.getLocalName());
1370
1371             if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1372                 StringBuilder builder = new StringBuilder();
1373                 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1374                     builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1375                 }
1376
1377                 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1378                         + "\" is added as augment from more than one module. "
1379                         + "Therefore node must have namespace (XML format) or module name (JSON format)."
1380                         + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1381                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1382             }
1383
1384             boolean rightNodeSchemaFound = false;
1385             for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1386                 if (!rightNodeSchemaFound) {
1387                     final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1388                             currentAugment, mountPoint);
1389                     if (child.getQname() != null) {
1390                         this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1391                         rightNodeSchemaFound = true;
1392                     }
1393                 }
1394             }
1395
1396             if (!rightNodeSchemaFound) {
1397                 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1398                         + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1399             }
1400         }
1401
1402         if ((schema instanceof ListSchemaNode)) {
1403             ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1404             final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1405             for (final QName listKey : listKeys) {
1406                 boolean foundKey = false;
1407                 for (final NodeWrapper<? extends Object> child : children) {
1408                     if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1409                         foundKey = true;
1410                     }
1411                 }
1412
1413                 if (!foundKey) {
1414                     throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1415                             + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1416                             ErrorTag.DATA_MISSING);
1417                 }
1418             }
1419         }
1420     }
1421
1422     private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1423             final List<NodeWrapper<?>> nodes) {
1424         Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1425         for (NodeWrapper<?> child : nodes) {
1426             Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1427             equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1428         }
1429
1430         for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1431             if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1432                 String localName = childSchemaNode.getQName().getLocalName();
1433                 Integer count = equalNodeNamesToCounts.get(localName);
1434                 if (count != null && count > 1) {
1435                     throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1436                             + childSchemaNode.getQName().getLocalName()
1437                             + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1438                             ErrorTag.BAD_ELEMENT);
1439                 }
1440             }
1441         }
1442     }
1443
1444     private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1445             final QName previousAugment, final DOMMountPoint mountPoint) {
1446         QName validQName = schema.getQName();
1447         QName currentAugment = previousAugment;
1448         if (schema.isAugmenting()) {
1449             currentAugment = schema.getQName();
1450         } else if (previousAugment != null
1451                 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1452             validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1453         }
1454
1455         String moduleName = null;
1456         if (mountPoint == null) {
1457             moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1458         } else {
1459             moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1460         }
1461
1462         if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1463                 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1464             /*
1465              * || Note : this check is wrong -
1466              * can never be true as it compares
1467              * a URI with a String not sure what
1468              * the intention is so commented out
1469              * ... Objects . equal ( nodeBuilder
1470              * . getNamespace ( ) ,
1471              * MOUNT_POINT_MODULE_NAME )
1472              */
1473
1474             nodeBuilder.setQname(validQName);
1475         }
1476
1477         return currentAugment;
1478     }
1479
1480     private URI namespace(final Node<?> data) {
1481         if (data instanceof NodeWrapper) {
1482             return ((NodeWrapper<?>) data).getNamespace();
1483         } else if (data != null) {
1484             return data.getNodeType().getNamespace();
1485         } else {
1486             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1487         }
1488     }
1489
1490     private String localName(final Node<?> data) {
1491         if (data instanceof NodeWrapper) {
1492             return ((NodeWrapper<?>) data).getLocalName();
1493         } else if (data != null) {
1494             return data.getNodeType().getLocalName();
1495         } else {
1496             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1497         }
1498     }
1499
1500     private String getName(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 TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
1511         TypeDefinition<?> baseType = type;
1512         QName qName = nodeQName;
1513         while (baseType.getBaseType() != null) {
1514             if (baseType instanceof ExtendedType) {
1515                 qName = baseType.getQName();
1516             }
1517             baseType = baseType.getBaseType();
1518         }
1519
1520         return new TypeDef(baseType, qName);
1521
1522     }
1523
1524     private TypeDef typeDefinition(final DataSchemaNode node) {
1525         if (node instanceof LeafListSchemaNode) {
1526             return typeDefinition(((LeafListSchemaNode)node).getType(), node.getQName());
1527         } else if (node instanceof LeafSchemaNode) {
1528             return typeDefinition(((LeafSchemaNode)node).getType(), node.getQName());
1529         } else if (node instanceof AnyXmlSchemaNode) {
1530             return null;
1531         } else {
1532             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1533         }
1534     }
1535
1536     private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1537         Node<?> nodes = null;
1538         if (dataNode == null) {
1539             throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1540                     "No data was found."));
1541         }
1542         nodes = DataNormalizer.toLegacy(dataNode);
1543         if (nodes != null) {
1544             if (nodes instanceof CompositeNode) {
1545                 return (CompositeNode) nodes;
1546             } else {
1547                 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1548             }
1549         } else {
1550             LOG.error("Top level node isn't of type Container or List schema node but "
1551                     + schema.getClass().getSimpleName());
1552         }
1553
1554         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1555                 "It wasn't possible to correctly interpret data."));
1556     }
1557
1558     private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1559             final DataSchemaNode schema) {
1560         List<Node<?>> lst = new ArrayList<Node<?>>();
1561         lst.add(compNode);
1562         if (schema instanceof ContainerSchemaNode) {
1563             return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1564                     .parse(lst, (ContainerSchemaNode) schema);
1565         } else if (schema instanceof ListSchemaNode) {
1566             return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1567                     .parse(lst, (ListSchemaNode) schema);
1568         }
1569
1570         LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1571
1572         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1573                 "It wasn't possible to translate specified data to datastore readable form."));
1574     }
1575
1576     private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1577             final InstanceIdentifierContext iiWithSchemaNode) {
1578         return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1579     }
1580
1581     private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1582             final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1583         return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1584                 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1585                 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1586     }
1587
1588     private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1589             final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1590         Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1591         final List<PathArgument> result = new ArrayList<PathArgument>();
1592         final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1593         while (iter.hasNext()) {
1594             final PathArgument pathArgument = iter.next();
1595             if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1596                 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1597             }
1598             result.add(pathArgument);
1599         }
1600         return YangInstanceIdentifier.create(result);
1601     }
1602
1603     private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1604             final DataSchemaNode schemaNode) {
1605         if (node instanceof CompositeNodeWrapper) {
1606             return (CompositeNodeWrapper) node;
1607         } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1608             final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1609             return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1610         }
1611
1612         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1613                 "Top level element has to be composite node or has to represent data container node."));
1614     }
1615
1616     private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1617         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1618             return true;
1619         }
1620         return false;
1621     }
1622
1623     public BigInteger getOperationalReceived() {
1624         // TODO Auto-generated method stub
1625         return null;
1626     }
1627 }