Remove SchemaContextRef
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / utils / PatchDataTransactionUtil.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.nb.rfc8040.rests.utils;
9
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.Lists;
12 import com.google.common.util.concurrent.FluentFuture;
13 import java.util.ArrayList;
14 import java.util.List;
15 import javax.ws.rs.core.Response.Status;
16 import org.opendaylight.mdsal.common.api.CommitInfo;
17 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
18 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
19 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
20 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
21 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
22 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
23 import org.opendaylight.restconf.common.errors.RestconfError;
24 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
25 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
26 import org.opendaylight.restconf.common.patch.PatchContext;
27 import org.opendaylight.restconf.common.patch.PatchEntity;
28 import org.opendaylight.restconf.common.patch.PatchStatusContext;
29 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
30 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
31 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.PatchData;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public final class PatchDataTransactionUtil {
42     private static final Logger LOG = LoggerFactory.getLogger(PatchDataTransactionUtil.class);
43
44     private PatchDataTransactionUtil() {
45         throw new UnsupportedOperationException("Util class.");
46     }
47
48     /**
49      * Process edit operations of one {@link PatchContext}. Close {@link DOMTransactionChain} inside of object
50      * {@link TransactionVarsWrapper} provided as a parameter.
51      * @param context Patch context to be processed
52      * @param transactionNode Wrapper for transaction
53      * @param schemaContext Global schema context
54      * @return {@link PatchStatusContext}
55      */
56     public static PatchStatusContext patchData(final PatchContext context, final TransactionVarsWrapper transactionNode,
57                                                final EffectiveModelContext schemaContext) {
58         final List<PatchStatusEntity> editCollection = new ArrayList<>();
59         boolean noError = true;
60         final DOMTransactionChain transactionChain = transactionNode.getTransactionChain();
61         final DOMDataTreeReadWriteTransaction tx = transactionChain.newReadWriteTransaction();
62
63         for (final PatchEntity patchEntity : context.getData()) {
64             if (noError) {
65                 switch (patchEntity.getOperation()) {
66                     case CREATE:
67                         try {
68                             createDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
69                                     patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContext);
70                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
71                         } catch (final RestconfDocumentedException e) {
72                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
73                                     false, Lists.newArrayList(e.getErrors())));
74                             noError = false;
75                         }
76                         break;
77                     case DELETE:
78                         try {
79                             deleteDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
80                                     tx);
81                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
82                         } catch (final RestconfDocumentedException e) {
83                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
84                                     false, Lists.newArrayList(e.getErrors())));
85                             noError = false;
86                         }
87                         break;
88                     case MERGE:
89                         try {
90                             mergeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
91                                     patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContext);
92                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
93                         } catch (final RestconfDocumentedException e) {
94                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
95                                     false, Lists.newArrayList(e.getErrors())));
96                             noError = false;
97                         }
98                         break;
99                     case REPLACE:
100                         try {
101                             replaceDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
102                                     patchEntity.getTargetNode(), patchEntity.getNode(), schemaContext, tx);
103                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
104                         } catch (final RestconfDocumentedException e) {
105                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
106                                     false, Lists.newArrayList(e.getErrors())));
107                             noError = false;
108                         }
109                         break;
110                     case REMOVE:
111                         try {
112                             removeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
113                                     tx);
114                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
115                         } catch (final RestconfDocumentedException e) {
116                             editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
117                                     false, Lists.newArrayList(e.getErrors())));
118                             noError = false;
119                         }
120                         break;
121                     default:
122                         editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
123                                 false, Lists.newArrayList(new RestconfError(ErrorType.PROTOCOL,
124                                 ErrorTag.OPERATION_NOT_SUPPORTED, "Not supported Yang Patch operation"))));
125                         noError = false;
126                         break;
127                 }
128             } else {
129                 break;
130             }
131         }
132
133         // if no errors then submit transaction, otherwise cancel
134         if (noError) {
135             final ResponseFactory response = new ResponseFactory(Status.OK);
136             final FluentFuture<? extends CommitInfo> future = tx.commit();
137
138             try {
139                 //This method will close transactionChain
140                 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response, transactionChain);
141             } catch (final RestconfDocumentedException e) {
142                 // if errors occurred during transaction commit then patch failed and global errors are reported
143                 return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
144                         Lists.newArrayList(e.getErrors()));
145             }
146
147             return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
148         } else {
149             tx.cancel();
150             transactionChain.close();
151             return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection),
152                     false, null);
153         }
154     }
155
156     /**
157      * Create data within one transaction, return error if already exists.
158      * @param dataStore Datastore to write data to
159      * @param path Path for data to be created
160      * @param payload Data to be created
161      * @param rwTransaction Transaction
162      * @param schemaContext Global schema context
163      */
164     private static void createDataWithinTransaction(final LogicalDatastoreType dataStore,
165                                                     final YangInstanceIdentifier path,
166                                                     final NormalizedNode<?, ?> payload,
167                                                     final DOMDataTreeReadWriteTransaction rwTransaction,
168                                                     final EffectiveModelContext schemaContext) {
169         LOG.trace("POST {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
170         createData(payload, schemaContext, path, rwTransaction, dataStore, true);
171     }
172
173     /**
174      * Check if data exists and remove it within one transaction.
175      * @param dataStore Datastore to delete data from
176      * @param path Path for data to be deleted
177      * @param readWriteTransaction Transaction
178      */
179     private static void deleteDataWithinTransaction(final LogicalDatastoreType dataStore,
180                                                     final YangInstanceIdentifier path,
181                                                     final DOMDataTreeReadWriteTransaction readWriteTransaction) {
182         LOG.trace("Delete {} within Restconf Patch: {}", dataStore.name(), path);
183         checkItemExistsWithinTransaction(readWriteTransaction, dataStore, path);
184         readWriteTransaction.delete(dataStore, path);
185     }
186
187     /**
188      * Merge data within one transaction.
189      * @param dataStore Datastore to merge data to
190      * @param path Path for data to be merged
191      * @param payload Data to be merged
192      * @param writeTransaction Transaction
193      * @param schemaContext Global schema context
194      */
195     private static void mergeDataWithinTransaction(final LogicalDatastoreType dataStore,
196                                                    final YangInstanceIdentifier path,
197                                                    final NormalizedNode<?, ?> payload,
198                                                    final DOMDataTreeWriteTransaction writeTransaction,
199                                                    final EffectiveModelContext schemaContext) {
200         LOG.trace("Merge {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
201         TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTransaction);
202         writeTransaction.merge(dataStore, path, payload);
203     }
204
205     /**
206      * Do NOT check if data exists and remove it within one transaction.
207      * @param dataStore Datastore to delete data from
208      * @param path Path for data to be deleted
209      * @param writeTransaction Transaction
210      */
211     private static void removeDataWithinTransaction(final LogicalDatastoreType dataStore,
212                                                     final YangInstanceIdentifier path,
213                                                     final DOMDataTreeWriteTransaction writeTransaction) {
214         LOG.trace("Remove {} within Restconf Patch: {}", dataStore.name(), path);
215         writeTransaction.delete(dataStore, path);
216     }
217
218     /**
219      * Create data within one transaction, replace if already exists.
220      * @param dataStore Datastore to write data to
221      * @param path Path for data to be created
222      * @param payload Data to be created
223      * @param path Path for data to be created
224      * @param rwTransaction Transaction
225      */
226     private static void replaceDataWithinTransaction(final LogicalDatastoreType dataStore,
227                                                      final YangInstanceIdentifier path,
228                                                      final NormalizedNode<?, ?> payload,
229                                                      final EffectiveModelContext schemaContext,
230                                                      final DOMDataTreeReadWriteTransaction rwTransaction) {
231         LOG.trace("PUT {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
232         createData(payload, schemaContext, path, rwTransaction, dataStore, false);
233     }
234
235     /**
236      * Create data within one transaction. If {@code errorIfExists} is set to {@code true} then data will be checked
237      * for existence before created, otherwise they will be overwritten.
238      * @param payload Data to be created
239      * @param schemaContext Global schema context
240      * @param path Path for data to be created
241      * @param rwTransaction Transaction
242      * @param dataStore Datastore to write data to
243      * @param errorIfExists Enable checking for existence of data (throws error if already exists)
244      */
245     private static void createData(final NormalizedNode<?, ?> payload, final EffectiveModelContext schemaContext,
246                                    final YangInstanceIdentifier path,
247                                    final DOMDataTreeReadWriteTransaction rwTransaction,
248                                    final LogicalDatastoreType dataStore, final boolean errorIfExists) {
249         if (payload instanceof MapNode) {
250             final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
251             rwTransaction.merge(dataStore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
252             TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
253             for (final MapEntryNode child : ((MapNode) payload).getValue()) {
254                 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
255
256                 if (errorIfExists) {
257                     checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, childPath);
258                 }
259
260                 rwTransaction.put(dataStore, childPath, child);
261             }
262         } else {
263             if (errorIfExists) {
264                 checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, path);
265             }
266
267             TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
268             rwTransaction.put(dataStore, path, payload);
269         }
270     }
271
272     /**
273      * Check if items already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
274      * data does NOT already exists.
275      * @param rwTransaction Transaction
276      * @param store Datastore
277      * @param path Path to be checked
278      */
279     public static void checkItemExistsWithinTransaction(final DOMDataTreeReadOperations rwTransaction,
280                                                 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
281         final FluentFuture<Boolean> future = rwTransaction.exists(store, path);
282         final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
283
284         FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
285
286         if (!response.result) {
287             LOG.trace("Operation via Restconf was not executed because data at {} does not exist", path);
288             throw new RestconfDocumentedException("Data does not exist", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
289                 path);
290         }
291     }
292
293     /**
294      * Check if items do NOT already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
295      * data already exists.
296      * @param rwTransaction Transaction
297      * @param store Datastore
298      * @param path Path to be checked
299      */
300     public static void checkItemDoesNotExistsWithinTransaction(final DOMDataTreeReadOperations rwTransaction,
301                                                final LogicalDatastoreType store, final YangInstanceIdentifier path) {
302         final FluentFuture<Boolean> future = rwTransaction.exists(store, path);
303         final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
304
305         FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
306
307         if (response.result) {
308             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
309             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
310                 path);
311         }
312     }
313 }