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