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