Bug 7686 - Make notifications defined by yangs automatic loaded
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / restful / utils / ReadDataTransactionUtil.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.restful.utils;
9
10 import static org.opendaylight.restconf.restful.utils.RestconfStreamsConstants.STREAMS_PATH;
11 import static org.opendaylight.restconf.restful.utils.RestconfStreamsConstants.STREAM_PATH_PART;
12
13 import com.google.common.base.Optional;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import java.net.URI;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.function.Function;
22 import java.util.stream.Collectors;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import javax.ws.rs.core.UriInfo;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
29 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
30 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
31 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
32 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
33 import org.opendaylight.netconf.sal.restconf.impl.WriterParameters;
34 import org.opendaylight.netconf.sal.restconf.impl.WriterParameters.WriterParametersBuilder;
35 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
36 import org.opendaylight.restconf.common.references.SchemaContextRef;
37 import org.opendaylight.restconf.restful.transaction.TransactionVarsWrapper;
38 import org.opendaylight.restconf.utils.mapping.RestconfMappingNodeUtil;
39 import org.opendaylight.restconf.utils.parser.ParserFieldsParameter;
40 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.QNameModule;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
63 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
64 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
69 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71
72 /**
73  * Util class for read data from data store via transaction.
74  * <ul>
75  * <li>config
76  * <li>state
77  * <li>all (config + state)
78  * </ul>
79  *
80  */
81 public final class ReadDataTransactionUtil {
82
83     private ReadDataTransactionUtil() {
84         throw new UnsupportedOperationException("Util class.");
85     }
86
87     /**
88      * Parse parameters from URI request and check their types and values.
89      *
90      *
91      * @param identifier
92      *            - {@link InstanceIdentifierContext}
93      * @param uriInfo
94      *            - URI info
95      * @param tagged
96      *            - set tagged for {@link WriterParameters}
97      * @return {@link WriterParameters}
98      */
99     public static @Nonnull WriterParameters parseUriParameters(@Nonnull final InstanceIdentifierContext<?> identifier,
100             @Nullable final UriInfo uriInfo, final boolean tagged) {
101         return parseParams(identifier, uriInfo, tagged);
102     }
103
104     /**
105      * Parse parameters from URI request and check their types and values.
106      *
107      *
108      * @param identifier
109      *            - {@link InstanceIdentifierContext}
110      * @param uriInfo
111      *            - URI info
112      * @return {@link WriterParameters}
113      */
114     public static @Nonnull WriterParameters parseUriParameters(@Nonnull final InstanceIdentifierContext<?> identifier,
115                                                                @Nullable final UriInfo uriInfo) {
116         return parseParams(identifier, uriInfo, false);
117     }
118
119     private static WriterParameters parseParams(final InstanceIdentifierContext<?> identifier, final UriInfo uriInfo,
120             final boolean tagged) {
121         final WriterParametersBuilder builder = new WriterParametersBuilder();
122         builder.setTagged(tagged);
123
124         if (uriInfo == null) {
125             return builder.build();
126         }
127
128         // check only allowed parameters
129         ParametersUtil.checkParametersTypes(
130                 RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
131                 uriInfo.getQueryParameters().keySet(),
132                 RestconfDataServiceConstant.ReadData.CONTENT,
133                 RestconfDataServiceConstant.ReadData.DEPTH,
134                 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
135
136         // read parameters from URI or set default values
137         final List<String> content = uriInfo.getQueryParameters().getOrDefault(
138                 RestconfDataServiceConstant.ReadData.CONTENT,
139                 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
140         final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
141                 RestconfDataServiceConstant.ReadData.DEPTH,
142                 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
143         // fields
144         final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
145                 RestconfDataServiceConstant.ReadData.FIELDS,
146                 Collections.emptyList());
147
148         // parameter can be in URI at most once
149         ParametersUtil.checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
150         ParametersUtil.checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
151         ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
152
153         // check and set content
154         final String contentValue = content.get(0);
155         if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
156             if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
157                     && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
158                 throw new RestconfDocumentedException(
159                         new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
160                                 "Invalid content parameter: " + contentValue, null,
161                                 "The content parameter value must be either config, nonconfig or all (default)"));
162             }
163         }
164
165         builder.setContent(content.get(0));
166
167         // check and set depth
168         if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
169             final Integer value = Ints.tryParse(depth.get(0));
170
171             if ((value == null)
172                     || (!((value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH)
173                         && (value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)))) {
174                 throw new RestconfDocumentedException(
175                         new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
176                                 "Invalid depth parameter: " + depth, null,
177                                 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
178             } else {
179                 builder.setDepth(value);
180             }
181         }
182
183         // check and set fields
184         if (!fields.isEmpty()) {
185             builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
186         }
187
188         return builder.build();
189     }
190
191     /**
192      * Read specific type of data from data store via transaction.
193      *
194      * @param valueOfContent
195      *            - type of data to read (config, state, all)
196      * @param transactionNode
197      *            - {@link TransactionVarsWrapper} - wrapper for variables
198      * @return {@link NormalizedNode}
199      */
200     public static @Nullable NormalizedNode<?, ?> readData(@Nonnull final String valueOfContent,
201             @Nonnull final TransactionVarsWrapper transactionNode) {
202         return readData(valueOfContent, transactionNode, null);
203     }
204
205     /**
206      * Read specific type of data from data store via transaction.
207      *
208      * @param valueOfContent
209      *            - type of data to read (config, state, all)
210      * @param transactionNode
211      *            - {@link TransactionVarsWrapper} - wrapper for variables
212      * @param withDefa
213      *            - vaule of with-defaults parameter
214      * @return {@link NormalizedNode}
215      */
216     public static @Nullable NormalizedNode<?, ?> readData(@Nonnull final String valueOfContent,
217             @Nonnull final TransactionVarsWrapper transactionNode, final String withDefa) {
218         switch (valueOfContent) {
219             case RestconfDataServiceConstant.ReadData.CONFIG:
220                 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
221                 if (withDefa == null) {
222                     return readDataViaTransaction(transactionNode);
223                 } else {
224                     return prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
225                             transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa);
226                 }
227             case RestconfDataServiceConstant.ReadData.NONCONFIG:
228                 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
229                 return readDataViaTransaction(transactionNode);
230
231             case RestconfDataServiceConstant.ReadData.ALL:
232                 return readAllData(transactionNode, withDefa);
233
234             default:
235                 throw new RestconfDocumentedException(
236                         new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
237                                 "Invalid content parameter: " + valueOfContent, null,
238                                 "The content parameter value must be either config, nonconfig or all (default)"));
239         }
240     }
241
242     private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
243             final YangInstanceIdentifier path, final String withDefa) {
244         boolean trim;
245         switch (withDefa) {
246             case "trim":
247                 trim = true;
248                 break;
249             case "explicit":
250                 trim = false;
251                 break;
252             default:
253                 throw new RestconfDocumentedException("");
254         }
255
256         final SchemaContext ctx = ControllerContext.getInstance().getGlobalSchema();
257         final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
258         final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
259         if (result instanceof ContainerNode) {
260             final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder =
261                     Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
262             buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
263             return builder.build();
264         } else {
265             final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
266                     Builders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
267             buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
268                     ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
269             return builder.build();
270         }
271     }
272
273     private static void buildMapEntryBuilder(
274             final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
275             final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
276             final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
277         for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
278             final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
279             final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
280             if (child instanceof ContainerNode) {
281                 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> childBuilder =
282                         Builders.containerBuilder((ContainerSchemaNode) childSchema);
283                 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
284                 builder.withChild(childBuilder.build());
285             } else if (child instanceof MapNode) {
286                 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
287                         Builders.mapBuilder((ListSchemaNode) childSchema);
288                 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
289                         ((ListSchemaNode) childSchema).getKeyDefinition());
290                 builder.withChild(childBuilder.build());
291             } else if (child instanceof LeafNode) {
292                 final String defaultVal = ((LeafSchemaNode) childSchema).getDefault();
293                 final String nodeVal = ((LeafNode<String>) child).getValue();
294                 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
295                         Builders.leafBuilder((LeafSchemaNode) childSchema);
296                 if (keys.contains(child.getNodeType())) {
297                     leafBuilder.withValue(((LeafNode) child).getValue());
298                     builder.withChild(leafBuilder.build());
299                 } else {
300                     if (trim) {
301                         if ((defaultVal == null) || !defaultVal.equals(nodeVal)) {
302                             leafBuilder.withValue(((LeafNode) child).getValue());
303                             builder.withChild(leafBuilder.build());
304                         }
305                     } else {
306                         if ((defaultVal != null) && defaultVal.equals(nodeVal)) {
307                             leafBuilder.withValue(((LeafNode) child).getValue());
308                             builder.withChild(leafBuilder.build());
309                         }
310                     }
311                 }
312             }
313         }
314     }
315
316     private static void buildList(final CollectionNodeBuilder<MapEntryNode, MapNode> builder, final MapNode result,
317             final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
318             final List<QName> keys) {
319         for (final MapEntryNode mapEntryNode : result.getValue()) {
320             final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
321             final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(actualNode).getDataSchemaNode();
322             final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
323                     Builders.mapEntryBuilder((ListSchemaNode) childSchema);
324             buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
325             builder.withChild(mapEntryBuilder.build());
326         }
327     }
328
329     private static void buildCont(final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder,
330             final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
331             final YangInstanceIdentifier actualPath, final boolean trim) {
332         for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
333             final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
334             final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
335             if (child instanceof ContainerNode) {
336                 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builderChild =
337                         Builders.containerBuilder((ContainerSchemaNode) childSchema);
338                 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
339                 builder.withChild(builderChild.build());
340             } else if (child instanceof MapNode) {
341                 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
342                         Builders.mapBuilder((ListSchemaNode) childSchema);
343                 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
344                         ((ListSchemaNode) childSchema).getKeyDefinition());
345                 builder.withChild(childBuilder.build());
346             } else if (child instanceof LeafNode) {
347                 final String defaultVal = ((LeafSchemaNode) childSchema).getDefault();
348                 final String nodeVal = ((LeafNode<String>) child).getValue();
349                 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
350                         Builders.leafBuilder((LeafSchemaNode) childSchema);
351                 if (trim) {
352                     if ((defaultVal == null) || !defaultVal.equals(nodeVal)) {
353                         leafBuilder.withValue(((LeafNode) child).getValue());
354                         builder.withChild(leafBuilder.build());
355                     }
356                 } else {
357                     if ((defaultVal != null) && defaultVal.equals(nodeVal)) {
358                         leafBuilder.withValue(((LeafNode) child).getValue());
359                         builder.withChild(leafBuilder.build());
360                     }
361                 }
362             }
363         }
364     }
365
366     /**
367      * If is set specific {@link LogicalDatastoreType} in
368      * {@link TransactionVarsWrapper}, then read this type of data from DS. If
369      * don't, we have to read all data from DS (state + config)
370      *
371      * @param transactionNode
372      *            - {@link TransactionVarsWrapper} - wrapper for variables
373      * @return {@link NormalizedNode}
374      */
375     private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
376             @Nonnull final TransactionVarsWrapper transactionNode) {
377         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> listenableFuture = transactionNode
378                 .getTransactionChain().newReadOnlyTransaction().read(transactionNode.getLogicalDatastoreType(),
379                         transactionNode.getInstanceIdentifier().getInstanceIdentifier());
380         final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
381         FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
382                 dataFactory);
383         return dataFactory.build();
384     }
385
386     /**
387      * Read config and state data, then map them.
388      *
389      * @param transactionNode
390      *            - {@link TransactionVarsWrapper} - wrapper for variables
391      * @param withDefa
392      * @return {@link NormalizedNode}
393      */
394     private static @Nullable NormalizedNode<?, ?> readAllData(@Nonnull final TransactionVarsWrapper transactionNode,
395             final String withDefa) {
396         // PREPARE STATE DATA NODE
397         transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
398         final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(transactionNode);
399
400         // PREPARE CONFIG DATA NODE
401         transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
402         final NormalizedNode<?, ?> configDataNode;
403         if (withDefa == null) {
404             configDataNode = readDataViaTransaction(transactionNode);
405         } else {
406             configDataNode = prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
407                     transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa);
408         }
409
410         // if no data exists
411         if ((stateDataNode == null) && (configDataNode == null)) {
412             return null;
413         }
414
415         // return config data
416         if (stateDataNode == null) {
417             return configDataNode;
418         }
419
420         // return state data
421         if (configDataNode == null) {
422             return stateDataNode;
423         }
424
425         // merge data from config and state
426         return mapNode(stateDataNode, configDataNode);
427     }
428
429     /**
430      * Map data by type of read node.
431      *
432      * @param stateDataNode
433      *            - data node of state data
434      * @param configDataNode
435      *            - data node of config data
436      * @return {@link NormalizedNode}
437      */
438     private static @Nonnull NormalizedNode<?, ?> mapNode(@Nonnull final NormalizedNode<?, ?> stateDataNode,
439                                                          @Nonnull final NormalizedNode<?, ?> configDataNode) {
440         validPossibilityOfMergeNodes(stateDataNode, configDataNode);
441         if (configDataNode instanceof RpcDefinition) {
442             return prepareRpcData(configDataNode, stateDataNode);
443         } else {
444             return prepareData(configDataNode, stateDataNode);
445         }
446     }
447
448     /**
449      * Valid of can be data merged together.
450      *
451      * @param stateDataNode
452      *            - data node of state data
453      * @param configDataNode
454      *            - data node of config data
455      */
456     private static void validPossibilityOfMergeNodes(@Nonnull final NormalizedNode<?, ?> stateDataNode,
457                                                      @Nonnull final NormalizedNode<?, ?> configDataNode) {
458         final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
459         final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
460         if (moduleOfStateData != moduleOfConfigData) {
461             throw new RestconfDocumentedException("It is not possible to merge ");
462         }
463     }
464
465     /**
466      * Prepare and map data for rpc
467      *
468      * @param configDataNode
469      *            - data node of config data
470      * @param stateDataNode
471      *            - data node of state data
472      * @return {@link NormalizedNode}
473      */
474     private static @Nonnull NormalizedNode<?, ?> prepareRpcData(@Nonnull final NormalizedNode<?, ?> configDataNode,
475                                                                 @Nonnull final NormalizedNode<?, ?> stateDataNode) {
476         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
477                 .mapEntryBuilder();
478         mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
479
480         // MAP CONFIG DATA
481         mapRpcDataNode(configDataNode, mapEntryBuilder);
482         // MAP STATE DATA
483         mapRpcDataNode(stateDataNode, mapEntryBuilder);
484
485         return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
486     }
487
488     /**
489      * Map node to map entry builder.
490      *
491      * @param dataNode
492      *            - data node
493      * @param mapEntryBuilder
494      *            - builder for mapping data
495      */
496     private static void mapRpcDataNode(@Nonnull final NormalizedNode<?, ?> dataNode,
497                                        @Nonnull final DataContainerNodeBuilder<
498                                                NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
499         ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
500     }
501
502     /**
503      * Prepare and map all data from DS
504      *
505      * @param configDataNode
506      *            - data node of config data
507      * @param stateDataNode
508      *            - data node of state data
509      * @return {@link NormalizedNode}
510      */
511     private static @Nonnull NormalizedNode<?, ?> prepareData(@Nonnull final NormalizedNode<?, ?> configDataNode,
512                                                              @Nonnull final NormalizedNode<?, ?> stateDataNode) {
513         if (configDataNode instanceof MapNode) {
514             final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
515                     .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
516
517             mapValueToBuilder(
518                     ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
519
520             return builder.build();
521         } else if (configDataNode instanceof MapEntryNode) {
522             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
523                     .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
524
525             mapValueToBuilder(
526                     ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
527
528             return builder.build();
529         } else if (configDataNode instanceof ContainerNode) {
530             final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = Builders
531                     .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
532
533             mapValueToBuilder(
534                     ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
535
536             return builder.build();
537         } else if (configDataNode instanceof AugmentationNode) {
538             final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
539                     .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
540
541             mapValueToBuilder(
542                     ((AugmentationNode) configDataNode).getValue(), ((AugmentationNode) stateDataNode).getValue(), builder);
543
544             return builder.build();
545         } else if (configDataNode instanceof ChoiceNode) {
546             final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
547                     .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
548
549             mapValueToBuilder(
550                     ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
551
552             return builder.build();
553         } else if (configDataNode instanceof LeafNode) {
554             return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
555         } else {
556             throw new RestconfDocumentedException("Bad type of node.");
557         }
558     }
559
560     /**
561      * Map value from container node to builder.
562      *
563      * @param configData
564      *            - collection of config data nodes
565      * @param stateData
566      *            - collection of state data nodes
567      * @param builder
568      *            - builder
569      */
570     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
571             @Nonnull final Collection<T> configData,
572             @Nonnull final Collection<T> stateData,
573             @Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
574         final Map<PathArgument, T> configMap = configData.stream().collect(
575                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
576         final Map<PathArgument, T> stateMap = stateData.stream().collect(
577                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
578
579         // merge config and state data of children with different identifiers
580         mapDataToBuilder(configMap, stateMap, builder);
581
582         // merge config and state data of children with the same identifiers
583         mergeDataToBuilder(configMap, stateMap, builder);
584     }
585
586     /**
587      * Map data with different identifiers to builder. Data with different identifiers can be just added
588      * as childs to parent node.
589      *
590      * @param configMap
591      *            - map of config data nodes
592      * @param stateMap
593      *            - map of state data nodes
594      * @param builder
595      *           - builder
596      */
597     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
598             @Nonnull final Map<PathArgument, T> configMap,
599             @Nonnull final Map<PathArgument, T> stateMap,
600             @Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
601         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
602                 y -> builder.addChild(y.getValue()));
603         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
604                 y -> builder.addChild(y.getValue()));
605     }
606
607     /**
608      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
609      * go one level down with {@code prepareData} method.
610      *
611      * @param configMap
612      *            - immutable config data
613      * @param stateMap
614      *            - immutable state data
615      * @param builder
616      *           - builder
617      */
618     @SuppressWarnings("unchecked")
619     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
620             @Nonnull final Map<PathArgument, T> configMap,
621             @Nonnull final Map<PathArgument, T> stateMap,
622             @Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
623         // it is enough to process only config data because operational contains the same data
624         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
625                 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
626     }
627
628     /**
629      * Read specific type of data from data store via transaction and if identifier read data from
630      * streams then put streams from actual schema context to datastore.
631      *
632      * @param identifier
633      *            - identifier of data to read
634      * @param content
635      *            - type of data to read (config, state, all)
636      * @param transactionNode
637      *            - {@link TransactionVarsWrapper} - wrapper for variables
638      * @param withDefa
639      *            - vaule of with-defaults parameter
640      * @param schemaContextRef
641      *            - schema context
642      * @param uriInfo
643      *            - uri info
644      * @return {@link NormalizedNode}
645      */
646     public static NormalizedNode<?, ?> readData(final String identifier, final String content,
647             final TransactionVarsWrapper transactionNode, final String withDefa,
648             final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
649         if (identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
650             final DOMDataReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
651             final SchemaContext schemaContext = schemaContextRef.get();
652             final boolean exist = SubscribeToStreamUtil.checkExist(schemaContext, wTx);
653
654             for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
655                 final List<NotificationListenerAdapter> notifiStreamXML =
656                         CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
657                                 NotificationOutputType.XML.getName());
658                 final List<NotificationListenerAdapter> notifiStreamJSON =
659                         CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
660                                 NotificationOutputType.JSON.getName());
661                 notifiStreamJSON.addAll(notifiStreamXML);
662
663                 for (final NotificationListenerAdapter listener : notifiStreamJSON) {
664                     final URI uri = SubscribeToStreamUtil.prepareUriByStreamName(uriInfo, listener.getStreamName());
665                     final NormalizedNode mapToStreams =
666                             RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
667                                     listener.getSchemaPath().getLastComponent(), schemaContext.getNotifications(),
668                                     null, listener.getOutputType(), uri,
669                                     SubscribeToStreamUtil.getMonitoringModule(schemaContext), exist);
670                     SubscribeToStreamUtil.writeDataToDS(schemaContext,
671                             listener.getSchemaPath().getLastComponent().getLocalName(), wTx, exist,
672                             mapToStreams);
673                 }
674             }
675             SubscribeToStreamUtil.submitData(wTx);
676         }
677         return readData(content, transactionNode, withDefa);
678     }
679 }