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