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