Bind Insert point PathArgument earlier
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / transactions / RestconfStrategy.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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.nb.rfc8040.rests.transactions;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.NoSuchElementException;
22 import java.util.Optional;
23 import java.util.function.Function;
24 import java.util.stream.Collectors;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.common.api.CommitInfo;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
30 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
31 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
32 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
33 import org.opendaylight.restconf.api.query.ContentParam;
34 import org.opendaylight.restconf.api.query.WithDefaultsParam;
35 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
36 import org.opendaylight.restconf.common.errors.RestconfError;
37 import org.opendaylight.restconf.common.errors.RestconfFuture;
38 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
39 import org.opendaylight.restconf.common.patch.PatchContext;
40 import org.opendaylight.restconf.common.patch.PatchStatusContext;
41 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
42 import org.opendaylight.restconf.nb.rfc8040.Insert;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
44 import org.opendaylight.yangtools.yang.common.Empty;
45 import org.opendaylight.yangtools.yang.common.ErrorTag;
46 import org.opendaylight.yangtools.yang.common.ErrorType;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
56 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
62 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
73 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
74 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
75 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
77 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 /**
85  * Baseline execution strategy for various RESTCONF operations.
86  *
87  * @see NetconfRestconfStrategy
88  * @see MdsalRestconfStrategy
89  */
90 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
91 //        operations. This should be handled through proper allocation indirection.
92 public abstract class RestconfStrategy {
93     /**
94      * Result of a {@code PUT} request as defined in
95      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.5">RFC8040 section 4.5</a>. The definition makes it
96      * clear that the logical operation is {@code create-or-replace}.
97      */
98     public enum CreateOrReplaceResult {
99         /**
100          * A new resource has been created.
101          */
102         CREATED,
103         /*
104          * An existing resources has been replaced.
105          */
106         REPLACED;
107     }
108
109     private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
110
111     private final @NonNull EffectiveModelContext modelContext;
112
113     RestconfStrategy(final EffectiveModelContext modelContext) {
114         this.modelContext = requireNonNull(modelContext);
115     }
116
117     /**
118      * Look up the appropriate strategy for a particular mount point.
119      *
120      * @param modelContext {@link EffectiveModelContext} of target mount point
121      * @param mountPoint Target mount point
122      * @return A strategy, or null if the mount point does not expose a supported interface
123      * @throws NullPointerException if any argument is {@code null}
124      */
125     public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
126             final DOMMountPoint mountPoint) {
127         final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
128         if (netconfService.isPresent()) {
129             return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow());
130         }
131         final var dataBroker = mountPoint.getService(DOMDataBroker.class);
132         if (dataBroker.isPresent()) {
133             return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow());
134         }
135         return null;
136     }
137
138     public final @NonNull EffectiveModelContext modelContext() {
139         return modelContext;
140     }
141
142     /**
143      * Lock the entire datastore.
144      *
145      * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
146      *         anything else.
147      */
148     abstract RestconfTransaction prepareWriteExecution();
149
150     /**
151      * Read data from the datastore.
152      *
153      * @param store the logical data store which should be modified
154      * @param path the data object path
155      * @return a ListenableFuture containing the result of the read
156      */
157     abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
158
159     /**
160      * Read data selected using fields from the datastore.
161      *
162      * @param store the logical data store which should be modified
163      * @param path the parent data object path
164      * @param fields paths to selected fields relative to parent path
165      * @return a ListenableFuture containing the result of the read
166      */
167     abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
168         List<YangInstanceIdentifier> fields);
169
170     /**
171      * Check if data already exists in the configuration datastore.
172      *
173      * @param path the data object path
174      * @return a ListenableFuture containing the result of the check
175      */
176     // FIXME: this method should be hosted in RestconfTransaction
177     // FIXME: this method should only be needed in MdsalRestconfStrategy
178     abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
179
180     /**
181      * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
182      * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
183      *
184      * @param path Path to delete
185      * @return A {@link RestconfFuture}
186      * @throws NullPointerException if {@code path} is {@code null}
187      */
188     public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
189         final var ret = new SettableRestconfFuture<Empty>();
190         delete(ret, requireNonNull(path));
191         return ret;
192     }
193
194     abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
195
196     /**
197      * Merge data into the configuration datastore, as outlined in
198      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
199      *
200      * @param path Path to merge
201      * @param data Data to merge
202      * @return A {@link RestconfFuture}
203      * @throws NullPointerException if any argument is {@code null}
204      */
205     public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
206         final var ret = new SettableRestconfFuture<Empty>();
207         merge(ret, requireNonNull(path), requireNonNull(data));
208         return ret;
209     }
210
211     private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
212             final @NonNull NormalizedNode data) {
213         final var tx = prepareWriteExecution();
214         // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
215         tx.ensureParentsByMerge(path);
216         tx.merge(path, data);
217         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
218             @Override
219             public void onSuccess(final CommitInfo result) {
220                 future.set(Empty.value());
221             }
222
223             @Override
224             public void onFailure(final Throwable cause) {
225                 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path));
226             }
227         }, MoreExecutors.directExecutor());
228     }
229
230     /**
231      * Check mount point and prepare variables for put data to DS.
232      *
233      * @param path    path of data
234      * @param data    data
235      * @param insert  {@link Insert}
236      * @return A {@link CreateOrReplaceResult}
237      */
238     public final @NonNull CreateOrReplaceResult putData(final YangInstanceIdentifier path, final NormalizedNode data,
239             final @Nullable Insert insert) {
240         final var exists = TransactionUtil.syncAccess(exists(path), path);
241
242         final ListenableFuture<? extends CommitInfo> commitFuture;
243         if (insert != null) {
244             final var parentPath = path.coerceParent();
245             checkListAndOrderedType(parentPath);
246             commitFuture = insertAndCommitPut(path, data, insert, parentPath);
247         } else {
248             commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
249         }
250
251         TransactionUtil.syncCommit(commitFuture, "PUT", path);
252         return exists ? CreateOrReplaceResult.REPLACED : CreateOrReplaceResult.CREATED;
253     }
254
255     private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
256             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
257         final var tx = prepareWriteExecution();
258
259         return switch (insert.insert()) {
260             case FIRST -> {
261                 final var readData = tx.readList(parentPath);
262                 if (readData == null || readData.isEmpty()) {
263                     yield replaceAndCommit(tx, path, data);
264                 }
265                 tx.remove(parentPath);
266                 tx.replace(path, data);
267                 tx.replace(parentPath, readData);
268                 yield tx.commit();
269             }
270             case LAST -> replaceAndCommit(tx, path, data);
271             case BEFORE -> {
272                 final var readData = tx.readList(parentPath);
273                 if (readData == null || readData.isEmpty()) {
274                     yield replaceAndCommit(tx, path, data);
275                 }
276                 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
277                 yield tx.commit();
278             }
279             case AFTER -> {
280                 final var readData = tx.readList(parentPath);
281                 if (readData == null || readData.isEmpty()) {
282                     yield replaceAndCommit(tx, path, data);
283                 }
284                 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
285                 yield tx.commit();
286             }
287         };
288     }
289
290     private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
291             final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
292             final boolean before) {
293         tx.remove(path.getParent());
294
295         int lastItemPosition = 0;
296         for (var nodeChild : readList.body()) {
297             if (nodeChild.name().equals(pointArg)) {
298                 break;
299             }
300             lastItemPosition++;
301         }
302         if (!before) {
303             lastItemPosition++;
304         }
305
306         int lastInsertedPosition = 0;
307         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, path.getParent());
308         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
309         for (var nodeChild : readList.body()) {
310             if (lastInsertedPosition == lastItemPosition) {
311                 tx.replace(path, data);
312             }
313             final var childPath = path.coerceParent().node(nodeChild.name());
314             tx.replace(childPath, nodeChild);
315             lastInsertedPosition++;
316         }
317     }
318
319     private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
320             final YangInstanceIdentifier path, final NormalizedNode data) {
321         tx.replace(path, data);
322         return tx.commit();
323     }
324
325     private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
326         // FIXME: we have this available in InstanceIdentifierContext
327         final var dataSchemaNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow()
328             .dataSchemaNode();
329
330         final String message;
331         if (dataSchemaNode instanceof ListSchemaNode listSchema) {
332             if (listSchema.isUserOrdered()) {
333                 return listSchema;
334             }
335             message = "Insert parameter can be used only with ordered-by user list.";
336         } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
337             if (leafListSchema.isUserOrdered()) {
338                 return leafListSchema;
339             }
340             message = "Insert parameter can be used only with ordered-by user leaf-list.";
341         } else {
342             message = "Insert parameter can be used only with list or leaf-list";
343         }
344         throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
345     }
346
347     /**
348      * Check mount point and prepare variables for post data.
349      *
350      * @param path    path
351      * @param data    data
352      * @param insert  {@link Insert}
353      */
354     public final void postData(final YangInstanceIdentifier path, final NormalizedNode data,
355             final @Nullable Insert insert) {
356         final ListenableFuture<? extends CommitInfo> future;
357         if (insert != null) {
358             final var parentPath = path.coerceParent();
359             checkListAndOrderedType(parentPath);
360             future = insertAndCommitPost(path, data, insert, parentPath);
361         } else {
362             future = createAndCommit(prepareWriteExecution(), path, data);
363         }
364         TransactionUtil.syncCommit(future, "POST", path);
365     }
366
367     private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
368             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
369         final var grandParent = parent.coerceParent();
370         final var tx = prepareWriteExecution();
371
372         return switch (insert.insert()) {
373             case FIRST -> {
374                 final var readData = tx.readList(grandParent);
375                 if (readData == null || readData.isEmpty()) {
376                     tx.replace(path, data);
377                 } else {
378                     checkItemDoesNotExists(exists(path), path);
379                     tx.remove(grandParent);
380                     tx.replace(path, data);
381                     tx.replace(grandParent, readData);
382                 }
383                 yield tx.commit();
384             }
385             case LAST -> createAndCommit(tx, path, data);
386             case BEFORE -> {
387                 final var readData = tx.readList(grandParent);
388                 if (readData == null || readData.isEmpty()) {
389                     tx.replace(path, data);
390                 } else {
391                     checkItemDoesNotExists(exists(path), path);
392                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
393                 }
394                 yield tx.commit();
395             }
396             case AFTER -> {
397                 final var readData = tx.readList(grandParent);
398                 if (readData == null || readData.isEmpty()) {
399                     tx.replace(path, data);
400                 } else {
401                     checkItemDoesNotExists(exists(path), path);
402                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
403                 }
404                 yield tx.commit();
405             }
406         };
407     }
408
409     /**
410      * Process edit operations of one {@link PatchContext}.
411      *
412      * @param patch Patch context to be processed
413      * @return {@link PatchStatusContext}
414      */
415     public final @NonNull PatchStatusContext patchData(final PatchContext patch) {
416         final var editCollection = new ArrayList<PatchStatusEntity>();
417         final var tx = prepareWriteExecution();
418
419         boolean noError = true;
420         for (var patchEntity : patch.entities()) {
421             if (noError) {
422                 final var targetNode = patchEntity.getTargetNode();
423                 final var editId = patchEntity.getEditId();
424
425                 switch (patchEntity.getOperation()) {
426                     case Create:
427                         try {
428                             tx.create(targetNode, patchEntity.getNode());
429                             editCollection.add(new PatchStatusEntity(editId, true, null));
430                         } catch (RestconfDocumentedException e) {
431                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
432                             noError = false;
433                         }
434                         break;
435                     case Delete:
436                         try {
437                             tx.delete(targetNode);
438                             editCollection.add(new PatchStatusEntity(editId, true, null));
439                         } catch (RestconfDocumentedException e) {
440                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
441                             noError = false;
442                         }
443                         break;
444                     case Merge:
445                         try {
446                             tx.ensureParentsByMerge(targetNode);
447                             tx.merge(targetNode, patchEntity.getNode());
448                             editCollection.add(new PatchStatusEntity(editId, true, null));
449                         } catch (RestconfDocumentedException e) {
450                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
451                             noError = false;
452                         }
453                         break;
454                     case Replace:
455                         try {
456                             tx.replace(targetNode, patchEntity.getNode());
457                             editCollection.add(new PatchStatusEntity(editId, true, null));
458                         } catch (RestconfDocumentedException e) {
459                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
460                             noError = false;
461                         }
462                         break;
463                     case Remove:
464                         try {
465                             tx.remove(targetNode);
466                             editCollection.add(new PatchStatusEntity(editId, true, null));
467                         } catch (RestconfDocumentedException e) {
468                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
469                             noError = false;
470                         }
471                         break;
472                     default:
473                         editCollection.add(new PatchStatusEntity(editId, false, List.of(
474                             new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
475                                 "Not supported Yang Patch operation"))));
476                         noError = false;
477                         break;
478                 }
479             } else {
480                 break;
481             }
482         }
483
484         // if no errors then submit transaction, otherwise cancel
485         final var patchId = patch.patchId();
486         if (noError) {
487             try {
488                 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
489             } catch (RestconfDocumentedException e) {
490                 // if errors occurred during transaction commit then patch failed and global errors are reported
491                 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), false, e.getErrors());
492             }
493
494             return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), true, null);
495         } else {
496             tx.cancel();
497             return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), false, null);
498         }
499     }
500
501     private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
502             final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
503             final YangInstanceIdentifier grandParentPath, final boolean before) {
504         tx.remove(grandParentPath);
505
506         int lastItemPosition = 0;
507         for (var nodeChild : readList.body()) {
508             if (nodeChild.name().equals(pointArg)) {
509                 break;
510             }
511             lastItemPosition++;
512         }
513         if (!before) {
514             lastItemPosition++;
515         }
516
517         int lastInsertedPosition = 0;
518         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, grandParentPath);
519         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
520         for (var nodeChild : readList.body()) {
521             if (lastInsertedPosition == lastItemPosition) {
522                 tx.replace(path, data);
523             }
524             tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
525             lastInsertedPosition++;
526         }
527     }
528
529     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
530             final YangInstanceIdentifier path, final NormalizedNode data) {
531         try {
532             tx.create(path, data);
533         } catch (RestconfDocumentedException e) {
534             // close transaction if any and pass exception further
535             tx.cancel();
536             throw e;
537         }
538
539         return tx.commit();
540     }
541
542     /**
543      * Check if items do NOT already exists at specified {@code path}.
544      *
545      * @param existsFuture if checked data exists
546      * @param path         Path to be checked
547      * @throws RestconfDocumentedException if data already exists.
548      */
549     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
550             final YangInstanceIdentifier path) {
551         if (TransactionUtil.syncAccess(existsFuture, path)) {
552             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
553             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
554                 path);
555         }
556     }
557
558     /**
559      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
560      * inside of object {@link RestconfStrategy} provided as a parameter.
561      *
562      * @param content      type of data to read (config, state, all)
563      * @param path         the path to read
564      * @param defaultsMode value of with-defaults parameter
565      * @return {@link NormalizedNode}
566      */
567     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
568             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
569         return switch (content) {
570             case ALL -> {
571                 // PREPARE STATE DATA NODE
572                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
573                 // PREPARE CONFIG DATA NODE
574                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
575
576                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
577                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
578             }
579             case CONFIG -> {
580                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
581                 yield defaultsMode == null ? read
582                     : prepareDataByParamWithDef(read, path, defaultsMode.mode());
583             }
584             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
585         };
586     }
587
588     /**
589      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
590      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
591      *
592      * @param content  type of data to read (config, state, all)
593      * @param path     the parent path to read
594      * @param withDefa value of with-defaults parameter
595      * @param fields   paths to selected subtrees which should be read, relative to to the parent path
596      * @return {@link NormalizedNode}
597      */
598     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
599             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
600             final @NonNull List<YangInstanceIdentifier> fields) {
601         return switch (content) {
602             case ALL -> {
603                 // PREPARE STATE DATA NODE
604                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
605                 // PREPARE CONFIG DATA NODE
606                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
607
608                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
609                     : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
610             }
611             case CONFIG -> {
612                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
613                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
614             }
615             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
616         };
617     }
618
619     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
620             final YangInstanceIdentifier path) {
621         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
622     }
623
624     /**
625      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
626      * specified subtrees that should only be read.
627      *
628      * @param store                 datastore type
629      * @param path                  parent path to selected fields
630      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
631      *                              in {@link RestconfStrategy} if any
632      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
633      * @return {@link NormalizedNode}
634      */
635     private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
636             final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
637         return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
638     }
639
640     private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
641             final WithDefaultsMode defaultsMode) {
642         final boolean trim = switch (defaultsMode) {
643             case Trim -> true;
644             case Explicit -> false;
645             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
646                 "Unsupported with-defaults value " + defaultsMode.getName());
647         };
648
649         // FIXME: we have this readily available in InstanceIdentifierContext
650         final var ctxNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow();
651         if (readData instanceof ContainerNode container) {
652             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
653             buildCont(builder, container.body(), ctxNode, trim);
654             return builder.build();
655         } else if (readData instanceof MapEntryNode mapEntry) {
656             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
657                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
658             }
659
660             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
661             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
662             return builder.build();
663         } else {
664             throw new IllegalStateException("Unhandled data contract " + readData.contract());
665         }
666     }
667
668     private static void buildMapEntryBuilder(
669             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
670             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
671             final boolean trim, final List<QName> keys) {
672         for (var child : children) {
673             final var childCtx = getChildContext(ctxNode, child);
674
675             if (child instanceof ContainerNode container) {
676                 appendContainer(builder, container, childCtx, trim);
677             } else if (child instanceof MapNode map) {
678                 appendMap(builder, map, childCtx, trim);
679             } else if (child instanceof LeafNode<?> leaf) {
680                 appendLeaf(builder, leaf, childCtx, trim, keys);
681             } else {
682                 // FIXME: we should never hit this, throw an ISE if this ever happens
683                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
684             }
685         }
686     }
687
688     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
689             final DataSchemaContext ctxNode, final boolean trim) {
690         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
691         buildCont(childBuilder, container.body(), ctxNode, trim);
692         builder.withChild(childBuilder.build());
693     }
694
695     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
696             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
697         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
698             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
699         }
700
701         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
702         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
703
704         // This is a combined check for when we need to emit the leaf.
705         if (
706             // We always have to emit key leaf values
707             keys.contains(leafSchema.getQName())
708             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
709             //
710             //            When data is retrieved with a <with-defaults> parameter equal to
711             //            'trim', data nodes MUST NOT be reported if they contain the schema
712             //            default value.  Non-configuration data nodes containing the schema
713             //            default value MUST NOT be reported.
714             //
715             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
716             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
717             // grasp what we are doing here... emit only if it matches default ???!!!
718             // FIXME: The WithDefaultsParam.EXPLICIT says:
719             //
720             //            Data nodes set to the YANG default by the client are reported.
721             //
722             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
723             //
724             //            If the "with-defaults" parameter is set to "explicit", then the
725             //            server MUST adhere to the default-reporting behavior defined in
726             //            Section 3.3 of [RFC6243].
727             //
728             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
729             //
730             //            When data is retrieved with a <with-defaults> parameter equal to
731             //            'explicit', a data node that was set by a client to its schema
732             //            default value MUST be reported.  A conceptual data node that would be
733             //            set by the server to the schema default value MUST NOT be reported.
734             //            Non-configuration data nodes containing the schema default value MUST
735             //            be reported.
736             //
737             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
738             //            This seems to disregard the 'trim = true' case semantics (see above).
739             //            Combining the above, though, these checks are missing the 'non-config' check, which would
740             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
741             //            Without that input, this really should be  covered by the previous case.
742                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
743             builder.withChild(leaf);
744         }
745     }
746
747     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
748             final DataSchemaContext childCtx, final boolean trim) {
749         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
750             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
751         }
752
753         final var childBuilder = switch (map.ordering()) {
754             case SYSTEM -> Builders.mapBuilder();
755             case USER -> Builders.orderedMapBuilder();
756         };
757         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
758             listSchema.getKeyDefinition());
759         builder.withChild(childBuilder.build());
760     }
761
762     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
763             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
764             final List<@NonNull QName> keys) {
765         for (var entry : entries) {
766             final var childCtx = getChildContext(ctxNode, entry);
767             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
768             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
769             builder.withChild(mapEntryBuilder.build());
770         }
771     }
772
773     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
774             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
775         for (var child : children) {
776             final var childCtx = getChildContext(ctxNode, child);
777             if (child instanceof ContainerNode container) {
778                 appendContainer(builder, container, childCtx, trim);
779             } else if (child instanceof MapNode map) {
780                 appendMap(builder, map, childCtx, trim);
781             } else if (child instanceof LeafNode<?> leaf) {
782                 appendLeaf(builder, leaf, childCtx, trim, List.of());
783             }
784         }
785     }
786
787     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
788             final NormalizedNode child) {
789         final var childId = child.name();
790         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
791             : null;
792         if (childCtx == null) {
793             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
794         }
795         return childCtx;
796     }
797
798     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
799                                                                   final NormalizedNode configDataNode) {
800         // if no data exists
801         if (stateDataNode == null && configDataNode == null) {
802             return null;
803         }
804
805         // return config data
806         if (stateDataNode == null) {
807             return configDataNode;
808         }
809
810         // return state data
811         if (configDataNode == null) {
812             return stateDataNode;
813         }
814
815         // merge data from config and state
816         return mergeStateAndConfigData(stateDataNode, configDataNode);
817     }
818
819     /**
820      * Merge state and config data into a single NormalizedNode.
821      *
822      * @param stateDataNode  data node of state data
823      * @param configDataNode data node of config data
824      * @return {@link NormalizedNode}
825      */
826     private static @NonNull NormalizedNode mergeStateAndConfigData(
827             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
828         validateNodeMerge(stateDataNode, configDataNode);
829         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
830         if (configDataNode instanceof RpcDefinition) {
831             return prepareRpcData(configDataNode, stateDataNode);
832         } else {
833             return prepareData(configDataNode, stateDataNode);
834         }
835     }
836
837     /**
838      * Validates whether the two NormalizedNodes can be merged.
839      *
840      * @param stateDataNode  data node of state data
841      * @param configDataNode data node of config data
842      */
843     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
844                                           final @NonNull NormalizedNode configDataNode) {
845         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
846         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
847         if (!moduleOfStateData.equals(moduleOfConfigData)) {
848             throw new RestconfDocumentedException("Unable to merge data from different modules.");
849         }
850     }
851
852     /**
853      * Prepare and map data for rpc.
854      *
855      * @param configDataNode data node of config data
856      * @param stateDataNode  data node of state data
857      * @return {@link NormalizedNode}
858      */
859     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
860                                                           final @NonNull NormalizedNode stateDataNode) {
861         final var mapEntryBuilder = Builders.mapEntryBuilder()
862             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
863
864         // MAP CONFIG DATA
865         mapRpcDataNode(configDataNode, mapEntryBuilder);
866         // MAP STATE DATA
867         mapRpcDataNode(stateDataNode, mapEntryBuilder);
868
869         return Builders.mapBuilder()
870             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
871             .addChild(mapEntryBuilder.build())
872             .build();
873     }
874
875     /**
876      * Map node to map entry builder.
877      *
878      * @param dataNode        data node
879      * @param mapEntryBuilder builder for mapping data
880      */
881     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
882             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
883         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
884     }
885
886     /**
887      * Prepare and map all data from DS.
888      *
889      * @param configDataNode data node of config data
890      * @param stateDataNode  data node of state data
891      * @return {@link NormalizedNode}
892      */
893     @SuppressWarnings("unchecked")
894     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
895                                                        final @NonNull NormalizedNode stateDataNode) {
896         if (configDataNode instanceof UserMapNode configMap) {
897             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
898             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
899             return builder.build();
900         } else if (configDataNode instanceof SystemMapNode configMap) {
901             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
902             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
903             return builder.build();
904         } else if (configDataNode instanceof MapEntryNode configEntry) {
905             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
906             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
907             return builder.build();
908         } else if (configDataNode instanceof ContainerNode configContaienr) {
909             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
910             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
911             return builder.build();
912         } else if (configDataNode instanceof ChoiceNode configChoice) {
913             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
914             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
915             return builder.build();
916         } else if (configDataNode instanceof LeafNode configLeaf) {
917             // config trumps oper
918             return configLeaf;
919         } else if (configDataNode instanceof UserLeafSetNode) {
920             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
921             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
922             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
923             return builder.build();
924         } else if (configDataNode instanceof SystemLeafSetNode) {
925             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
926             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
927             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
928             return builder.build();
929         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
930             // config trumps oper
931             return configEntry;
932         } else if (configDataNode instanceof UnkeyedListNode configList) {
933             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
934             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
935             return builder.build();
936         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
937             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
938             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
939             return builder.build();
940         } else {
941             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
942         }
943     }
944
945     /**
946      * Map value from container node to builder.
947      *
948      * @param configData collection of config data nodes
949      * @param stateData  collection of state data nodes
950      * @param builder    builder
951      */
952     private static <T extends NormalizedNode> void mapValueToBuilder(
953             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
954             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
955         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
956         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
957
958         // merge config and state data of children with different identifiers
959         mapDataToBuilder(configMap, stateMap, builder);
960
961         // merge config and state data of children with the same identifiers
962         mergeDataToBuilder(configMap, stateMap, builder);
963     }
964
965     /**
966      * Map data with different identifiers to builder. Data with different identifiers can be just added
967      * as childs to parent node.
968      *
969      * @param configMap map of config data nodes
970      * @param stateMap  map of state data nodes
971      * @param builder   - builder
972      */
973     private static <T extends NormalizedNode> void mapDataToBuilder(
974             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
975             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
976         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
977             y -> builder.addChild(y.getValue()));
978         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
979             y -> builder.addChild(y.getValue()));
980     }
981
982     /**
983      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
984      * go one level down with {@code prepareData} method.
985      *
986      * @param configMap immutable config data
987      * @param stateMap  immutable state data
988      * @param builder   - builder
989      */
990     @SuppressWarnings("unchecked")
991     private static <T extends NormalizedNode> void mergeDataToBuilder(
992             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
993             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
994         // it is enough to process only config data because operational contains the same data
995         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
996             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
997     }
998 }