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