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