Fix PatchEditOperation
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / restful / utils / PatchDataTransactionUtil.java
index 09cdf6a6e2284ef6bbe5f7cb6ef2601c8da321db..09107d3db88fceda3383ea4076ba65bd76f2c71c 100644 (file)
@@ -14,18 +14,19 @@ import com.google.common.util.concurrent.CheckedFuture;
 import java.util.ArrayList;
 import java.util.List;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusEntity;
 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
+import org.opendaylight.restconf.RestConnectorProvider;
 import org.opendaylight.restconf.common.references.SchemaContextRef;
 import org.opendaylight.restconf.restful.transaction.TransactionVarsWrapper;
 import org.opendaylight.restconf.restful.utils.RestconfDataServiceConstant.PatchData;
@@ -41,121 +42,112 @@ import org.slf4j.LoggerFactory;
 public final class PatchDataTransactionUtil {
     private static final Logger LOG = LoggerFactory.getLogger(PatchDataTransactionUtil.class);
 
-    public PatchDataTransactionUtil() {
+    private PatchDataTransactionUtil() {
         throw new UnsupportedOperationException("Util class.");
     }
 
     /**
-     * Process edit operations of one {@link PATCHContext}.
+     * Process edit operations of one {@link PatchContext}.
      * @param context Patch context to be processed
      * @param transactionNode Wrapper for transaction
      * @param schemaContextRef Soft reference for global schema context
-     * @return {@link PATCHStatusContext}
+     * @return {@link PatchStatusContext}
      */
-    public static PATCHStatusContext patchData(final PATCHContext context, final TransactionVarsWrapper transactionNode,
+    public static PatchStatusContext patchData(final PatchContext context, final TransactionVarsWrapper transactionNode,
                                                final SchemaContextRef schemaContextRef) {
-        final List<PATCHStatusEntity> editCollection = new ArrayList<>();
-        int errorCounter = 0;
+        final List<PatchStatusEntity> editCollection = new ArrayList<>();
+        boolean noError = true;
+        final DOMDataReadWriteTransaction tx = transactionNode.getTransactionChain().newReadWriteTransaction();
 
-        for (final PATCHEntity patchEntity : context.getData()) {
-            final PATCHEditOperation operation = PATCHEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
-
-            switch (operation) {
-                case CREATE:
-                    if (errorCounter == 0) {
+        for (final PatchEntity patchEntity : context.getData()) {
+            if (noError) {
+                switch (patchEntity.getOperation()) {
+                    case CREATE:
                         try {
                             createDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
-                                    patchEntity.getTargetNode(), patchEntity.getNode(),
-                                    transactionNode.getTransaction(), schemaContextRef);
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+                                    patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContextRef);
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                         } catch (final RestconfDocumentedException e) {
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
                                     false, Lists.newArrayList(e.getErrors())));
-                            errorCounter++;
+                            noError = false;
                         }
-                    }
-                    break;
-                case DELETE:
-                    if (errorCounter == 0) {
+                        break;
+                    case DELETE:
                         try {
-                            deleteDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
-                                    patchEntity.getTargetNode(), transactionNode.getTransaction());
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+                            deleteDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
+                                    tx);
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                         } catch (final RestconfDocumentedException e) {
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
                                     false, Lists.newArrayList(e.getErrors())));
-                            errorCounter++;
+                            noError = false;
                         }
-                    }
-                    break;
-                case MERGE:
-                    if (errorCounter == 0) {
+                        break;
+                    case MERGE:
                         try {
                             mergeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
-                                    patchEntity.getTargetNode(), patchEntity.getNode(), transactionNode.getTransaction(),
-                                    schemaContextRef);
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+                                    patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContextRef);
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                         } catch (final RestconfDocumentedException e) {
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
                                     false, Lists.newArrayList(e.getErrors())));
-                            errorCounter++;
+                            noError = false;
                         }
-                    }
-                    break;
-                case REPLACE:
-                    if (errorCounter == 0) {
+                        break;
+                    case REPLACE:
                         try {
                             replaceDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
-                                    patchEntity.getTargetNode(), patchEntity.getNode(), schemaContextRef,
-                                    transactionNode.getTransaction());
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+                                    patchEntity.getTargetNode(), patchEntity.getNode(), schemaContextRef, tx);
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                         } catch (final RestconfDocumentedException e) {
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
                                     false, Lists.newArrayList(e.getErrors())));
-                            errorCounter++;
+                            noError = false;
                         }
