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