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.base.Optional;
11 import com.google.common.collect.Maps;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import java.util.List;
15 import javax.ws.rs.core.Response;
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.controller.md.sal.dom.api.DOMTransactionChain;
23 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
24 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
25 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
26 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
28 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
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.MapNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
44 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
45 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
53 * Util class for put data to DS.
56 public final class PutDataTransactionUtil {
58 private PutDataTransactionUtil() {
63 * Valid input data with {@link SchemaNode}.
70 public static void validInputData(final SchemaNode schemaNode, final NormalizedNodeContext payload) {
71 if (schemaNode != null && payload.getData() == null) {
72 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
73 } else if (schemaNode == null && payload.getData() != null) {
74 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
79 * Valid top level node name.
86 public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
87 final String payloadName = payload.getData().getNodeType().getLocalName();
90 if (!payload.getData().getNodeType().equals(RestconfDataServiceConstant.NETCONF_BASE_QNAME)) {
91 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
92 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
95 final String identifierName = path.getLastPathArgument().getNodeType().getLocalName();
96 if (!payloadName.equals(identifierName)) {
97 throw new RestconfDocumentedException(
98 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
99 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
105 * Validates whether keys in {@code payload} are equal to values of keys in
106 * {@code iiWithData} for list schema node.
108 * @throws RestconfDocumentedException
109 * if key values or key count in payload and URI isn't equal
111 public static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
112 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
113 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
114 final SchemaNode schemaNode = iiWithData.getSchemaNode();
115 final NormalizedNode<?, ?> data = payload.getData();
116 if (schemaNode instanceof ListSchemaNode) {
117 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
118 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
119 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
121 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
126 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
127 final List<QName> keyDefinitions) {
128 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
129 for (final QName keyDefinition : keyDefinitions) {
130 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
131 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
132 "Missing key " + keyDefinition + " in URI.");
134 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
136 if (!uriKeyValue.equals(dataKeyValue)) {
137 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
138 + "' specified in the URI doesn't match the value '" + dataKeyValue
139 + "' specified in the message body. ";
140 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
146 * Check mount point and prepare variables for put data to DS.
150 * @param schemaCtxRef
151 * reference to {@link SchemaContext}
152 * @param transactionNode
153 * wrapper of variables for transaction
158 * @return {@link CheckedFuture}
160 public static Response putData(final NormalizedNodeContext payload, final SchemaContextRef schemaCtxRef,
161 final TransactionVarsWrapper transactionNode, final String insert, final String point) {
162 final YangInstanceIdentifier path = payload.getInstanceIdentifierContext().getInstanceIdentifier();
163 final SchemaContext schemaContext = schemaCtxRef.get();
165 final DOMDataReadWriteTransaction readWriteTransaction =
166 transactionNode.getTransactionChain().newReadWriteTransaction();
168 final CheckedFuture<Boolean, ReadFailedException> existsFuture =
169 readWriteTransaction.exists(LogicalDatastoreType.CONFIGURATION, path);
170 final FutureDataFactory<Boolean> existsResponse = new FutureDataFactory<>();
171 FutureCallbackTx.addCallback(existsFuture, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, existsResponse);
173 final ResponseFactory responseFactory =
174 new ResponseFactory(existsResponse.result ? Status.NO_CONTENT : Status.CREATED);
175 final CheckedFuture<Void, TransactionCommitFailedException> submitData = submitData(path, schemaContext,
176 transactionNode.getTransactionChain(), readWriteTransaction, payload.getData(), insert, point);
177 FutureCallbackTx.addCallback(submitData, RestconfDataServiceConstant.PutData.PUT_TX_TYPE, responseFactory);
178 return responseFactory.build();
186 * @param schemaContext
187 * {@link SchemaContext}
188 * @param domTransactionChain
196 * @return {@link CheckedFuture}
198 private static CheckedFuture<Void, TransactionCommitFailedException> submitData(final YangInstanceIdentifier path,
199 final SchemaContext schemaContext, final DOMTransactionChain domTransactionChain,
200 final DOMDataReadWriteTransaction readWriteTransaction,
201 final NormalizedNode<?, ?> data, final String insert, final String point) {
202 if (insert == null) {
203 return makePut(path, schemaContext, readWriteTransaction, data);
205 final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
208 if (schemaNode instanceof ListSchemaNode) {
209 final NormalizedNode<?, ?> readData =
210 readList(path, schemaContext, domTransactionChain, schemaNode);
211 final OrderedMapNode readList = (OrderedMapNode) readData;
212 if (readList == null || readList.getValue().isEmpty()) {
213 return makePut(path, schemaContext, readWriteTransaction, data);
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.submit();
223 final NormalizedNode<?, ?> readData =
224 readList(path, schemaContext, domTransactionChain, schemaNode);
226 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
227 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
228 return makePut(path, schemaContext, readWriteTransaction, data);
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.submit();
239 return makePut(path, schemaContext, readWriteTransaction, data);
241 if (schemaNode instanceof ListSchemaNode) {
242 final NormalizedNode<?, ?> readData =
243 readList(path, schemaContext, domTransactionChain, schemaNode);
244 final OrderedMapNode readList = (OrderedMapNode) readData;
245 if (readList == null || readList.getValue().isEmpty()) {
246 return makePut(path, schemaContext, readWriteTransaction, data);
248 insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION, path,
249 data, schemaContext, point, readList, true);
250 return readWriteTransaction.submit();
253 final NormalizedNode<?, ?> readData =
254 readList(path, schemaContext, domTransactionChain, schemaNode);
256 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
257 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
258 return makePut(path, schemaContext, readWriteTransaction, data);
260 insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
261 path, data, schemaContext, point, readLeafList, true);
262 return readWriteTransaction.submit();
266 if (schemaNode instanceof ListSchemaNode) {
267 final NormalizedNode<?, ?> readData =
268 readList(path, schemaContext, domTransactionChain, schemaNode);
269 final OrderedMapNode readList = (OrderedMapNode) readData;
270 if (readList == null || readList.getValue().isEmpty()) {
271 return makePut(path, schemaContext, readWriteTransaction, data);
273 insertWithPointListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
274 path, data, schemaContext, point, readList, false);
275 return readWriteTransaction.submit();
278 final NormalizedNode<?, ?> readData =
279 readList(path, schemaContext, domTransactionChain, schemaNode);
281 final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
282 if (readLeafList == null || readLeafList.getValue().isEmpty()) {
283 return makePut(path, schemaContext, readWriteTransaction, data);
285 insertWithPointLeafListPut(readWriteTransaction, LogicalDatastoreType.CONFIGURATION,
286 path, data, schemaContext, point, readLeafList, true);
287 return readWriteTransaction.submit();
291 throw new RestconfDocumentedException(
292 "Used bad value of insert parameter. Possible values are first, last, before or after, "
293 + "but was: " + insert);
298 public static NormalizedNode<?, ?> readList(final YangInstanceIdentifier path, final SchemaContext schemaContext,
299 final DOMTransactionChain domTransactionChain, final DataSchemaNode schemaNode) {
300 final InstanceIdentifierContext<?> iid = new InstanceIdentifierContext<SchemaNode>(
301 path.getParent(), schemaNode, null, schemaContext);
302 final TransactionVarsWrapper transactionNode =
303 new TransactionVarsWrapper(iid, null, domTransactionChain);
304 final NormalizedNode<?, ?> readData = ReadDataTransactionUtil
305 .readData(RestconfDataServiceConstant.ReadData.CONFIG, transactionNode, schemaContext);
309 private static void insertWithPointLeafListPut(final DOMDataReadWriteTransaction 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.absent());
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 DOMDataReadWriteTransaction 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.absent());
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 DOMDataReadWriteTransaction 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 DOMDataReadWriteTransaction 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 : ((MapNode) 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 DOMDataReadWriteTransaction writeTx, final SchemaContext schemaContext,
395 final NormalizedNode<?, ?> data) {
396 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
397 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
400 private static CheckedFuture<Void, TransactionCommitFailedException> makePut(final YangInstanceIdentifier path,
401 final SchemaContext schemaContext, final DOMDataWriteTransaction writeTx, final NormalizedNode<?, ?> data) {
402 TransactionUtil.ensureParentsByMerge(path, schemaContext, writeTx);
403 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
404 return writeTx.submit();
407 public static DataSchemaNode checkListAndOrderedType(final SchemaContext ctx, final YangInstanceIdentifier path) {
408 final YangInstanceIdentifier parent = path.getParent();
409 final DataSchemaContextNode<?> node = DataSchemaContextTree.from(ctx).getChild(parent);
410 final DataSchemaNode dataSchemaNode = node.getDataSchemaNode();
412 if (dataSchemaNode instanceof ListSchemaNode) {
413 if (!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
414 throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user list.");
416 return dataSchemaNode;
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.");
423 return dataSchemaNode;
425 throw new RestconfDocumentedException("Insert parameter can be used only with list or leaf-list");