Add representations of RFC8040 query parameters
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfDataServiceImpl.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.services.impl;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.NOTIFICATION_STREAM;
12 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAMS_PATH;
13 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART;
14 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART;
15 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
16 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH_PART;
17
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.net.URI;
23 import java.time.Clock;
24 import java.time.LocalDateTime;
25 import java.time.format.DateTimeFormatter;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.concurrent.CancellationException;
32 import java.util.concurrent.ExecutionException;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.Response.Status;
36 import javax.ws.rs.core.UriInfo;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
39 import org.opendaylight.mdsal.dom.api.DOMActionException;
40 import org.opendaylight.mdsal.dom.api.DOMActionResult;
41 import org.opendaylight.mdsal.dom.api.DOMActionService;
42 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
46 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
47 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
48 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
49 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
50 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
51 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
52 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
53 import org.opendaylight.restconf.common.patch.PatchContext;
54 import org.opendaylight.restconf.common.patch.PatchStatusContext;
55 import org.opendaylight.restconf.nb.rfc8040.InsertParameter;
56 import org.opendaylight.restconf.nb.rfc8040.PointParameter;
57 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
58 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
59 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
60 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
61 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService;
62 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
63 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
64 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
65 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
66 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
67 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PlainPatchDataTransactionUtil;
68 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
69 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
70 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
71 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
72 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
73 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
74 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
75 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
76 import org.opendaylight.yangtools.concepts.Immutable;
77 import org.opendaylight.yangtools.yang.common.ErrorTag;
78 import org.opendaylight.yangtools.yang.common.ErrorType;
79 import org.opendaylight.yangtools.yang.common.QName;
80 import org.opendaylight.yangtools.yang.common.Revision;
81 import org.opendaylight.yangtools.yang.common.RpcError;
82 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
89 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
90 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
91 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98
99 /**
100  * Implementation of {@link RestconfDataService}.
101  */
102 @Path("/")
103 public class RestconfDataServiceImpl implements RestconfDataService {
104     // FIXME: we should be able to interpret 'point' and refactor this class into a behavior
105     private static final class QueryParams implements Immutable {
106         final @Nullable PointParameter point;
107         final @Nullable InsertParameter insert;
108
109         QueryParams(final @Nullable InsertParameter insert, final @Nullable PointParameter point) {
110             this.insert = insert;
111             this.point = point;
112         }
113     }
114
115     private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
116     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
117     private static final QName NETCONF_BASE_QNAME = SchemaContext.NAME;
118
119     private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
120     private final SchemaContextHandler schemaContextHandler;
121     private final MdsalRestconfStrategy restconfStrategy;
122     private final DOMMountPointService mountPointService;
123     private final SubscribeToStreamUtil streamUtils;
124     private final DOMActionService actionService;
125     private final DOMDataBroker dataBroker;
126
127     public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
128             final DOMDataBroker dataBroker, final DOMMountPointService  mountPointService,
129             final RestconfStreamsSubscriptionService delegRestconfSubscrService,
130             final DOMActionService actionService, final Configuration configuration) {
131         this.schemaContextHandler = requireNonNull(schemaContextHandler);
132         this.dataBroker = requireNonNull(dataBroker);
133         restconfStrategy = new MdsalRestconfStrategy(dataBroker);
134         this.mountPointService = requireNonNull(mountPointService);
135         this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
136         this.actionService = requireNonNull(actionService);
137         streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
138                 : SubscribeToStreamUtil.webSockets();
139     }
140
141     @Override
142     public Response readData(final UriInfo uriInfo) {
143         return readData(null, uriInfo);
144     }
145
146     @Override
147     public Response readData(final String identifier, final UriInfo uriInfo) {
148         final EffectiveModelContext schemaContextRef = schemaContextHandler.get();
149         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
150                 identifier, schemaContextRef, Optional.of(mountPointService));
151         final QueryParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
152
153         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
154
155         // FIXME: this looks quite crazy, why do we even have it?
156         if (mountPoint == null && identifier != null && identifier.contains(STREAMS_PATH)
157             && !identifier.contains(STREAM_PATH_PART)) {
158             createAllYangNotificationStreams(schemaContextRef, uriInfo);
159         }
160
161         final List<YangInstanceIdentifier> fieldPaths = parameters.getFieldPaths();
162         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
163         final NormalizedNode node;
164         if (fieldPaths != null && !fieldPaths.isEmpty()) {
165             node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
166                     strategy, parameters.getWithDefault(), schemaContextRef, fieldPaths);
167         } else {
168             node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
169                     strategy, parameters.getWithDefault(), schemaContextRef);
170         }
171
172         // FIXME: this is utter craziness, refactor it properly!
173         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
174                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
175             final String value = (String) node.body();
176             final String streamName = value.substring(value.indexOf(NOTIFICATION_STREAM + '/'));
177             delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
178         }
179         if (node == null) {
180             throw new RestconfDocumentedException(
181                     "Request could not be completed because the relevant data model content does not exist",
182                     ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
183         }
184
185         switch (parameters.getContent()) {
186             case ALL:
187             case CONFIG:
188                 final QName type = node.getIdentifier().getNodeType();
189                 return Response.status(Status.OK)
190                     .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
191                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
192                         + "-" + type.getLocalName() + '"')
193                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
194                     .build();
195             default:
196                 return Response.status(Status.OK)
197                     .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
198                     .build();
199         }
200     }
201
202     private void createAllYangNotificationStreams(final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
203         final DOMDataTreeWriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
204         for (final NotificationDefinition notificationDefinition : schemaContext.getNotifications()) {
205             writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
206                 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
207                     NotificationOutputType.XML));
208             writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
209                 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
210                     NotificationOutputType.JSON));
211         }
212         try {
213             transaction.commit().get();
214         } catch (final InterruptedException | ExecutionException e) {
215             throw new RestconfDocumentedException("Problem while putting data to DS.", e);
216         }
217     }
218
219     private void writeNotificationStreamToDatastore(final EffectiveModelContext schemaContext,
220             final UriInfo uriInfo, final DOMDataTreeWriteOperations tx, final NotificationListenerAdapter listener) {
221         final URI uri = streamUtils.prepareUriByStreamName(uriInfo, listener.getStreamName());
222         final MapEntryNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
223                 listener.getSchemaPath().lastNodeIdentifier(), schemaContext.getNotifications(), null,
224                 listener.getOutputType(), uri);
225
226         tx.merge(LogicalDatastoreType.OPERATIONAL,
227             Rfc8040.restconfStateStreamPath(mapToStreams.getIdentifier()), mapToStreams);
228     }
229
230     @Override
231     public Response putData(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo) {
232         requireNonNull(payload);
233
234         final QueryParams checkedParms = checkQueryParameters(uriInfo);
235
236         final InstanceIdentifierContext<? extends SchemaNode> iid = payload.getInstanceIdentifierContext();
237
238         validInputData(iid.getSchemaNode(), payload);
239         validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
240         validateListKeysEqualityInPayloadAndUri(payload);
241
242         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
243         final EffectiveModelContext ref = mountPoint == null
244                 ? schemaContextHandler.get() : modelContext(mountPoint);
245
246         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
247         return PutDataTransactionUtil.putData(payload, ref, strategy, checkedParms.insert, checkedParms.point);
248     }
249
250     private static QueryParams checkQueryParameters(final UriInfo uriInfo) {
251         boolean insertUsed = false;
252         boolean pointUsed = false;
253         InsertParameter insert = null;
254         PointParameter point = null;
255
256         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
257             final String uriName = entry.getKey();
258             if (InsertParameter.uriName().equals(uriName)) {
259                 if (insertUsed) {
260                     throw new RestconfDocumentedException("Insert parameter can be used only once.",
261                         ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
262                 }
263
264                 insertUsed = true;
265                 final String str = entry.getValue().get(0);
266                 insert = InsertParameter.forUriValue(str);
267                 if (insert == null) {
268                     throw new RestconfDocumentedException("Unrecognized insert parameter value '" + str + "'",
269                         ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
270                 }
271             } else if (PointParameter.uriName().equals(uriName)) {
272                 if (pointUsed) {
273                     throw new RestconfDocumentedException("Point parameter can be used only once.",
274                         ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
275                 }
276
277                 pointUsed = true;
278                 point = PointParameter.forUriValue(entry.getValue().get(0));
279             } else {
280                 throw new RestconfDocumentedException("Bad parameter for post: " + uriName,
281                     ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
282             }
283         }
284
285         checkQueryParams(insertUsed, pointUsed, insert);
286         return new QueryParams(insert, point);
287     }
288
289     private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed,
290             final InsertParameter insert) {
291         if (pointUsed) {
292             if (!insertUsed) {
293                 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.",
294                     ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
295             }
296             if (insert != InsertParameter.BEFORE && insert != InsertParameter.AFTER) {
297                 throw new RestconfDocumentedException(
298                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
299                     ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
300             }
301         }
302     }
303
304     @Override
305     public Response postData(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo) {
306         return postData(payload, uriInfo);
307     }
308
309     @Override
310     public Response postData(final NormalizedNodePayload payload, final UriInfo uriInfo) {
311         requireNonNull(payload);
312         if (payload.getInstanceIdentifierContext().getSchemaNode() instanceof ActionDefinition) {
313             return invokeAction(payload);
314         }
315
316         final QueryParams checkedParms = checkQueryParameters(uriInfo);
317         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
318         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
319         return PostDataTransactionUtil.postData(uriInfo, payload, strategy,
320                 getSchemaContext(mountPoint), checkedParms.insert, checkedParms.point);
321     }
322
323     @Override
324     public Response deleteData(final String identifier) {
325         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
326                 identifier, schemaContextHandler.get(), Optional.of(mountPointService));
327
328         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
329         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
330         return DeleteDataTransactionUtil.deleteData(strategy, instanceIdentifier.getInstanceIdentifier());
331     }
332
333     @Override
334     public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
335         return patchData(context, uriInfo);
336     }
337
338     @Override
339     public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
340         final DOMMountPoint mountPoint = RestconfDocumentedException.throwIfNull(context,
341             ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "No patch documented provided")
342             .getInstanceIdentifierContext().getMountPoint();
343         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
344         return PatchDataTransactionUtil.patchData(context, strategy, getSchemaContext(mountPoint));
345     }
346
347     @Override
348     public Response patchData(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo) {
349         requireNonNull(payload);
350
351         final InstanceIdentifierContext<? extends SchemaNode> iid = payload.getInstanceIdentifierContext();
352         validInputData(iid.getSchemaNode(), payload);
353         validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
354         validateListKeysEqualityInPayloadAndUri(payload);
355
356         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
357         final EffectiveModelContext ref = mountPoint == null
358                 ? schemaContextHandler.get() : modelContext(mountPoint);
359         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
360
361         return PlainPatchDataTransactionUtil.patchData(payload, strategy, ref);
362     }
363
364     private EffectiveModelContext getSchemaContext(final DOMMountPoint mountPoint) {
365         return mountPoint == null ? schemaContextHandler.get() : modelContext(mountPoint);
366     }
367
368     // FIXME: why is this synchronized?
369     public synchronized RestconfStrategy getRestconfStrategy(final DOMMountPoint mountPoint) {
370         if (mountPoint == null) {
371             return restconfStrategy;
372         }
373
374         return RestconfStrategy.forMountPoint(mountPoint).orElseThrow(() -> {
375             LOG.warn("Mount point {} does not expose a suitable access interface", mountPoint.getIdentifier());
376             return new RestconfDocumentedException("Could not find a supported access interface in mount point "
377                 + mountPoint.getIdentifier());
378         });
379     }
380
381     /**
382      * Invoke Action operation.
383      *
384      * @param payload {@link NormalizedNodeContext} - the body of the operation
385      * @return {@link NormalizedNodeContext} wrapped in {@link Response}
386      */
387     public Response invokeAction(final NormalizedNodeContext payload) {
388         final InstanceIdentifierContext<?> context = payload.getInstanceIdentifierContext();
389         final DOMMountPoint mountPoint = context.getMountPoint();
390         final Absolute schemaPath = Absolute.of(ImmutableList.copyOf(context.getSchemaNode().getPath()
391             .getPathFromRoot()));
392         final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
393         final NormalizedNode data = payload.getData();
394
395         if (yangIIdContext.isEmpty() && !NETCONF_BASE_QNAME.equals(data.getIdentifier().getNodeType())) {
396             throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument",
397                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
398         }
399
400         final DOMActionResult response;
401         final EffectiveModelContext schemaContextRef;
402         if (mountPoint != null) {
403             response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, mountPoint);
404             schemaContextRef = modelContext(mountPoint);
405         } else {
406             response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, actionService);
407             schemaContextRef = schemaContextHandler.get();
408         }
409         final DOMActionResult result = checkActionResponse(response);
410
411         ActionDefinition resultNodeSchema = null;
412         ContainerNode resultData = null;
413         if (result != null) {
414             final Optional<ContainerNode> optOutput = result.getOutput();
415             if (optOutput.isPresent()) {
416                 resultData = optOutput.get();
417                 resultNodeSchema = (ActionDefinition) context.getSchemaNode();
418             }
419         }
420
421         if (resultData != null && resultData.isEmpty()) {
422             return Response.status(Status.NO_CONTENT).build();
423         }
424
425         return Response.status(Status.OK)
426             .entity(new NormalizedNodeContext(
427                 new InstanceIdentifierContext<>(yangIIdContext, resultNodeSchema, mountPoint, schemaContextRef),
428                 resultData))
429             .build();
430     }
431
432
433     /**
434      * Invoking Action via mount point.
435      *
436      * @param mountPoint mount point
437      * @param data input data
438      * @param schemaPath schema path of data
439      * @return {@link DOMActionResult}
440      */
441     private static DOMActionResult invokeAction(final ContainerNode data,
442             final Absolute schemaPath, final YangInstanceIdentifier yangIId, final DOMMountPoint mountPoint) {
443         return invokeAction(data, schemaPath, yangIId, mountPoint.getService(DOMActionService.class)
444             .orElseThrow(() -> new RestconfDocumentedException("DomAction service is missing.")));
445     }
446
447     /**
448      * Invoke Action via ActionServiceHandler.
449      *
450      * @param data input data
451      * @param yangIId invocation context
452      * @param schemaPath schema path of data
453      * @param actionService action service to invoke action
454      * @return {@link DOMActionResult}
455      */
456     // FIXME: NETCONF-718: we should be returning a future here
457     private static DOMActionResult invokeAction(final ContainerNode data, final Absolute schemaPath,
458             final YangInstanceIdentifier yangIId, final DOMActionService actionService) {
459         return RestconfInvokeOperationsServiceImpl.checkedGet(Futures.catching(actionService.invokeAction(
460             schemaPath, new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, yangIId.getParent()), data),
461             DOMActionException.class,
462             cause -> new SimpleDOMActionResult(ImmutableList.of(RpcResultBuilder.newError(
463                 RpcError.ErrorType.RPC, "operation-failed", cause.getMessage()))),
464             MoreExecutors.directExecutor()));
465     }
466
467     /**
468      * Check the validity of the result.
469      *
470      * @param response response of Action
471      * @return {@link DOMActionResult} result
472      */
473     private static DOMActionResult checkActionResponse(final DOMActionResult response) {
474         if (response == null) {
475             return null;
476         }
477
478         try {
479             if (response.getErrors().isEmpty()) {
480                 return response;
481             }
482             LOG.debug("InvokeAction Error Message {}", response.getErrors());
483             throw new RestconfDocumentedException("InvokeAction Error Message ", null, response.getErrors());
484         } catch (final CancellationException e) {
485             final String errMsg = "The Action Operation was cancelled while executing.";
486             LOG.debug("Cancel Execution: {}", errMsg, e);
487             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
488         }
489     }
490
491     /**
492      * Valid input data with {@link SchemaNode}.
493      *
494      * @param schemaNode {@link SchemaNode}
495      * @param payload    input data
496      */
497     @VisibleForTesting
498     public static void validInputData(final SchemaNode schemaNode, final NormalizedNodeContext payload) {
499         if (schemaNode != null && payload.getData() == null) {
500             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
501         } else if (schemaNode == null && payload.getData() != null) {
502             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
503         }
504     }
505
506     /**
507      * Valid top level node name.
508      *
509      * @param path    path of node
510      * @param payload data
511      */
512     @VisibleForTesting
513     public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
514         final QName dataNodeType = payload.getData().getIdentifier().getNodeType();
515         if (path.isEmpty()) {
516             if (!NETCONF_BASE_QNAME.equals(dataNodeType)) {
517                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
518                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
519             }
520         } else {
521             final String identifierName = path.getLastPathArgument().getNodeType().getLocalName();
522             final String payloadName = dataNodeType.getLocalName();
523             if (!payloadName.equals(identifierName)) {
524                 throw new RestconfDocumentedException(
525                         "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
526                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
527             }
528         }
529     }
530
531
532     /**
533      * Validates whether keys in {@code payload} are equal to values of keys in
534      * {@code iiWithData} for list schema node.
535      *
536      * @throws RestconfDocumentedException if key values or key count in payload and URI isn't equal
537      */
538     @VisibleForTesting
539     public static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
540         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
541         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
542         final SchemaNode schemaNode = iiWithData.getSchemaNode();
543         final NormalizedNode data = payload.getData();
544         if (schemaNode instanceof ListSchemaNode) {
545             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
546             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
547                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
548                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
549             }
550         }
551     }
552
553     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
554             final List<QName> keyDefinitions) {
555         final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
556         for (final QName keyDefinition : keyDefinitions) {
557             final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
558                     mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
559                     "Missing key %s in URI.", keyDefinition);
560
561             final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
562
563             if (!uriKeyValue.equals(dataKeyValue)) {
564                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
565                         + "' specified in the URI doesn't match the value '" + dataKeyValue
566                         + "' specified in the message body. ";
567                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
568             }
569         }
570     }
571
572     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
573         return mountPoint.getService(DOMSchemaService.class)
574             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
575             .orElse(null);
576     }
577 }