2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.utils;
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;
41 public final class PatchDataTransactionUtil {
42 private static final Logger LOG = LoggerFactory.getLogger(PatchDataTransactionUtil.class);
44 private PatchDataTransactionUtil() {
45 throw new UnsupportedOperationException("Util class.");
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}
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();
63 for (final PatchEntity patchEntity : context.getData()) {
65 switch (patchEntity.getOperation()) {
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())));
79 deleteDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
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())));
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())));
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())));
112 removeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
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())));
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"))));
133 // if no errors then submit transaction, otherwise cancel
135 final ResponseFactory response = new ResponseFactory(Status.OK);
136 final FluentFuture<? extends CommitInfo> future = tx.commit();
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()));
147 return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
150 transactionChain.close();
151 return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection),
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
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);
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
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);
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
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);
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
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);
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
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);
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)
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());
257 checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, childPath);
260 rwTransaction.put(dataStore, childPath, child);
264 checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, path);
267 TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
268 rwTransaction.put(dataStore, path, payload);
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
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<>();
284 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
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,
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
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<>();
305 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
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,