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.Maps;
11 import com.google.common.util.concurrent.FluentFuture;
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.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.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;
51 * Util class for put data to DS.
54 public final class PutDataTransactionUtil {
56 private PutDataTransactionUtil() {
61 * Valid input data with {@link SchemaNode}.
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);
77 * Valid top level node name.
84 public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
85 final String payloadName = payload.getData().getNodeType().getLocalName();
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);
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);
103 * Validates whether keys in {@code payload} are equal to values of keys in
104 * {@code iiWithData} for list schema node.
106 * @throws RestconfDocumentedException
107 * if key values or key count in payload and URI isn't equal
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)
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 = Maps.newHashMap(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().getKeyValues().get(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.
148 * @param schemaCtxRef
149 * reference to {@link SchemaContext}
150 * @param transactionNode
151 * wrapper of variables for transaction
156 * @return {@link Response}
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();
163 final DOMDataTreeReadWriteTransaction readWriteTransaction =
164 transactionNode.getTransactionChain().newReadWriteTransaction();
166 final FluentFuture<Boolean> existsFuture = readWriteTransaction.exists(LogicalDatastoreType.CONFIGURATION,
168 final FutureDataFactory<Boolean> existsResponse = new FutureDataFactory<>();
169 FutureCallbackTx.addCallback(existsFuture, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, existsResponse);
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();
184 * @param schemaContext
185 * {@link SchemaContext}
186 * @param transactionChainHandler
194 * @return {@link FluentFuture}
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);
204 final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
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);
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();
222 final NormalizedNode<?, ?> readData =
223 readList(path, schemaContext, transactionChainHandler, schemaNode);
225 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
226 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
227 return makePut(path, schemaContext, readWriteTransaction, data);
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();
238 return makePut(path, schemaContext, readWriteTransaction, data);
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);
247 insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION, path,
248 data, schemaContext, point, readList, true);
249 return readWriteTransaction.commit();
252 final NormalizedNode<?, ?> readData =
253 readList(path, schemaContext, transactionChainHandler, schemaNode);
255 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
256 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
257 return makePut(path, schemaContext, readWriteTransaction, data);
259 insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
260 path, data, schemaContext, point, readLeafList, true);
261 return readWriteTransaction.commit();
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);
272 insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
273 path, data, schemaContext, point, readList, false);
274 return readWriteTransaction.commit();
277 final NormalizedNode<?, ?> readData =
278 readList(path, schemaContext, transactionChainHandler, schemaNode);
280 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
281 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
282 return makePut(path, schemaContext, readWriteTransaction, data);
284 insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
285 path, data, schemaContext, point, readLeafList, true);
286 return readWriteTransaction.commit();
290 throw new RestconfDocumentedException(
291 "Used bad value of insert parameter. Possible values are first, last, before or after, "
292 + "but was: " + insert, RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE);
296 public static NormalizedNode<?, ?> readList(final YangInstanceIdentifier path, final SchemaContext schemaContext,
297 final TransactionChainHandler transactionChainHandler, final DataSchemaNode schemaNode) {
298 final InstanceIdentifierContext<?> iid = new InstanceIdentifierContext<SchemaNode>(
299 path.getParent(), schemaNode, null, schemaContext);
300 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(iid, null, transactionChainHandler);
301 final NormalizedNode<?, ?> readData = ReadDataTransactionUtil
302 .readData(RestconfDataServiceConstant.ReadData.CONFIG, transactionNode, schemaContext);
306 private static void insertWithPointLeafListPut(final DOMDataTreeReadWriteTransaction rwTransaction,
307 final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
308 final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
309 final OrderedLeafSetNode<?> readLeafList, final boolean before) {
310 rwTransaction.delete(datastore, path.getParent());
311 final InstanceIdentifierContext<?> instanceIdentifier =
312 ParserIdentifier.toInstanceIdentifier(point, schemaContext, Optional.empty());
313 int lastItemPosition = 0;
314 for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
315 if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
323 int lastInsertedPosition = 0;
324 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
325 rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
326 for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
327 if (lastInsertedPosition == lastItemPosition) {
328 simplePut(datastore, path, rwTransaction, schemaContext, data);
330 final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
331 rwTransaction.put(datastore, childPath, nodeChild);
332 lastInsertedPosition++;
336 private static void insertWithPointListPut(final DOMDataTreeReadWriteTransaction writeTx,
337 final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
338 final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
339 final OrderedMapNode readList, final boolean before) {
340 writeTx.delete(datastore, path.getParent());
341 final InstanceIdentifierContext<?> instanceIdentifier =
342 ParserIdentifier.toInstanceIdentifier(point, schemaContext, Optional.empty());
343 int lastItemPosition = 0;
344 for (final MapEntryNode mapEntryNode : readList.getValue()) {
345 if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
353 int lastInsertedPosition = 0;
354 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
355 writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
356 for (final MapEntryNode mapEntryNode : readList.getValue()) {
357 if (lastInsertedPosition == lastItemPosition) {
358 simplePut(datastore, path, writeTx, schemaContext, data);
360 final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
361 writeTx.put(datastore, childPath, mapEntryNode);
362 lastInsertedPosition++;
366 private static void listPut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
367 final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
368 final OrderedLeafSetNode<?> payload) {
369 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
370 writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
371 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
372 for (final LeafSetEntryNode<?> child : ((LeafSetNode<?>) payload).getValue()) {
373 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
374 writeTx.put(datastore, childPath, child);
378 private static void listPut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
379 final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
380 final OrderedMapNode payload) {
381 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
382 writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
383 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
384 for (final MapEntryNode child : payload.getValue()) {
385 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
386 writeTx.put(datastore, childPath, child);
390 private static void simplePut(final LogicalDatastoreType configuration, final YangInstanceIdentifier path,
391 final DOMDataTreeWriteTransaction writeTx, final SchemaContext schemaContext,
392 final NormalizedNode<?, ?> data) {
393 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
394 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
397 private static FluentFuture<? extends CommitInfo> makePut(final YangInstanceIdentifier path,
398 final SchemaContext schemaContext, final DOMDataTreeWriteTransaction writeTx,
399 final NormalizedNode<?, ?> data) {
400 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
401 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
402 return writeTx.commit();
405 public static DataSchemaNode checkListAndOrderedType(final SchemaContext ctx, final YangInstanceIdentifier path) {
406 final YangInstanceIdentifier parent = path.getParent();
407 final DataSchemaContextNode<?> node = DataSchemaContextTree.from(ctx).getChild(parent);
408 final DataSchemaNode dataSchemaNode = node.getDataSchemaNode();
410 if (dataSchemaNode instanceof ListSchemaNode) {
411 if (!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
412 throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user list.",
413 RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
415 return dataSchemaNode;
417 if (dataSchemaNode instanceof LeafListSchemaNode) {
418 if (!((LeafListSchemaNode) dataSchemaNode).isUserOrdered()) {
419 throw new RestconfDocumentedException(
420 "Insert parameter can be used only with ordered-by user leaf-list.",
421 RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
423 return dataSchemaNode;
425 throw new RestconfDocumentedException("Insert parameter can be used only with list or leaf-list",
426 RestconfError.ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);