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