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