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