-                    }
-                    break;
-                case REMOVE:
-                    if (errorCounter == 0) {
+                        break;
+                    case REMOVE:
                         try {
-                            removeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
-                                    patchEntity.getTargetNode(), transactionNode.getTransaction());
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+                            removeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
+                                    tx);
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
                         } catch (final RestconfDocumentedException e) {
-                            editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+                            editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
                                     false, Lists.newArrayList(e.getErrors())));
-                            errorCounter++;
+                            noError = false;
                         }
-                    }
-                    break;
-                default:
-                    editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
-                            false, Lists.newArrayList(new RestconfError(ErrorType.PROTOCOL,
-                            ErrorTag.OPERATION_NOT_SUPPORTED, "Not supported Yang PATCH operation"))));
-                    errorCounter++;
-                    break;
+                        break;
+                    default:
+                        editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
+                                false, Lists.newArrayList(new RestconfError(ErrorType.PROTOCOL,
+                                ErrorTag.OPERATION_NOT_SUPPORTED, "Not supported Yang Patch operation"))));
+                        noError = false;
+                        break;
+                }
+            } else {
+                break;
             }
         }
 
         // if no errors then submit transaction, otherwise cancel
-        if (errorCounter == 0) {
+        if (noError) {
             final ResponseFactory response = new ResponseFactory();
-            final CheckedFuture<Void, TransactionCommitFailedException> future = transactionNode
-                    .getTransaction().submit();
+            final CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
 
             try {
                 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
             } catch (final RestconfDocumentedException e) {
                 // if errors occurred during transaction commit then patch failed and global errors are reported
-                return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
+                return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
                         Lists.newArrayList(e.getErrors()));
             }
 
-            return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
+            return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
         } else {
-            transactionNode.getTransaction().cancel();
-            return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false, null);
+            tx.cancel();
+            RestConnectorProvider.resetTransactionChainForAdapaters(transactionNode.getTransactionChain());
+            return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection),
+                    false, null);
         }
     }
 
