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
9 package org.opendaylight.restconf.nb.rfc8040.rests.utils;
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.Lists;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import java.util.ArrayList;
15 import java.util.List;
16 import javax.ws.rs.core.Response.Status;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
19 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
20 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
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.references.SchemaContextRef;
31 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
32 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.PatchData;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public final class PatchDataTransactionUtil {
43 private static final Logger LOG = LoggerFactory.getLogger(PatchDataTransactionUtil.class);
45 private PatchDataTransactionUtil() {
46 throw new UnsupportedOperationException("Util class.");
50 * Process edit operations of one {@link PatchContext}.
51 * @param context Patch context to be processed
52 * @param transactionNode Wrapper for transaction
53 * @param schemaContextRef Soft reference for global schema context
54 * @return {@link PatchStatusContext}
56 public static PatchStatusContext patchData(final PatchContext context, final TransactionVarsWrapper transactionNode,
57 final SchemaContextRef schemaContextRef) {
58 final List<PatchStatusEntity> editCollection = new ArrayList<>();
59 boolean noError = true;
60 final DOMDataReadWriteTransaction tx = transactionNode.getTransactionChain().newReadWriteTransaction();
62 for (final PatchEntity patchEntity : context.getData()) {
64 switch (patchEntity.getOperation()) {
67 createDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
68 patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContextRef);
69 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
70 } catch (final RestconfDocumentedException e) {
71 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
72 false, Lists.newArrayList(e.getErrors())));
78 deleteDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
80 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
81 } catch (final RestconfDocumentedException e) {
82 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
83 false, Lists.newArrayList(e.getErrors())));
89 mergeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
90 patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContextRef);
91 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
92 } catch (final RestconfDocumentedException e) {
93 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
94 false, Lists.newArrayList(e.getErrors())));
100 replaceDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
101 patchEntity.getTargetNode(), patchEntity.getNode(), schemaContextRef, tx);
102 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
103 } catch (final RestconfDocumentedException e) {
104 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
105 false, Lists.newArrayList(e.getErrors())));
111 removeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
113 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
114 } catch (final RestconfDocumentedException e) {
115 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
116 false, Lists.newArrayList(e.getErrors())));
121 editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
122 false, Lists.newArrayList(new RestconfError(ErrorType.PROTOCOL,
123 ErrorTag.OPERATION_NOT_SUPPORTED, "Not supported Yang Patch operation"))));
132 // if no errors then submit transaction, otherwise cancel
134 final ResponseFactory response = new ResponseFactory(Status.OK);
135 final CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
138 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
139 } catch (final RestconfDocumentedException e) {
140 // if errors occurred during transaction commit then patch failed and global errors are reported
141 return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
142 Lists.newArrayList(e.getErrors()));
145 return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
148 transactionNode.getTransactionChainHandler().reset();
149 return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection),
155 * Create data within one transaction, return error if already exists.
156 * @param dataStore Datastore to write data to
157 * @param path Path for data to be created
158 * @param payload Data to be created
159 * @param rWTransaction Transaction
160 * @param schemaContextRef Soft reference for global schema context
162 private static void createDataWithinTransaction(final LogicalDatastoreType dataStore,
163 final YangInstanceIdentifier path,
164 final NormalizedNode<?, ?> payload,
165 final DOMDataReadWriteTransaction rwTransaction,
166 final SchemaContextRef schemaContextRef) {
167 LOG.trace("POST {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
168 createData(payload, schemaContextRef.get(), path, rwTransaction, dataStore, true);
172 * Check if data exists and remove it within one transaction.
173 * @param dataStore Datastore to delete data from
174 * @param path Path for data to be deleted
175 * @param readWriteTransaction Transaction
177 private static void deleteDataWithinTransaction(final LogicalDatastoreType dataStore,
178 final YangInstanceIdentifier path,
179 final DOMDataReadWriteTransaction readWriteTransaction) {
180 LOG.trace("Delete {} within Restconf Patch: {}", dataStore.name(), path);
181 checkItemExistsWithinTransaction(readWriteTransaction, dataStore, path);
182 readWriteTransaction.delete(dataStore, path);
186 * Merge data within one transaction.
187 * @param dataStore Datastore to merge data to
188 * @param path Path for data to be merged
189 * @param payload Data to be merged
190 * @param writeTransaction Transaction
191 * @param schemaContextRef Soft reference for global schema context
193 private static void mergeDataWithinTransaction(final LogicalDatastoreType dataStore,
194 final YangInstanceIdentifier path,
195 final NormalizedNode<?, ?> payload,
196 final DOMDataReadWriteTransaction writeTransaction,
197 final SchemaContextRef schemaContextRef) {
198 LOG.trace("Merge {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
199 TransactionUtil.ensureParentsByMerge(path, schemaContextRef.get(), writeTransaction);
200 writeTransaction.merge(dataStore, path, payload);
204 * Do NOT check if data exists and remove it within one transaction.
205 * @param dataStore Datastore to delete data from
206 * @param path Path for data to be deleted
207 * @param writeTransaction Transaction
209 private static void removeDataWithinTransaction(final LogicalDatastoreType dataStore,
210 final YangInstanceIdentifier path,
211 final DOMDataWriteTransaction writeTransaction) {
212 LOG.trace("Remove {} within Restconf Patch: {}", dataStore.name(), path);
213 writeTransaction.delete(dataStore, path);
217 * Create data within one transaction, replace if already exists.
218 * @param dataStore Datastore to write data to
219 * @param path Path for data to be created
220 * @param payload Data to be created
221 * @param schemaContextRef Soft reference for global schema context
222 * @param rwTransaction Transaction
224 private static void replaceDataWithinTransaction(final LogicalDatastoreType dataStore,
225 final YangInstanceIdentifier path,
226 final NormalizedNode<?, ?> payload,
227 final SchemaContextRef schemaContextRef,
228 final DOMDataReadWriteTransaction rwTransaction) {
229 LOG.trace("PUT {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
230 createData(payload, schemaContextRef.get(), path, rwTransaction, dataStore, false);
234 * Create data within one transaction. If {@code errorIfExists} is set to {@code true} then data will be checked
235 * for existence before created, otherwise they will be overwritten.
236 * @param payload Data to be created
237 * @param schemaContext Global schema context
238 * @param path Path for data to be created
239 * @param rwTransaction Transaction
240 * @param dataStore Datastore to write data to
241 * @param errorIfExists Enable checking for existence of data (throws error if already exists)
243 private static void createData(final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
244 final YangInstanceIdentifier path, final DOMDataReadWriteTransaction rwTransaction,
245 final LogicalDatastoreType dataStore, final boolean errorIfExists) {
246 if (payload instanceof MapNode) {
247 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
248 rwTransaction.merge(dataStore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
249 TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
250 for (final MapEntryNode child : ((MapNode) payload).getValue()) {
251 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
254 checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, childPath);
257 rwTransaction.put(dataStore, childPath, child);
261 checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, path);
264 TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
265 rwTransaction.put(dataStore, path, payload);
270 * Check if items already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
271 * data does NOT already exists.
272 * @param rwTransaction Transaction
273 * @param store Datastore
274 * @param path Path to be checked
276 public static void checkItemExistsWithinTransaction(final DOMDataReadWriteTransaction rwTransaction,
277 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
278 final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
279 final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
281 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
283 if (!response.result) {
284 LOG.trace("Operation via Restconf was not executed because data at {} does not exist", path);
285 throw new RestconfDocumentedException("Data does not exist", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
291 * Check if items do NOT already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
292 * data already exists.
293 * @param rwTransaction Transaction
294 * @param store Datastore
295 * @param path Path to be checked
297 public static void checkItemDoesNotExistsWithinTransaction(final DOMDataReadWriteTransaction rwTransaction,
298 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
299 final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
300 final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
302 FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
304 if (response.result) {
305 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
306 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,