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