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.util.concurrent.FluentFuture;
11 import java.util.HashMap;
12 import java.util.List;
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.mdsal.dom.api.DOMTransactionChain;
22 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
23 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
24 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
25 import org.opendaylight.restconf.common.errors.RestconfError;
26 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
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;
52 * Util class for put data to DS.
55 public final class PutDataTransactionUtil {
57 private PutDataTransactionUtil() {
62 * Valid input data with {@link SchemaNode}.
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);
78 * Valid top level node name.
85 public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
86 final String payloadName = payload.getData().getNodeType().getLocalName();
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);
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);
104 * Validates whether keys in {@code payload} are equal to values of keys in
105 * {@code iiWithData} for list schema node.
107 * @throws RestconfDocumentedException
108 * if key values or key count in payload and URI isn't equal
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).asMap();
119 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
124 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
125 final List<QName> keyDefinitions) {
126 final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
127 for (final QName keyDefinition : keyDefinitions) {
128 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
129 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
130 "Missing key %s in URI.", keyDefinition);
132 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
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);
144 * Check mount point and prepare variables for put data to DS. Close {@link DOMTransactionChain} inside of object
145 * {@link TransactionVarsWrapper} provided as a parameter.
149 * @param schemaCtxRef
150 * reference to {@link SchemaContext}
151 * @param transactionNode
152 * wrapper of variables for transaction
157 * @return {@link Response}
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();
164 final DOMDataTreeReadWriteTransaction readWriteTransaction =
165 transactionNode.getTransactionChain().newReadWriteTransaction();
167 final FluentFuture<Boolean> existsFuture = readWriteTransaction.exists(LogicalDatastoreType.CONFIGURATION,
169 final FutureDataFactory<Boolean> existsResponse = new FutureDataFactory<>();
170 FutureCallbackTx.addCallback(existsFuture, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, existsResponse);
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 //This method will close transactionChain
177 FutureCallbackTx.addCallback(submitData, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, responseFactory,
178 transactionNode.getTransactionChain());
179 return responseFactory.build();
187 * @param schemaContext
188 * {@link SchemaContext}
189 * @param transactionChainHandler
197 * @return {@link FluentFuture}
199 private static FluentFuture<? extends CommitInfo> submitData(final YangInstanceIdentifier path,
200 final SchemaContext schemaContext, final TransactionChainHandler transactionChainHandler,
201 final DOMDataTreeReadWriteTransaction readWriteTransaction,
202 final NormalizedNode<?, ?> data, final String insert, final String point) {
203 if (insert == null) {
204 return makePut(path, schemaContext, readWriteTransaction, data);
207 final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
210 if (schemaNode instanceof ListSchemaNode) {
211 final NormalizedNode<?, ?> readData =
212 readList(path, schemaContext, transactionChainHandler, schemaNode);
213 final OrderedMapNode readList = (OrderedMapNode) readData;
214 if (readList == null || readList.getValue().isEmpty()) {
215 return makePut(path, schemaContext, readWriteTransaction, data);
217 readWriteTransaction.delete(LogicalDatastoreType.CONFIGURATION, path.getParent());
218 simplePut(LogicalDatastoreType.CONFIGURATION, path, readWriteTransaction,
219 schemaContext, data);
220 listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), readWriteTransaction,
221 schemaContext, readList);
222 return readWriteTransaction.commit();
225 final NormalizedNode<?, ?> readData =
226 readList(path, schemaContext, transactionChainHandler, schemaNode);
228 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
229 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
230 return makePut(path, schemaContext, readWriteTransaction, data);
232 readWriteTransaction.delete(LogicalDatastoreType.CONFIGURATION, path.getParent());
233 simplePut(LogicalDatastoreType.CONFIGURATION, path, readWriteTransaction,
234 schemaContext, data);
235 listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), readWriteTransaction,
236 schemaContext, readLeafList);
237 return readWriteTransaction.commit();
241 return makePut(path, schemaContext, readWriteTransaction, data);
243 if (schemaNode instanceof ListSchemaNode) {
244 final NormalizedNode<?, ?> readData =
245 readList(path, schemaContext, transactionChainHandler, schemaNode);
246 final OrderedMapNode readList = (OrderedMapNode) readData;
247 if (readList == null || readList.getValue().isEmpty()) {
248 return makePut(path, schemaContext, readWriteTransaction, data);
250 insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION, path,
251 data, schemaContext, point, readList, true);
252 return readWriteTransaction.commit();
255 final NormalizedNode<?, ?> readData =
256 readList(path, schemaContext, transactionChainHandler, schemaNode);
258 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
259 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
260 return makePut(path, schemaContext, readWriteTransaction, data);
262 insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
263 path, data, schemaContext, point, readLeafList, true);
264 return readWriteTransaction.commit();
268 if (schemaNode instanceof ListSchemaNode) {
269 final NormalizedNode<?, ?> readData =
270 readList(path, schemaContext, transactionChainHandler, schemaNode);
271 final OrderedMapNode readList = (OrderedMapNode) readData;
272 if (readList == null || readList.getValue().isEmpty()) {
273 return makePut(path, schemaContext, readWriteTransaction, data);
275 insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
276 path, data, schemaContext, point, readList, false);
277 return readWriteTransaction.commit();
280 final NormalizedNode<?, ?> readData =
281 readList(path, schemaContext, transactionChainHandler, schemaNode);
283 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
284 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
285 return makePut(path, schemaContext, readWriteTransaction, data);
287 insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
288 path, data, schemaContext, point, readLeafList, true);
289 return readWriteTransaction.commit();
293 throw new RestconfDocumentedException(
294 "Used bad value of insert parameter. Possible values are first, last, before or after, "
295 + "but was: " + insert, RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE);
299 public static NormalizedNode<?, ?> readList(final YangInstanceIdentifier path, final SchemaContext schemaContext,
300 final TransactionChainHandler transactionChainHandler, final DataSchemaNode schemaNode) {
301 final InstanceIdentifierContext<?> iid = new InstanceIdentifierContext<SchemaNode>(
302 path.getParent(), schemaNode, null, schemaContext);
303 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(iid, null, transactionChainHandler);
304 final NormalizedNode<?, ?> readData = ReadDataTransactionUtil
305 .readData(RestconfDataServiceConstant.ReadData.CONFIG, transactionNode, schemaContext);
309 private static void insertWithPointLeafListPut(final DOMDataTreeReadWriteTransaction rwTransaction,
310 final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
311 final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
312 final OrderedLeafSetNode<?> readLeafList, final boolean before) {
313 rwTransaction.delete(datastore, path.getParent());
314 final InstanceIdentifierContext<?> instanceIdentifier =
315 ParserIdentifier.toInstanceIdentifier(point, schemaContext, Optional.empty());
316 int lastItemPosition = 0;
317 for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
318 if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
326 int lastInsertedPosition = 0;
327 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
328 rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
329 for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
330 if (lastInsertedPosition == lastItemPosition) {
331 simplePut(datastore, path, rwTransaction, schemaContext, data);
333 final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
334 rwTransaction.put(datastore, childPath, nodeChild);
335 lastInsertedPosition++;
339 private static void insertWithPointListPut(final DOMDataTreeReadWriteTransaction writeTx,
340 final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
341 final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
342 final OrderedMapNode readList, final boolean before) {
343 writeTx.delete(datastore, path.getParent());
344 final InstanceIdentifierContext<?> instanceIdentifier =
345 ParserIdentifier.toInstanceIdentifier(point, schemaContext, Optional.empty());
346 int lastItemPosition = 0;
347 for (final MapEntryNode mapEntryNode : readList.getValue()) {
348 if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
356 int lastInsertedPosition = 0;
357 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
358 writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
359 for (final MapEntryNode mapEntryNode : readList.getValue()) {
360 if (lastInsertedPosition == lastItemPosition) {
361 simplePut(datastore, path, writeTx, schemaContext, data);
363 final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
364 writeTx.put(datastore, childPath, mapEntryNode);
365 lastInsertedPosition++;
369 private static void listPut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
370 final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
371 final OrderedLeafSetNode<?> payload) {
372 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
373 writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
374 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
375 for (final LeafSetEntryNode<?> child : ((LeafSetNode<?>) payload).getValue()) {
376 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
377 writeTx.put(datastore, childPath, child);
381 private static void listPut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
382 final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
383 final OrderedMapNode payload) {
384 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
385 writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
386 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
387 for (final MapEntryNode child : payload.getValue()) {
388 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
389 writeTx.put(datastore, childPath, child);
393 private static void simplePut(final LogicalDatastoreType configuration, final YangInstanceIdentifier path,
394 final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
395 final NormalizedNode<?, ?> data) {
396 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
397 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
400 private static FluentFuture<? extends CommitInfo> makePut(final YangInstanceIdentifier path,
401 final SchemaContext schemaContext, final DOMDataTreeWriteTransaction writeTx,
402 final NormalizedNode<?, ?> data) {
403 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
404 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
405 return writeTx.commit();
408 public static DataSchemaNode checkListAndOrderedType(final SchemaContext ctx, final YangInstanceIdentifier path) {
409 final YangInstanceIdentifier parent = path.getParent();
410 final DataSchemaContextNode<?> node = DataSchemaContextTree.from(ctx).getChild(parent);
411 final DataSchemaNode dataSchemaNode = node.getDataSchemaNode();
413 if (dataSchemaNode instanceof ListSchemaNode) {
414 if (!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
415 throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user list.",
416 RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
418 return dataSchemaNode;
420 if (dataSchemaNode instanceof LeafListSchemaNode) {
421 if (!((LeafListSchemaNode) dataSchemaNode).isUserOrdered()) {
422 throw new RestconfDocumentedException(
423 "Insert parameter can be used only with ordered-by user leaf-list.",
424 RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
426 return dataSchemaNode;
428 throw new RestconfDocumentedException("Insert parameter can be used only with list or leaf-list",
429 RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);