d8cd95f35ed34080962c67fbb2c0b1b8ecba9e98
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / utils / PutDataTransactionUtil.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.Maps;
11 import com.google.common.util.concurrent.FluentFuture;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Optional;
15 import javax.ws.rs.core.Response;
16 import javax.ws.rs.core.Response.Status;
17 import org.opendaylight.mdsal.common.api.CommitInfo;
18 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
19 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
20 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
21 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
22 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
25 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
26 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
27 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
28 import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
29 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
30 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
41 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
42 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
43 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49
50 /**
51  * Util class for put data to DS.
52  *
53  */
54 public final class PutDataTransactionUtil {
55
56     private PutDataTransactionUtil() {
57
58     }
59
60     /**
61      * Valid input data with {@link SchemaNode}.
62      *
63      * @param schemaNode
64      *             {@link SchemaNode}
65      * @param payload
66      *             input data
67      */
68     public static void validInputData(final SchemaNode schemaNode, final NormalizedNodeContext payload) {
69         if (schemaNode != null && payload.getData() == null) {
70             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
71         } else if (schemaNode == null && payload.getData() != null) {
72             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
73         }
74     }
75
76     /**
77      * Valid top level node name.
78      *
79      * @param path
80      *             path of node
81      * @param payload
82      *             data
83      */
84     public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
85         final String payloadName = payload.getData().getNodeType().getLocalName();
86
87         if (path.isEmpty()) {
88             if (!payload.getData().getNodeType().equals(RestconfDataServiceConstant.NETCONF_BASE_QNAME)) {
89                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
90                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
91             }
92         } else {
93             final String identifierName = path.getLastPathArgument().getNodeType().getLocalName();
94             if (!payloadName.equals(identifierName)) {
95                 throw new RestconfDocumentedException(
96                         "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
97                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
98             }
99         }
100     }
101
102     /**
103      * Validates whether keys in {@code payload} are equal to values of keys in
104      * {@code iiWithData} for list schema node.
105      *
106      * @throws RestconfDocumentedException
107      *             if key values or key count in payload and URI isn't equal
108      */
109     public static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
110         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
111         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
112         final SchemaNode schemaNode = iiWithData.getSchemaNode();
113         final NormalizedNode<?, ?> data = payload.getData();
114         if (schemaNode instanceof ListSchemaNode) {
115             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
116             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
117                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
118                         .getKeyValues();
119                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
120             }
121         }
122     }
123
124     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
125             final List<QName> keyDefinitions) {
126         final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
127         for (final QName keyDefinition : keyDefinitions) {
128             final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
129             RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
130                     "Missing key " + keyDefinition + " in URI.");
131
132             final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
133
134             if (!uriKeyValue.equals(dataKeyValue)) {
135                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
136                         + "' specified in the URI doesn't match the value '" + dataKeyValue
137                         + "' specified in the message body. ";
138                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
139             }
140         }
141     }
142
143     /**
144      * Check mount point and prepare variables for put data to DS.
145      *
146      * @param payload
147      *             data to put
148      * @param schemaCtxRef
149      *             reference to {@link SchemaContext}
150      * @param transactionNode
151      *             wrapper of variables for transaction
152      * @param point
153      *             query parameter
154      * @param insert
155      *             query parameter
156      * @return {@link Response}
157      */
158     public static Response putData(final NormalizedNodeContext payload, final SchemaContextRef schemaCtxRef,
159                                final TransactionVarsWrapper transactionNode, final String insert, final String point) {
160         final YangInstanceIdentifier path = payload.getInstanceIdentifierContext().getInstanceIdentifier();
161         final SchemaContext schemaContext = schemaCtxRef.get();
162
163         final DOMDataTreeReadWriteTransaction readWriteTransaction =
164                 transactionNode.getTransactionChain().newReadWriteTransaction();
165
166         final FluentFuture<Boolean> existsFuture = readWriteTransaction.exists(LogicalDatastoreType.CONFIGURATION,
167             path);
168         final FutureDataFactory<Boolean> existsResponse = new FutureDataFactory<>();
169         FutureCallbackTx.addCallback(existsFuture, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, existsResponse);
170
171         final ResponseFactory responseFactory =
172                 new ResponseFactory(existsResponse.result ? Status.NO_CONTENT : Status.CREATED);
173         final FluentFuture<? extends CommitInfo> submitData = submitData(path, schemaContext,
174                 transactionNode.getTransactionChainHandler(), readWriteTransaction, payload.getData(), insert, point);
175         FutureCallbackTx.addCallback(submitData, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, responseFactory);
176         return responseFactory.build();
177     }
178
179     /**
180      * Put data to DS.
181      *
182      * @param path
183      *             path of data
184      * @param schemaContext
185      *             {@link SchemaContext}
186      * @param transactionChainHandler
187      *             write transaction
188      * @param data
189      *             data
190      * @param point
191      *             query parameter
192      * @param insert
193      *             query parameter
194      * @return {@link FluentFuture}
195      */
196     private static FluentFuture<? extends CommitInfo> submitData(final YangInstanceIdentifier path,
197             final SchemaContext schemaContext, final TransactionChainHandler transactionChainHandler,
198             final DOMDataTreeReadWriteTransaction readWriteTransaction,
199             final NormalizedNode<?, ?> data, final String insert, final String point) {
200         if (insert == null) {
201             return makePut(path, schemaContext, readWriteTransaction, data);
202         }
203
204         final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
205         switch (insert) {
206             case "first":
207                 if (schemaNode instanceof ListSchemaNode) {
208                     final NormalizedNode<?, ?> readData =
209                             readList(path, schemaContext, transactionChainHandler, schemaNode);
210                     final OrderedMapNode readList = (OrderedMapNode) readData;
211                     if (readList == null || readList.getValue().isEmpty()) {
212                         return makePut(path, schemaContext, readWriteTransaction, data);
213                     } else {
214                         readWriteTransaction.delete(LogicalDatastoreType.CONFIGURATION, path.getParent());
215                         simplePut(LogicalDatastoreType.CONFIGURATION, path, readWriteTransaction,
216                             schemaContext, data);
217                         listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), readWriteTransaction,
218                             schemaContext, readList);
219                         return readWriteTransaction.commit();
220                     }
221                 } else {
222                     final NormalizedNode<?, ?> readData =
223                             readList(path, schemaContext, transactionChainHandler, schemaNode);
224
225                     final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
226                     if (readLeafList == null || readLeafList.getValue().isEmpty()) {
227                         return makePut(path, schemaContext, readWriteTransaction, data);
228                     } else {
229                         readWriteTransaction.delete(LogicalDatastoreType.CONFIGURATION, path.getParent());
230                         simplePut(LogicalDatastoreType.CONFIGURATION, path, readWriteTransaction,
231                             schemaContext, data);
232                         listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), readWriteTransaction,
233                             schemaContext, readLeafList);
234                         return readWriteTransaction.commit();
235                     }
236                 }
237             case "last":
238                 return makePut(path, schemaContext, readWriteTransaction, data);
239             case "before":
240                 if (schemaNode instanceof ListSchemaNode) {
241                     final NormalizedNode<?, ?> readData =
242                             readList(path, schemaContext, transactionChainHandler, schemaNode);
243                     final OrderedMapNode readList = (OrderedMapNode) readData;
244                     if (readList == null || readList.getValue().isEmpty()) {
245                         return makePut(path, schemaContext, readWriteTransaction, data);
246                     } else {
247                         insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION, path,
248                             data, schemaContext, point, readList, true);
249                         return readWriteTransaction.commit();
250                     }
251                 } else {
252                     final NormalizedNode<?, ?> readData =
253                             readList(path, schemaContext, transactionChainHandler, schemaNode);
254
255                     final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
256                     if (readLeafList == null || readLeafList.getValue().isEmpty()) {
257                         return makePut(path, schemaContext, readWriteTransaction, data);
258                     } else {
259                         insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
260                             path, data, schemaContext, point, readLeafList, true);
261                         return readWriteTransaction.commit();
262                     }
263                 }
264             case "after":
265                 if (schemaNode instanceof ListSchemaNode) {
266                     final NormalizedNode<?, ?> readData =
267                             readList(path, schemaContext, transactionChainHandler, schemaNode);
268                     final OrderedMapNode readList = (OrderedMapNode) readData;
269                     if (readList == null || readList.getValue().isEmpty()) {
270                         return makePut(path, schemaContext, readWriteTransaction, data);
271                     } else {
272                         insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
273                             path, data, schemaContext, point, readList, false);
274                         return readWriteTransaction.commit();
275                     }
276                 } else {
277                     final NormalizedNode<?, ?> readData =
278                             readList(path, schemaContext, transactionChainHandler, schemaNode);
279
280                     final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
281                     if (readLeafList == null || readLeafList.getValue().isEmpty()) {
282                         return makePut(path, schemaContext, readWriteTransaction, data);
283                     } else {
284                         insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
285                             path, data, schemaContext, point, readLeafList, true);
286                         return readWriteTransaction.commit();
287                     }
288                 }
289             default:
290                 throw new RestconfDocumentedException("Used bad value of insert parameter. Possible values are "
291                         + "first, last, before or after, but was: " + insert);
292         }
293     }
294
295     public static NormalizedNode<?, ?> readList(final YangInstanceIdentifier path, final SchemaContext schemaContext,
296             final TransactionChainHandler transactionChainHandler, final DataSchemaNode schemaNode) {
297         final InstanceIdentifierContext<?> iid = new InstanceIdentifierContext<SchemaNode>(
298                 path.getParent(), schemaNode, null, schemaContext);
299         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(iid, null, transactionChainHandler);
300         final NormalizedNode<?, ?> readData = ReadDataTransactionUtil
301                 .readData(RestconfDataServiceConstant.ReadData.CONFIG, transactionNode, schemaContext);
302         return readData;
303     }
304
305     private static void insertWithPointLeafListPut(final DOMDataTreeReadWriteTransaction rwTransaction,
306             final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
307             final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
308             final OrderedLeafSetNode<?> readLeafList, final boolean before) {
309         rwTransaction.delete(datastore, path.getParent());
310         final InstanceIdentifierContext<?> instanceIdentifier =
311                 ParserIdentifier.toInstanceIdentifier(point, schemaContext, Optional.empty());
312         int lastItemPosition = 0;
313         for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
314             if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
315                 break;
316             }
317             lastItemPosition++;
318         }
319         if (!before) {
320             lastItemPosition++;
321         }
322         int lastInsertedPosition = 0;
323         final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
324         rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
325         for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
326             if (lastInsertedPosition == lastItemPosition) {
327                 simplePut(datastore, path, rwTransaction, schemaContext, data);
328             }
329             final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
330             rwTransaction.put(datastore, childPath, nodeChild);
331             lastInsertedPosition++;
332         }
333     }
334
335     private static void insertWithPointListPut(final DOMDataTreeReadWriteTransaction writeTx,
336             final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
337             final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
338             final OrderedMapNode readList, final boolean before) {
339         writeTx.delete(datastore, path.getParent());
340         final InstanceIdentifierContext<?> instanceIdentifier =
341                 ParserIdentifier.toInstanceIdentifier(point, schemaContext, Optional.empty());
342         int lastItemPosition = 0;
343         for (final MapEntryNode mapEntryNode : readList.getValue()) {
344             if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
345                 break;
346             }
347             lastItemPosition++;
348         }
349         if (!before) {
350             lastItemPosition++;
351         }
352         int lastInsertedPosition = 0;
353         final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
354         writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
355         for (final MapEntryNode mapEntryNode : readList.getValue()) {
356             if (lastInsertedPosition == lastItemPosition) {
357                 simplePut(datastore, path, writeTx, schemaContext, data);
358             }
359             final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
360             writeTx.put(datastore, childPath, mapEntryNode);
361             lastInsertedPosition++;
362         }
363     }
364
365     private static void listPut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
366             final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
367             final OrderedLeafSetNode<?> payload) {
368         final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
369         writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
370         TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
371         for (final LeafSetEntryNode<?> child : ((LeafSetNode<?>) payload).getValue()) {
372             final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
373             writeTx.put(datastore, childPath, child);
374         }
375     }
376
377     private static void listPut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
378             final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
379             final OrderedMapNode payload) {
380         final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
381         writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
382         TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
383         for (final MapEntryNode child : payload.getValue()) {
384             final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
385             writeTx.put(datastore, childPath, child);
386         }
387     }
388
389     private static void simplePut(final LogicalDatastoreType configuration, final YangInstanceIdentifier path,
390             final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
391             final NormalizedNode<?, ?> data) {
392         TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
393         writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
394     }
395
396     private static FluentFuture<? extends CommitInfo> makePut(final YangInstanceIdentifier path,
397             final SchemaContext schemaContext, final DOMDataTreeWriteTransaction writeTx,
398             final NormalizedNode<?, ?> data) {
399         TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
400         writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
401         return writeTx.commit();
402     }
403
404     public static DataSchemaNode checkListAndOrderedType(final SchemaContext ctx, final YangInstanceIdentifier path) {
405         final YangInstanceIdentifier parent = path.getParent();
406         final DataSchemaContextNode<?> node = DataSchemaContextTree.from(ctx).getChild(parent);
407         final DataSchemaNode dataSchemaNode = node.getDataSchemaNode();
408
409         if (dataSchemaNode instanceof ListSchemaNode) {
410             if (!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
411                 throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user list.");
412             }
413             return dataSchemaNode;
414         }
415         if (dataSchemaNode instanceof LeafListSchemaNode) {
416             if (!((LeafListSchemaNode) dataSchemaNode).isUserOrdered()) {
417                 throw new RestconfDocumentedException(
418                         "Insert parameter can be used only with ordered-by user leaf-list.");
419             }
420             return dataSchemaNode;
421         }
422         throw new RestconfDocumentedException("Insert parameter can be used only with list or leaf-list");
423     }
424 }