@@ -170,10 +162,10 @@ public final class PatchDataTransactionUtil {
     private static void createDataWithinTransaction(final LogicalDatastoreType dataStore,
                                                     final YangInstanceIdentifier path,
                                                     final NormalizedNode<?, ?> payload,
-                                                    final DOMDataReadWriteTransaction rWTransaction,
+                                                    final DOMDataReadWriteTransaction rwTransaction,
                                                     final SchemaContextRef schemaContextRef) {
-        LOG.trace("POST {} within Restconf PATCH: {} with payload {}", dataStore.name(), path, payload);
-        createData(payload, schemaContextRef.get(), path, rWTransaction, dataStore, true);
+        LOG.trace("POST {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
+        createData(payload, schemaContextRef.get(), path, rwTransaction, dataStore, true);
     }
 
     /**
@@ -185,8 +177,8 @@ public final class PatchDataTransactionUtil {
     private static void deleteDataWithinTransaction(final LogicalDatastoreType dataStore,
                                                     final YangInstanceIdentifier path,
                                                     final DOMDataReadWriteTransaction readWriteTransaction) {
-        LOG.trace("Delete {} within Restconf PATCH: {}", dataStore.name(), path);
-        TransactionUtil.checkItemExists(readWriteTransaction, dataStore, path, PatchData.PATCH_TX_TYPE);
+        LOG.trace("Delete {} within Restconf Patch: {}", dataStore.name(), path);
+        checkItemExistsWithinTransaction(readWriteTransaction, dataStore, path);
         readWriteTransaction.delete(dataStore, path);
     }
 
@@ -203,15 +195,9 @@ public final class PatchDataTransactionUtil {
                                                    final NormalizedNode<?, ?> payload,
                                                    final DOMDataReadWriteTransaction writeTransaction,
                                                    final SchemaContextRef schemaContextRef) {
-        LOG.trace("Merge {} within Restconf PATCH: {} with payload {}", dataStore.name(), path, payload);
+        LOG.trace("Merge {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
         TransactionUtil.ensureParentsByMerge(path, schemaContextRef.get(), writeTransaction);
-
-        // merging is necessary only for lists otherwise we can call put method
-        if (payload instanceof MapNode) {
-            writeTransaction.merge(dataStore, path, payload);
-        } else {
-            writeTransaction.put(dataStore, path, payload);
-        }
+        writeTransaction.merge(dataStore, path, payload);
     }
 
     /**
@@ -223,7 +209,7 @@ public final class PatchDataTransactionUtil {
     private static void removeDataWithinTransaction(final LogicalDatastoreType dataStore,
                                                     final YangInstanceIdentifier path,
                                                     final DOMDataWriteTransaction writeTransaction) {
-        LOG.trace("Remove {} within Restconf PATCH: {}", dataStore.name(), path);
+        LOG.trace("Remove {} within Restconf Patch: {}", dataStore.name(), path);
         writeTransaction.delete(dataStore, path);
     }
 
@@ -233,15 +219,15 @@ public final class PatchDataTransactionUtil {
      * @param path Path for data to be created
      * @param payload Data to be created
      * @param schemaContextRef Soft reference for global schema context
-     * @param rWTransaction Transaction
+     * @param rwTransaction Transaction
      */
     private static void replaceDataWithinTransaction(final LogicalDatastoreType dataStore,
                                                      final YangInstanceIdentifier path,
                                                      final NormalizedNode<?, ?> payload,
                                                      final SchemaContextRef schemaContextRef,
-                                                     final DOMDataReadWriteTransaction rWTransaction) {
-        LOG.trace("PUT {} within Restconf PATCH: {} with payload {}", dataStore.name(), path, payload);
-        createData(payload, schemaContextRef.get(), path, rWTransaction, dataStore, false);
+                                                     final DOMDataReadWriteTransaction rwTransaction) {
+        LOG.trace("PUT {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
+        createData(payload, schemaContextRef.get(), path, rwTransaction, dataStore, false);
     }
 
     /**
@@ -250,35 +236,77 @@ public final class PatchDataTransactionUtil {
      * @param payload Data to be created
      * @param schemaContext Global schema context
      * @param path Path for data to be created
-     * @param rWTransaction Transaction
+     * @param rwTransaction Transaction
      * @param dataStore Datastore to write data to
      * @param errorIfExists Enable checking for existence of data (throws error if already exists)
      */
     private static void createData(final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
-                                   final YangInstanceIdentifier path, final DOMDataReadWriteTransaction rWTransaction,
+                                   final YangInstanceIdentifier path, final DOMDataReadWriteTransaction rwTransaction,
                                    final LogicalDatastoreType dataStore, final boolean errorIfExists) {
         if (payload instanceof MapNode) {
             final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
-            rWTransaction.merge(dataStore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
-            TransactionUtil.ensureParentsByMerge(path, schemaContext, rWTransaction);
+            rwTransaction.merge(dataStore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+            TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
             for (final MapEntryNode child : ((MapNode) payload).getValue()) {
                 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
 
                 if (errorIfExists) {
-                    TransactionUtil.checkItemDoesNotExists(
-                            rWTransaction, dataStore, childPath, PatchData.PATCH_TX_TYPE);
+                    checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, childPath);
                 }
 
-                rWTransaction.put(dataStore, childPath, child);
+                rwTransaction.put(dataStore, childPath, child);
             }
         } else {
             if (errorIfExists) {
-                TransactionUtil.checkItemDoesNotExists(
-                        rWTransaction, dataStore, path, PatchData.PATCH_TX_TYPE);
+                checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, path);
             }
 
-            TransactionUtil.ensureParentsByMerge(path, schemaContext, rWTransaction);
-            rWTransaction.put(dataStore, path, payload);
+            TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
+            rwTransaction.put(dataStore, path, payload);
+        }
+    }
+
+    /**
+     * Check if items already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
+     * data does NOT already exists.
+     * @param rwTransaction Transaction
+     * @param store Datastore
+     * @param path Path to be checked
+     */
+    public static void checkItemExistsWithinTransaction(final DOMDataReadWriteTransaction rwTransaction,
+                                                final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+        final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
+        final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
+
+        FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
+
+        if (!response.result) {
+            final String errMsg = "Operation via Restconf was not executed because data does not exist";
+            LOG.trace("{}:{}", errMsg, path);
+            throw new RestconfDocumentedException(
+                    "Data does not exist", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, path);
+        }
+    }
+
+    /**
+     * Check if items do NOT already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
+     * data already exists.
+     * @param rwTransaction Transaction
+     * @param store Datastore
+     * @param path Path to be checked
+     */
+    public static void checkItemDoesNotExistsWithinTransaction(final DOMDataReadWriteTransaction rwTransaction,
+                                               final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+        final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
+        final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
+
+        FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
+
+        if (response.result) {
+            final String errMsg = "Operation via Restconf was not executed because data already exists";
+            LOG.trace("{}:{}", errMsg, path);
+            throw new RestconfDocumentedException(
+                    "Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, path);
         }
     }
-}
+}
\ No newline at end of file