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