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